* objfiles.h (gdb_bfd_close_or_warn): Declare.
[platform/upstream/binutils.git] / gdb / ax-gdb.c
1 /* GDB-specific functions for operating on agent expressions.
2
3    Copyright (C) 1998, 1999, 2000, 2001, 2003, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "symtab.h"
23 #include "symfile.h"
24 #include "gdbtypes.h"
25 #include "language.h"
26 #include "value.h"
27 #include "expression.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "frame.h"
31 #include "target.h"
32 #include "ax.h"
33 #include "ax-gdb.h"
34 #include "gdb_string.h"
35 #include "block.h"
36 #include "regcache.h"
37 #include "user-regs.h"
38 #include "language.h"
39 #include "dictionary.h"
40 #include "breakpoint.h"
41 #include "tracepoint.h"
42 #include "cp-support.h"
43
44 /* To make sense of this file, you should read doc/agentexpr.texi.
45    Then look at the types and enums in ax-gdb.h.  For the code itself,
46    look at gen_expr, towards the bottom; that's the main function that
47    looks at the GDB expressions and calls everything else to generate
48    code.
49
50    I'm beginning to wonder whether it wouldn't be nicer to internally
51    generate trees, with types, and then spit out the bytecode in
52    linear form afterwards; we could generate fewer `swap', `ext', and
53    `zero_ext' bytecodes that way; it would make good constant folding
54    easier, too.  But at the moment, I think we should be willing to
55    pay for the simplicity of this code with less-than-optimal bytecode
56    strings.
57
58    Remember, "GBD" stands for "Great Britain, Dammit!"  So be careful.  */
59 \f
60
61
62 /* Prototypes for local functions. */
63
64 /* There's a standard order to the arguments of these functions:
65    union exp_element ** --- pointer into expression
66    struct agent_expr * --- agent expression buffer to generate code into
67    struct axs_value * --- describes value left on top of stack  */
68
69 static struct value *const_var_ref (struct symbol *var);
70 static struct value *const_expr (union exp_element **pc);
71 static struct value *maybe_const_expr (union exp_element **pc);
72
73 static void gen_traced_pop (struct gdbarch *, struct agent_expr *, struct axs_value *);
74
75 static void gen_sign_extend (struct agent_expr *, struct type *);
76 static void gen_extend (struct agent_expr *, struct type *);
77 static void gen_fetch (struct agent_expr *, struct type *);
78 static void gen_left_shift (struct agent_expr *, int);
79
80
81 static void gen_frame_args_address (struct gdbarch *, struct agent_expr *);
82 static void gen_frame_locals_address (struct gdbarch *, struct agent_expr *);
83 static void gen_offset (struct agent_expr *ax, int offset);
84 static void gen_sym_offset (struct agent_expr *, struct symbol *);
85 static void gen_var_ref (struct gdbarch *, struct agent_expr *ax,
86                          struct axs_value *value, struct symbol *var);
87
88
89 static void gen_int_literal (struct agent_expr *ax,
90                              struct axs_value *value,
91                              LONGEST k, struct type *type);
92
93
94 static void require_rvalue (struct agent_expr *ax, struct axs_value *value);
95 static void gen_usual_unary (struct expression *exp, struct agent_expr *ax,
96                              struct axs_value *value);
97 static int type_wider_than (struct type *type1, struct type *type2);
98 static struct type *max_type (struct type *type1, struct type *type2);
99 static void gen_conversion (struct agent_expr *ax,
100                             struct type *from, struct type *to);
101 static int is_nontrivial_conversion (struct type *from, struct type *to);
102 static void gen_usual_arithmetic (struct expression *exp,
103                                   struct agent_expr *ax,
104                                   struct axs_value *value1,
105                                   struct axs_value *value2);
106 static void gen_integral_promotions (struct expression *exp,
107                                      struct agent_expr *ax,
108                                      struct axs_value *value);
109 static void gen_cast (struct agent_expr *ax,
110                       struct axs_value *value, struct type *type);
111 static void gen_scale (struct agent_expr *ax,
112                        enum agent_op op, struct type *type);
113 static void gen_ptradd (struct agent_expr *ax, struct axs_value *value,
114                         struct axs_value *value1, struct axs_value *value2);
115 static void gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
116                         struct axs_value *value1, struct axs_value *value2);
117 static void gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
118                          struct axs_value *value1, struct axs_value *value2,
119                          struct type *result_type);
120 static void gen_binop (struct agent_expr *ax,
121                        struct axs_value *value,
122                        struct axs_value *value1,
123                        struct axs_value *value2,
124                        enum agent_op op,
125                        enum agent_op op_unsigned, int may_carry, char *name);
126 static void gen_logical_not (struct agent_expr *ax, struct axs_value *value,
127                              struct type *result_type);
128 static void gen_complement (struct agent_expr *ax, struct axs_value *value);
129 static void gen_deref (struct agent_expr *, struct axs_value *);
130 static void gen_address_of (struct agent_expr *, struct axs_value *);
131 static void gen_bitfield_ref (struct expression *exp, struct agent_expr *ax,
132                               struct axs_value *value,
133                               struct type *type, int start, int end);
134 static void gen_primitive_field (struct expression *exp,
135                                  struct agent_expr *ax,
136                                  struct axs_value *value,
137                                  int offset, int fieldno, struct type *type);
138 static int gen_struct_ref_recursive (struct expression *exp,
139                                      struct agent_expr *ax,
140                                      struct axs_value *value,
141                                      char *field, int offset,
142                                      struct type *type);
143 static void gen_struct_ref (struct expression *exp, struct agent_expr *ax,
144                             struct axs_value *value,
145                             char *field,
146                             char *operator_name, char *operand_name);
147 static void gen_static_field (struct gdbarch *gdbarch,
148                               struct agent_expr *ax, struct axs_value *value,
149                               struct type *type, int fieldno);
150 static void gen_repeat (struct expression *exp, union exp_element **pc,
151                         struct agent_expr *ax, struct axs_value *value);
152 static void gen_sizeof (struct expression *exp, union exp_element **pc,
153                         struct agent_expr *ax, struct axs_value *value,
154                         struct type *size_type);
155 static void gen_expr (struct expression *exp, union exp_element **pc,
156                       struct agent_expr *ax, struct axs_value *value);
157 static void gen_expr_binop_rest (struct expression *exp,
158                                  enum exp_opcode op, union exp_element **pc,
159                                  struct agent_expr *ax,
160                                  struct axs_value *value,
161                                  struct axs_value *value1,
162                                  struct axs_value *value2);
163
164 static void agent_command (char *exp, int from_tty);
165 \f
166
167 /* Detecting constant expressions.  */
168
169 /* If the variable reference at *PC is a constant, return its value.
170    Otherwise, return zero.
171
172    Hey, Wally!  How can a variable reference be a constant?
173
174    Well, Beav, this function really handles the OP_VAR_VALUE operator,
175    not specifically variable references.  GDB uses OP_VAR_VALUE to
176    refer to any kind of symbolic reference: function names, enum
177    elements, and goto labels are all handled through the OP_VAR_VALUE
178    operator, even though they're constants.  It makes sense given the
179    situation.
180
181    Gee, Wally, don'cha wonder sometimes if data representations that
182    subvert commonly accepted definitions of terms in favor of heavily
183    context-specific interpretations are really just a tool of the
184    programming hegemony to preserve their power and exclude the
185    proletariat?  */
186
187 static struct value *
188 const_var_ref (struct symbol *var)
189 {
190   struct type *type = SYMBOL_TYPE (var);
191
192   switch (SYMBOL_CLASS (var))
193     {
194     case LOC_CONST:
195       return value_from_longest (type, (LONGEST) SYMBOL_VALUE (var));
196
197     case LOC_LABEL:
198       return value_from_pointer (type, (CORE_ADDR) SYMBOL_VALUE_ADDRESS (var));
199
200     default:
201       return 0;
202     }
203 }
204
205
206 /* If the expression starting at *PC has a constant value, return it.
207    Otherwise, return zero.  If we return a value, then *PC will be
208    advanced to the end of it.  If we return zero, *PC could be
209    anywhere.  */
210 static struct value *
211 const_expr (union exp_element **pc)
212 {
213   enum exp_opcode op = (*pc)->opcode;
214   struct value *v1;
215
216   switch (op)
217     {
218     case OP_LONG:
219       {
220         struct type *type = (*pc)[1].type;
221         LONGEST k = (*pc)[2].longconst;
222         (*pc) += 4;
223         return value_from_longest (type, k);
224       }
225
226     case OP_VAR_VALUE:
227       {
228         struct value *v = const_var_ref ((*pc)[2].symbol);
229         (*pc) += 4;
230         return v;
231       }
232
233       /* We could add more operators in here.  */
234
235     case UNOP_NEG:
236       (*pc)++;
237       v1 = const_expr (pc);
238       if (v1)
239         return value_neg (v1);
240       else
241         return 0;
242
243     default:
244       return 0;
245     }
246 }
247
248
249 /* Like const_expr, but guarantee also that *PC is undisturbed if the
250    expression is not constant.  */
251 static struct value *
252 maybe_const_expr (union exp_element **pc)
253 {
254   union exp_element *tentative_pc = *pc;
255   struct value *v = const_expr (&tentative_pc);
256
257   /* If we got a value, then update the real PC.  */
258   if (v)
259     *pc = tentative_pc;
260
261   return v;
262 }
263 \f
264
265 /* Generating bytecode from GDB expressions: general assumptions */
266
267 /* Here are a few general assumptions made throughout the code; if you
268    want to make a change that contradicts one of these, then you'd
269    better scan things pretty thoroughly.
270
271    - We assume that all values occupy one stack element.  For example,
272    sometimes we'll swap to get at the left argument to a binary
273    operator.  If we decide that void values should occupy no stack
274    elements, or that synthetic arrays (whose size is determined at
275    run time, created by the `@' operator) should occupy two stack
276    elements (address and length), then this will cause trouble.
277
278    - We assume the stack elements are infinitely wide, and that we
279    don't have to worry what happens if the user requests an
280    operation that is wider than the actual interpreter's stack.
281    That is, it's up to the interpreter to handle directly all the
282    integer widths the user has access to.  (Woe betide the language
283    with bignums!)
284
285    - We don't support side effects.  Thus, we don't have to worry about
286    GCC's generalized lvalues, function calls, etc.
287
288    - We don't support floating point.  Many places where we switch on
289    some type don't bother to include cases for floating point; there
290    may be even more subtle ways this assumption exists.  For
291    example, the arguments to % must be integers.
292
293    - We assume all subexpressions have a static, unchanging type.  If
294    we tried to support convenience variables, this would be a
295    problem.
296
297    - All values on the stack should always be fully zero- or
298    sign-extended.
299
300    (I wasn't sure whether to choose this or its opposite --- that
301    only addresses are assumed extended --- but it turns out that
302    neither convention completely eliminates spurious extend
303    operations (if everything is always extended, then you have to
304    extend after add, because it could overflow; if nothing is
305    extended, then you end up producing extends whenever you change
306    sizes), and this is simpler.)  */
307 \f
308
309 /* Generating bytecode from GDB expressions: the `trace' kludge  */
310
311 /* The compiler in this file is a general-purpose mechanism for
312    translating GDB expressions into bytecode.  One ought to be able to
313    find a million and one uses for it.
314
315    However, at the moment it is HOPELESSLY BRAIN-DAMAGED for the sake
316    of expediency.  Let he who is without sin cast the first stone.
317
318    For the data tracing facility, we need to insert `trace' bytecodes
319    before each data fetch; this records all the memory that the
320    expression touches in the course of evaluation, so that memory will
321    be available when the user later tries to evaluate the expression
322    in GDB.
323
324    This should be done (I think) in a post-processing pass, that walks
325    an arbitrary agent expression and inserts `trace' operations at the
326    appropriate points.  But it's much faster to just hack them
327    directly into the code.  And since we're in a crunch, that's what
328    I've done.
329
330    Setting the flag trace_kludge to non-zero enables the code that
331    emits the trace bytecodes at the appropriate points.  */
332 static int trace_kludge;
333
334 /* Scan for all static fields in the given class, including any base
335    classes, and generate tracing bytecodes for each.  */
336
337 static void
338 gen_trace_static_fields (struct gdbarch *gdbarch,
339                          struct agent_expr *ax,
340                          struct type *type)
341 {
342   int i, nbases = TYPE_N_BASECLASSES (type);
343   struct axs_value value;
344
345   CHECK_TYPEDEF (type);
346
347   for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
348     {
349       if (field_is_static (&TYPE_FIELD (type, i)))
350         {
351           gen_static_field (gdbarch, ax, &value, type, i);
352           if (value.optimized_out)
353             continue;
354           switch (value.kind)
355             {
356             case axs_lvalue_memory:
357               {
358                 int length = TYPE_LENGTH (check_typedef (value.type));
359
360                 ax_const_l (ax, length);
361                 ax_simple (ax, aop_trace);
362               }
363               break;
364
365             case axs_lvalue_register:
366               /* We need to mention the register somewhere in the bytecode,
367                  so ax_reqs will pick it up and add it to the mask of
368                  registers used.  */
369               ax_reg (ax, value.u.reg);
370
371             default:
372               break;
373             }
374         }
375     }
376
377   /* Now scan through base classes recursively.  */
378   for (i = 0; i < nbases; i++)
379     {
380       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
381
382       gen_trace_static_fields (gdbarch, ax, basetype);
383     }
384 }
385
386 /* Trace the lvalue on the stack, if it needs it.  In either case, pop
387    the value.  Useful on the left side of a comma, and at the end of
388    an expression being used for tracing.  */
389 static void
390 gen_traced_pop (struct gdbarch *gdbarch,
391                 struct agent_expr *ax, struct axs_value *value)
392 {
393   if (trace_kludge)
394     switch (value->kind)
395       {
396       case axs_rvalue:
397         /* We don't trace rvalues, just the lvalues necessary to
398            produce them.  So just dispose of this value.  */
399         ax_simple (ax, aop_pop);
400         break;
401
402       case axs_lvalue_memory:
403         {
404           int length = TYPE_LENGTH (check_typedef (value->type));
405
406           /* There's no point in trying to use a trace_quick bytecode
407              here, since "trace_quick SIZE pop" is three bytes, whereas
408              "const8 SIZE trace" is also three bytes, does the same
409              thing, and the simplest code which generates that will also
410              work correctly for objects with large sizes.  */
411           ax_const_l (ax, length);
412           ax_simple (ax, aop_trace);
413         }
414         break;
415
416       case axs_lvalue_register:
417         /* We need to mention the register somewhere in the bytecode,
418            so ax_reqs will pick it up and add it to the mask of
419            registers used.  */
420         ax_reg (ax, value->u.reg);
421         ax_simple (ax, aop_pop);
422         break;
423       }
424   else
425     /* If we're not tracing, just pop the value.  */
426     ax_simple (ax, aop_pop);
427
428   /* To trace C++ classes with static fields stored elsewhere.  */
429   if (trace_kludge
430       && (TYPE_CODE (value->type) == TYPE_CODE_STRUCT
431           || TYPE_CODE (value->type) == TYPE_CODE_UNION))
432     gen_trace_static_fields (gdbarch, ax, value->type);
433 }
434 \f
435
436
437 /* Generating bytecode from GDB expressions: helper functions */
438
439 /* Assume that the lower bits of the top of the stack is a value of
440    type TYPE, and the upper bits are zero.  Sign-extend if necessary.  */
441 static void
442 gen_sign_extend (struct agent_expr *ax, struct type *type)
443 {
444   /* Do we need to sign-extend this?  */
445   if (!TYPE_UNSIGNED (type))
446     ax_ext (ax, TYPE_LENGTH (type) * TARGET_CHAR_BIT);
447 }
448
449
450 /* Assume the lower bits of the top of the stack hold a value of type
451    TYPE, and the upper bits are garbage.  Sign-extend or truncate as
452    needed.  */
453 static void
454 gen_extend (struct agent_expr *ax, struct type *type)
455 {
456   int bits = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
457   /* I just had to.  */
458   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, bits));
459 }
460
461
462 /* Assume that the top of the stack contains a value of type "pointer
463    to TYPE"; generate code to fetch its value.  Note that TYPE is the
464    target type, not the pointer type.  */
465 static void
466 gen_fetch (struct agent_expr *ax, struct type *type)
467 {
468   if (trace_kludge)
469     {
470       /* Record the area of memory we're about to fetch.  */
471       ax_trace_quick (ax, TYPE_LENGTH (type));
472     }
473
474   switch (TYPE_CODE (type))
475     {
476     case TYPE_CODE_PTR:
477     case TYPE_CODE_REF:
478     case TYPE_CODE_ENUM:
479     case TYPE_CODE_INT:
480     case TYPE_CODE_CHAR:
481     case TYPE_CODE_BOOL:
482       /* It's a scalar value, so we know how to dereference it.  How
483          many bytes long is it?  */
484       switch (TYPE_LENGTH (type))
485         {
486         case 8 / TARGET_CHAR_BIT:
487           ax_simple (ax, aop_ref8);
488           break;
489         case 16 / TARGET_CHAR_BIT:
490           ax_simple (ax, aop_ref16);
491           break;
492         case 32 / TARGET_CHAR_BIT:
493           ax_simple (ax, aop_ref32);
494           break;
495         case 64 / TARGET_CHAR_BIT:
496           ax_simple (ax, aop_ref64);
497           break;
498
499           /* Either our caller shouldn't have asked us to dereference
500              that pointer (other code's fault), or we're not
501              implementing something we should be (this code's fault).
502              In any case, it's a bug the user shouldn't see.  */
503         default:
504           internal_error (__FILE__, __LINE__,
505                           _("gen_fetch: strange size"));
506         }
507
508       gen_sign_extend (ax, type);
509       break;
510
511     default:
512       /* Either our caller shouldn't have asked us to dereference that
513          pointer (other code's fault), or we're not implementing
514          something we should be (this code's fault).  In any case,
515          it's a bug the user shouldn't see.  */
516       internal_error (__FILE__, __LINE__,
517                       _("gen_fetch: bad type code"));
518     }
519 }
520
521
522 /* Generate code to left shift the top of the stack by DISTANCE bits, or
523    right shift it by -DISTANCE bits if DISTANCE < 0.  This generates
524    unsigned (logical) right shifts.  */
525 static void
526 gen_left_shift (struct agent_expr *ax, int distance)
527 {
528   if (distance > 0)
529     {
530       ax_const_l (ax, distance);
531       ax_simple (ax, aop_lsh);
532     }
533   else if (distance < 0)
534     {
535       ax_const_l (ax, -distance);
536       ax_simple (ax, aop_rsh_unsigned);
537     }
538 }
539 \f
540
541
542 /* Generating bytecode from GDB expressions: symbol references */
543
544 /* Generate code to push the base address of the argument portion of
545    the top stack frame.  */
546 static void
547 gen_frame_args_address (struct gdbarch *gdbarch, struct agent_expr *ax)
548 {
549   int frame_reg;
550   LONGEST frame_offset;
551
552   gdbarch_virtual_frame_pointer (gdbarch,
553                                  ax->scope, &frame_reg, &frame_offset);
554   ax_reg (ax, frame_reg);
555   gen_offset (ax, frame_offset);
556 }
557
558
559 /* Generate code to push the base address of the locals portion of the
560    top stack frame.  */
561 static void
562 gen_frame_locals_address (struct gdbarch *gdbarch, struct agent_expr *ax)
563 {
564   int frame_reg;
565   LONGEST frame_offset;
566
567   gdbarch_virtual_frame_pointer (gdbarch,
568                                  ax->scope, &frame_reg, &frame_offset);
569   ax_reg (ax, frame_reg);
570   gen_offset (ax, frame_offset);
571 }
572
573
574 /* Generate code to add OFFSET to the top of the stack.  Try to
575    generate short and readable code.  We use this for getting to
576    variables on the stack, and structure members.  If we were
577    programming in ML, it would be clearer why these are the same
578    thing.  */
579 static void
580 gen_offset (struct agent_expr *ax, int offset)
581 {
582   /* It would suffice to simply push the offset and add it, but this
583      makes it easier to read positive and negative offsets in the
584      bytecode.  */
585   if (offset > 0)
586     {
587       ax_const_l (ax, offset);
588       ax_simple (ax, aop_add);
589     }
590   else if (offset < 0)
591     {
592       ax_const_l (ax, -offset);
593       ax_simple (ax, aop_sub);
594     }
595 }
596
597
598 /* In many cases, a symbol's value is the offset from some other
599    address (stack frame, base register, etc.)  Generate code to add
600    VAR's value to the top of the stack.  */
601 static void
602 gen_sym_offset (struct agent_expr *ax, struct symbol *var)
603 {
604   gen_offset (ax, SYMBOL_VALUE (var));
605 }
606
607
608 /* Generate code for a variable reference to AX.  The variable is the
609    symbol VAR.  Set VALUE to describe the result.  */
610
611 static void
612 gen_var_ref (struct gdbarch *gdbarch, struct agent_expr *ax,
613              struct axs_value *value, struct symbol *var)
614 {
615   /* Dereference any typedefs. */
616   value->type = check_typedef (SYMBOL_TYPE (var));
617   value->optimized_out = 0;
618
619   /* I'm imitating the code in read_var_value.  */
620   switch (SYMBOL_CLASS (var))
621     {
622     case LOC_CONST:             /* A constant, like an enum value.  */
623       ax_const_l (ax, (LONGEST) SYMBOL_VALUE (var));
624       value->kind = axs_rvalue;
625       break;
626
627     case LOC_LABEL:             /* A goto label, being used as a value.  */
628       ax_const_l (ax, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
629       value->kind = axs_rvalue;
630       break;
631
632     case LOC_CONST_BYTES:
633       internal_error (__FILE__, __LINE__,
634                       _("gen_var_ref: LOC_CONST_BYTES symbols are not supported"));
635
636       /* Variable at a fixed location in memory.  Easy.  */
637     case LOC_STATIC:
638       /* Push the address of the variable.  */
639       ax_const_l (ax, SYMBOL_VALUE_ADDRESS (var));
640       value->kind = axs_lvalue_memory;
641       break;
642
643     case LOC_ARG:               /* var lives in argument area of frame */
644       gen_frame_args_address (gdbarch, ax);
645       gen_sym_offset (ax, var);
646       value->kind = axs_lvalue_memory;
647       break;
648
649     case LOC_REF_ARG:           /* As above, but the frame slot really
650                                    holds the address of the variable.  */
651       gen_frame_args_address (gdbarch, ax);
652       gen_sym_offset (ax, var);
653       /* Don't assume any particular pointer size.  */
654       gen_fetch (ax, builtin_type (gdbarch)->builtin_data_ptr);
655       value->kind = axs_lvalue_memory;
656       break;
657
658     case LOC_LOCAL:             /* var lives in locals area of frame */
659       gen_frame_locals_address (gdbarch, ax);
660       gen_sym_offset (ax, var);
661       value->kind = axs_lvalue_memory;
662       break;
663
664     case LOC_TYPEDEF:
665       error (_("Cannot compute value of typedef `%s'."),
666              SYMBOL_PRINT_NAME (var));
667       break;
668
669     case LOC_BLOCK:
670       ax_const_l (ax, BLOCK_START (SYMBOL_BLOCK_VALUE (var)));
671       value->kind = axs_rvalue;
672       break;
673
674     case LOC_REGISTER:
675       /* Don't generate any code at all; in the process of treating
676          this as an lvalue or rvalue, the caller will generate the
677          right code.  */
678       value->kind = axs_lvalue_register;
679       value->u.reg = SYMBOL_REGISTER_OPS (var)->register_number (var, gdbarch);
680       break;
681
682       /* A lot like LOC_REF_ARG, but the pointer lives directly in a
683          register, not on the stack.  Simpler than LOC_REGISTER
684          because it's just like any other case where the thing
685          has a real address.  */
686     case LOC_REGPARM_ADDR:
687       ax_reg (ax, SYMBOL_REGISTER_OPS (var)->register_number (var, gdbarch));
688       value->kind = axs_lvalue_memory;
689       break;
690
691     case LOC_UNRESOLVED:
692       {
693         struct minimal_symbol *msym
694           = lookup_minimal_symbol (SYMBOL_LINKAGE_NAME (var), NULL, NULL);
695         if (!msym)
696           error (_("Couldn't resolve symbol `%s'."), SYMBOL_PRINT_NAME (var));
697
698         /* Push the address of the variable.  */
699         ax_const_l (ax, SYMBOL_VALUE_ADDRESS (msym));
700         value->kind = axs_lvalue_memory;
701       }
702       break;
703
704     case LOC_COMPUTED:
705       /* FIXME: cagney/2004-01-26: It should be possible to
706          unconditionally call the SYMBOL_COMPUTED_OPS method when available.
707          Unfortunately DWARF 2 stores the frame-base (instead of the
708          function) location in a function's symbol.  Oops!  For the
709          moment enable this when/where applicable.  */
710       SYMBOL_COMPUTED_OPS (var)->tracepoint_var_ref (var, gdbarch, ax, value);
711       break;
712
713     case LOC_OPTIMIZED_OUT:
714       /* Flag this, but don't say anything; leave it up to callers to
715          warn the user.  */
716       value->optimized_out = 1;
717       break;
718
719     default:
720       error (_("Cannot find value of botched symbol `%s'."),
721              SYMBOL_PRINT_NAME (var));
722       break;
723     }
724 }
725 \f
726
727
728 /* Generating bytecode from GDB expressions: literals */
729
730 static void
731 gen_int_literal (struct agent_expr *ax, struct axs_value *value, LONGEST k,
732                  struct type *type)
733 {
734   ax_const_l (ax, k);
735   value->kind = axs_rvalue;
736   value->type = check_typedef (type);
737 }
738 \f
739
740
741 /* Generating bytecode from GDB expressions: unary conversions, casts */
742
743 /* Take what's on the top of the stack (as described by VALUE), and
744    try to make an rvalue out of it.  Signal an error if we can't do
745    that.  */
746 static void
747 require_rvalue (struct agent_expr *ax, struct axs_value *value)
748 {
749   /* Only deal with scalars, structs and such may be too large
750      to fit in a stack entry.  */
751   value->type = check_typedef (value->type);
752   if (TYPE_CODE (value->type) == TYPE_CODE_ARRAY
753       || TYPE_CODE (value->type) == TYPE_CODE_STRUCT
754       || TYPE_CODE (value->type) == TYPE_CODE_UNION
755       || TYPE_CODE (value->type) == TYPE_CODE_FUNC)
756     error (_("Value not scalar: cannot be an rvalue."));
757
758   switch (value->kind)
759     {
760     case axs_rvalue:
761       /* It's already an rvalue.  */
762       break;
763
764     case axs_lvalue_memory:
765       /* The top of stack is the address of the object.  Dereference.  */
766       gen_fetch (ax, value->type);
767       break;
768
769     case axs_lvalue_register:
770       /* There's nothing on the stack, but value->u.reg is the
771          register number containing the value.
772
773          When we add floating-point support, this is going to have to
774          change.  What about SPARC register pairs, for example?  */
775       ax_reg (ax, value->u.reg);
776       gen_extend (ax, value->type);
777       break;
778     }
779
780   value->kind = axs_rvalue;
781 }
782
783
784 /* Assume the top of the stack is described by VALUE, and perform the
785    usual unary conversions.  This is motivated by ANSI 6.2.2, but of
786    course GDB expressions are not ANSI; they're the mishmash union of
787    a bunch of languages.  Rah.
788
789    NOTE!  This function promises to produce an rvalue only when the
790    incoming value is of an appropriate type.  In other words, the
791    consumer of the value this function produces may assume the value
792    is an rvalue only after checking its type.
793
794    The immediate issue is that if the user tries to use a structure or
795    union as an operand of, say, the `+' operator, we don't want to try
796    to convert that structure to an rvalue; require_rvalue will bomb on
797    structs and unions.  Rather, we want to simply pass the struct
798    lvalue through unchanged, and let `+' raise an error.  */
799
800 static void
801 gen_usual_unary (struct expression *exp, struct agent_expr *ax,
802                  struct axs_value *value)
803 {
804   /* We don't have to generate any code for the usual integral
805      conversions, since values are always represented as full-width on
806      the stack.  Should we tweak the type?  */
807
808   /* Some types require special handling.  */
809   switch (TYPE_CODE (value->type))
810     {
811       /* Functions get converted to a pointer to the function.  */
812     case TYPE_CODE_FUNC:
813       value->type = lookup_pointer_type (value->type);
814       value->kind = axs_rvalue; /* Should always be true, but just in case.  */
815       break;
816
817       /* Arrays get converted to a pointer to their first element, and
818          are no longer an lvalue.  */
819     case TYPE_CODE_ARRAY:
820       {
821         struct type *elements = TYPE_TARGET_TYPE (value->type);
822         value->type = lookup_pointer_type (elements);
823         value->kind = axs_rvalue;
824         /* We don't need to generate any code; the address of the array
825            is also the address of its first element.  */
826       }
827       break;
828
829       /* Don't try to convert structures and unions to rvalues.  Let the
830          consumer signal an error.  */
831     case TYPE_CODE_STRUCT:
832     case TYPE_CODE_UNION:
833       return;
834
835       /* If the value is an enum or a bool, call it an integer.  */
836     case TYPE_CODE_ENUM:
837     case TYPE_CODE_BOOL:
838       value->type = builtin_type (exp->gdbarch)->builtin_int;
839       break;
840     }
841
842   /* If the value is an lvalue, dereference it.  */
843   require_rvalue (ax, value);
844 }
845
846
847 /* Return non-zero iff the type TYPE1 is considered "wider" than the
848    type TYPE2, according to the rules described in gen_usual_arithmetic.  */
849 static int
850 type_wider_than (struct type *type1, struct type *type2)
851 {
852   return (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)
853           || (TYPE_LENGTH (type1) == TYPE_LENGTH (type2)
854               && TYPE_UNSIGNED (type1)
855               && !TYPE_UNSIGNED (type2)));
856 }
857
858
859 /* Return the "wider" of the two types TYPE1 and TYPE2.  */
860 static struct type *
861 max_type (struct type *type1, struct type *type2)
862 {
863   return type_wider_than (type1, type2) ? type1 : type2;
864 }
865
866
867 /* Generate code to convert a scalar value of type FROM to type TO.  */
868 static void
869 gen_conversion (struct agent_expr *ax, struct type *from, struct type *to)
870 {
871   /* Perhaps there is a more graceful way to state these rules.  */
872
873   /* If we're converting to a narrower type, then we need to clear out
874      the upper bits.  */
875   if (TYPE_LENGTH (to) < TYPE_LENGTH (from))
876     gen_extend (ax, from);
877
878   /* If the two values have equal width, but different signednesses,
879      then we need to extend.  */
880   else if (TYPE_LENGTH (to) == TYPE_LENGTH (from))
881     {
882       if (TYPE_UNSIGNED (from) != TYPE_UNSIGNED (to))
883         gen_extend (ax, to);
884     }
885
886   /* If we're converting to a wider type, and becoming unsigned, then
887      we need to zero out any possible sign bits.  */
888   else if (TYPE_LENGTH (to) > TYPE_LENGTH (from))
889     {
890       if (TYPE_UNSIGNED (to))
891         gen_extend (ax, to);
892     }
893 }
894
895
896 /* Return non-zero iff the type FROM will require any bytecodes to be
897    emitted to be converted to the type TO.  */
898 static int
899 is_nontrivial_conversion (struct type *from, struct type *to)
900 {
901   struct agent_expr *ax = new_agent_expr (0);
902   int nontrivial;
903
904   /* Actually generate the code, and see if anything came out.  At the
905      moment, it would be trivial to replicate the code in
906      gen_conversion here, but in the future, when we're supporting
907      floating point and the like, it may not be.  Doing things this
908      way allows this function to be independent of the logic in
909      gen_conversion.  */
910   gen_conversion (ax, from, to);
911   nontrivial = ax->len > 0;
912   free_agent_expr (ax);
913   return nontrivial;
914 }
915
916
917 /* Generate code to perform the "usual arithmetic conversions" (ANSI C
918    6.2.1.5) for the two operands of an arithmetic operator.  This
919    effectively finds a "least upper bound" type for the two arguments,
920    and promotes each argument to that type.  *VALUE1 and *VALUE2
921    describe the values as they are passed in, and as they are left.  */
922 static void
923 gen_usual_arithmetic (struct expression *exp, struct agent_expr *ax,
924                       struct axs_value *value1, struct axs_value *value2)
925 {
926   /* Do the usual binary conversions.  */
927   if (TYPE_CODE (value1->type) == TYPE_CODE_INT
928       && TYPE_CODE (value2->type) == TYPE_CODE_INT)
929     {
930       /* The ANSI integral promotions seem to work this way: Order the
931          integer types by size, and then by signedness: an n-bit
932          unsigned type is considered "wider" than an n-bit signed
933          type.  Promote to the "wider" of the two types, and always
934          promote at least to int.  */
935       struct type *target = max_type (builtin_type (exp->gdbarch)->builtin_int,
936                                       max_type (value1->type, value2->type));
937
938       /* Deal with value2, on the top of the stack.  */
939       gen_conversion (ax, value2->type, target);
940
941       /* Deal with value1, not on the top of the stack.  Don't
942          generate the `swap' instructions if we're not actually going
943          to do anything.  */
944       if (is_nontrivial_conversion (value1->type, target))
945         {
946           ax_simple (ax, aop_swap);
947           gen_conversion (ax, value1->type, target);
948           ax_simple (ax, aop_swap);
949         }
950
951       value1->type = value2->type = check_typedef (target);
952     }
953 }
954
955
956 /* Generate code to perform the integral promotions (ANSI 6.2.1.1) on
957    the value on the top of the stack, as described by VALUE.  Assume
958    the value has integral type.  */
959 static void
960 gen_integral_promotions (struct expression *exp, struct agent_expr *ax,
961                          struct axs_value *value)
962 {
963   const struct builtin_type *builtin = builtin_type (exp->gdbarch);
964
965   if (!type_wider_than (value->type, builtin->builtin_int))
966     {
967       gen_conversion (ax, value->type, builtin->builtin_int);
968       value->type = builtin->builtin_int;
969     }
970   else if (!type_wider_than (value->type, builtin->builtin_unsigned_int))
971     {
972       gen_conversion (ax, value->type, builtin->builtin_unsigned_int);
973       value->type = builtin->builtin_unsigned_int;
974     }
975 }
976
977
978 /* Generate code for a cast to TYPE.  */
979 static void
980 gen_cast (struct agent_expr *ax, struct axs_value *value, struct type *type)
981 {
982   /* GCC does allow casts to yield lvalues, so this should be fixed
983      before merging these changes into the trunk.  */
984   require_rvalue (ax, value);
985   /* Dereference typedefs. */
986   type = check_typedef (type);
987
988   switch (TYPE_CODE (type))
989     {
990     case TYPE_CODE_PTR:
991     case TYPE_CODE_REF:
992       /* It's implementation-defined, and I'll bet this is what GCC
993          does.  */
994       break;
995
996     case TYPE_CODE_ARRAY:
997     case TYPE_CODE_STRUCT:
998     case TYPE_CODE_UNION:
999     case TYPE_CODE_FUNC:
1000       error (_("Invalid type cast: intended type must be scalar."));
1001
1002     case TYPE_CODE_ENUM:
1003     case TYPE_CODE_BOOL:
1004       /* We don't have to worry about the size of the value, because
1005          all our integral values are fully sign-extended, and when
1006          casting pointers we can do anything we like.  Is there any
1007          way for us to know what GCC actually does with a cast like
1008          this?  */
1009       break;
1010
1011     case TYPE_CODE_INT:
1012       gen_conversion (ax, value->type, type);
1013       break;
1014
1015     case TYPE_CODE_VOID:
1016       /* We could pop the value, and rely on everyone else to check
1017          the type and notice that this value doesn't occupy a stack
1018          slot.  But for now, leave the value on the stack, and
1019          preserve the "value == stack element" assumption.  */
1020       break;
1021
1022     default:
1023       error (_("Casts to requested type are not yet implemented."));
1024     }
1025
1026   value->type = type;
1027 }
1028 \f
1029
1030
1031 /* Generating bytecode from GDB expressions: arithmetic */
1032
1033 /* Scale the integer on the top of the stack by the size of the target
1034    of the pointer type TYPE.  */
1035 static void
1036 gen_scale (struct agent_expr *ax, enum agent_op op, struct type *type)
1037 {
1038   struct type *element = TYPE_TARGET_TYPE (type);
1039
1040   if (TYPE_LENGTH (element) != 1)
1041     {
1042       ax_const_l (ax, TYPE_LENGTH (element));
1043       ax_simple (ax, op);
1044     }
1045 }
1046
1047
1048 /* Generate code for pointer arithmetic PTR + INT.  */
1049 static void
1050 gen_ptradd (struct agent_expr *ax, struct axs_value *value,
1051             struct axs_value *value1, struct axs_value *value2)
1052 {
1053   gdb_assert (pointer_type (value1->type));
1054   gdb_assert (TYPE_CODE (value2->type) == TYPE_CODE_INT);
1055
1056   gen_scale (ax, aop_mul, value1->type);
1057   ax_simple (ax, aop_add);
1058   gen_extend (ax, value1->type);        /* Catch overflow.  */
1059   value->type = value1->type;
1060   value->kind = axs_rvalue;
1061 }
1062
1063
1064 /* Generate code for pointer arithmetic PTR - INT.  */
1065 static void
1066 gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
1067             struct axs_value *value1, struct axs_value *value2)
1068 {
1069   gdb_assert (pointer_type (value1->type));
1070   gdb_assert (TYPE_CODE (value2->type) == TYPE_CODE_INT);
1071
1072   gen_scale (ax, aop_mul, value1->type);
1073   ax_simple (ax, aop_sub);
1074   gen_extend (ax, value1->type);        /* Catch overflow.  */
1075   value->type = value1->type;
1076   value->kind = axs_rvalue;
1077 }
1078
1079
1080 /* Generate code for pointer arithmetic PTR - PTR.  */
1081 static void
1082 gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
1083              struct axs_value *value1, struct axs_value *value2,
1084              struct type *result_type)
1085 {
1086   gdb_assert (pointer_type (value1->type));
1087   gdb_assert (pointer_type (value2->type));
1088
1089   if (TYPE_LENGTH (TYPE_TARGET_TYPE (value1->type))
1090       != TYPE_LENGTH (TYPE_TARGET_TYPE (value2->type)))
1091     error (_("\
1092 First argument of `-' is a pointer, but second argument is neither\n\
1093 an integer nor a pointer of the same type."));
1094
1095   ax_simple (ax, aop_sub);
1096   gen_scale (ax, aop_div_unsigned, value1->type);
1097   value->type = result_type;
1098   value->kind = axs_rvalue;
1099 }
1100
1101 static void
1102 gen_equal (struct agent_expr *ax, struct axs_value *value,
1103            struct axs_value *value1, struct axs_value *value2,
1104            struct type *result_type)
1105 {
1106   if (pointer_type (value1->type) || pointer_type (value2->type))
1107     ax_simple (ax, aop_equal);
1108   else
1109     gen_binop (ax, value, value1, value2,
1110                aop_equal, aop_equal, 0, "equal");
1111   value->type = result_type;
1112   value->kind = axs_rvalue;
1113 }
1114
1115 static void
1116 gen_less (struct agent_expr *ax, struct axs_value *value,
1117           struct axs_value *value1, struct axs_value *value2,
1118           struct type *result_type)
1119 {
1120   if (pointer_type (value1->type) || pointer_type (value2->type))
1121     ax_simple (ax, aop_less_unsigned);
1122   else
1123     gen_binop (ax, value, value1, value2,
1124                aop_less_signed, aop_less_unsigned, 0, "less than");
1125   value->type = result_type;
1126   value->kind = axs_rvalue;
1127 }
1128
1129 /* Generate code for a binary operator that doesn't do pointer magic.
1130    We set VALUE to describe the result value; we assume VALUE1 and
1131    VALUE2 describe the two operands, and that they've undergone the
1132    usual binary conversions.  MAY_CARRY should be non-zero iff the
1133    result needs to be extended.  NAME is the English name of the
1134    operator, used in error messages */
1135 static void
1136 gen_binop (struct agent_expr *ax, struct axs_value *value,
1137            struct axs_value *value1, struct axs_value *value2, enum agent_op op,
1138            enum agent_op op_unsigned, int may_carry, char *name)
1139 {
1140   /* We only handle INT op INT.  */
1141   if ((TYPE_CODE (value1->type) != TYPE_CODE_INT)
1142       || (TYPE_CODE (value2->type) != TYPE_CODE_INT))
1143     error (_("Invalid combination of types in %s."), name);
1144
1145   ax_simple (ax,
1146              TYPE_UNSIGNED (value1->type) ? op_unsigned : op);
1147   if (may_carry)
1148     gen_extend (ax, value1->type);      /* catch overflow */
1149   value->type = value1->type;
1150   value->kind = axs_rvalue;
1151 }
1152
1153
1154 static void
1155 gen_logical_not (struct agent_expr *ax, struct axs_value *value,
1156                  struct type *result_type)
1157 {
1158   if (TYPE_CODE (value->type) != TYPE_CODE_INT
1159       && TYPE_CODE (value->type) != TYPE_CODE_PTR)
1160     error (_("Invalid type of operand to `!'."));
1161
1162   ax_simple (ax, aop_log_not);
1163   value->type = result_type;
1164 }
1165
1166
1167 static void
1168 gen_complement (struct agent_expr *ax, struct axs_value *value)
1169 {
1170   if (TYPE_CODE (value->type) != TYPE_CODE_INT)
1171     error (_("Invalid type of operand to `~'."));
1172
1173   ax_simple (ax, aop_bit_not);
1174   gen_extend (ax, value->type);
1175 }
1176 \f
1177
1178
1179 /* Generating bytecode from GDB expressions: * & . -> @ sizeof */
1180
1181 /* Dereference the value on the top of the stack.  */
1182 static void
1183 gen_deref (struct agent_expr *ax, struct axs_value *value)
1184 {
1185   /* The caller should check the type, because several operators use
1186      this, and we don't know what error message to generate.  */
1187   if (!pointer_type (value->type))
1188     internal_error (__FILE__, __LINE__,
1189                     _("gen_deref: expected a pointer"));
1190
1191   /* We've got an rvalue now, which is a pointer.  We want to yield an
1192      lvalue, whose address is exactly that pointer.  So we don't
1193      actually emit any code; we just change the type from "Pointer to
1194      T" to "T", and mark the value as an lvalue in memory.  Leave it
1195      to the consumer to actually dereference it.  */
1196   value->type = check_typedef (TYPE_TARGET_TYPE (value->type));
1197   if (TYPE_CODE (value->type) == TYPE_CODE_VOID)
1198     error (_("Attempt to dereference a generic pointer."));
1199   value->kind = ((TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1200                  ? axs_rvalue : axs_lvalue_memory);
1201 }
1202
1203
1204 /* Produce the address of the lvalue on the top of the stack.  */
1205 static void
1206 gen_address_of (struct agent_expr *ax, struct axs_value *value)
1207 {
1208   /* Special case for taking the address of a function.  The ANSI
1209      standard describes this as a special case, too, so this
1210      arrangement is not without motivation.  */
1211   if (TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1212     /* The value's already an rvalue on the stack, so we just need to
1213        change the type.  */
1214     value->type = lookup_pointer_type (value->type);
1215   else
1216     switch (value->kind)
1217       {
1218       case axs_rvalue:
1219         error (_("Operand of `&' is an rvalue, which has no address."));
1220
1221       case axs_lvalue_register:
1222         error (_("Operand of `&' is in a register, and has no address."));
1223
1224       case axs_lvalue_memory:
1225         value->kind = axs_rvalue;
1226         value->type = lookup_pointer_type (value->type);
1227         break;
1228       }
1229 }
1230
1231 /* Generate code to push the value of a bitfield of a structure whose
1232    address is on the top of the stack.  START and END give the
1233    starting and one-past-ending *bit* numbers of the field within the
1234    structure.  */
1235 static void
1236 gen_bitfield_ref (struct expression *exp, struct agent_expr *ax,
1237                   struct axs_value *value, struct type *type,
1238                   int start, int end)
1239 {
1240   /* Note that ops[i] fetches 8 << i bits.  */
1241   static enum agent_op ops[]
1242   =
1243   {aop_ref8, aop_ref16, aop_ref32, aop_ref64};
1244   static int num_ops = (sizeof (ops) / sizeof (ops[0]));
1245
1246   /* We don't want to touch any byte that the bitfield doesn't
1247      actually occupy; we shouldn't make any accesses we're not
1248      explicitly permitted to.  We rely here on the fact that the
1249      bytecode `ref' operators work on unaligned addresses.
1250
1251      It takes some fancy footwork to get the stack to work the way
1252      we'd like.  Say we're retrieving a bitfield that requires three
1253      fetches.  Initially, the stack just contains the address:
1254      addr
1255      For the first fetch, we duplicate the address
1256      addr addr
1257      then add the byte offset, do the fetch, and shift and mask as
1258      needed, yielding a fragment of the value, properly aligned for
1259      the final bitwise or:
1260      addr frag1
1261      then we swap, and repeat the process:
1262      frag1 addr                    --- address on top
1263      frag1 addr addr               --- duplicate it
1264      frag1 addr frag2              --- get second fragment
1265      frag1 frag2 addr              --- swap again
1266      frag1 frag2 frag3             --- get third fragment
1267      Notice that, since the third fragment is the last one, we don't
1268      bother duplicating the address this time.  Now we have all the
1269      fragments on the stack, and we can simply `or' them together,
1270      yielding the final value of the bitfield.  */
1271
1272   /* The first and one-after-last bits in the field, but rounded down
1273      and up to byte boundaries.  */
1274   int bound_start = (start / TARGET_CHAR_BIT) * TARGET_CHAR_BIT;
1275   int bound_end = (((end + TARGET_CHAR_BIT - 1)
1276                     / TARGET_CHAR_BIT)
1277                    * TARGET_CHAR_BIT);
1278
1279   /* current bit offset within the structure */
1280   int offset;
1281
1282   /* The index in ops of the opcode we're considering.  */
1283   int op;
1284
1285   /* The number of fragments we generated in the process.  Probably
1286      equal to the number of `one' bits in bytesize, but who cares?  */
1287   int fragment_count;
1288
1289   /* Dereference any typedefs. */
1290   type = check_typedef (type);
1291
1292   /* Can we fetch the number of bits requested at all?  */
1293   if ((end - start) > ((1 << num_ops) * 8))
1294     internal_error (__FILE__, __LINE__,
1295                     _("gen_bitfield_ref: bitfield too wide"));
1296
1297   /* Note that we know here that we only need to try each opcode once.
1298      That may not be true on machines with weird byte sizes.  */
1299   offset = bound_start;
1300   fragment_count = 0;
1301   for (op = num_ops - 1; op >= 0; op--)
1302     {
1303       /* number of bits that ops[op] would fetch */
1304       int op_size = 8 << op;
1305
1306       /* The stack at this point, from bottom to top, contains zero or
1307          more fragments, then the address.  */
1308
1309       /* Does this fetch fit within the bitfield?  */
1310       if (offset + op_size <= bound_end)
1311         {
1312           /* Is this the last fragment?  */
1313           int last_frag = (offset + op_size == bound_end);
1314
1315           if (!last_frag)
1316             ax_simple (ax, aop_dup);    /* keep a copy of the address */
1317
1318           /* Add the offset.  */
1319           gen_offset (ax, offset / TARGET_CHAR_BIT);
1320
1321           if (trace_kludge)
1322             {
1323               /* Record the area of memory we're about to fetch.  */
1324               ax_trace_quick (ax, op_size / TARGET_CHAR_BIT);
1325             }
1326
1327           /* Perform the fetch.  */
1328           ax_simple (ax, ops[op]);
1329
1330           /* Shift the bits we have to their proper position.
1331              gen_left_shift will generate right shifts when the operand
1332              is negative.
1333
1334              A big-endian field diagram to ponder:
1335              byte 0  byte 1  byte 2  byte 3  byte 4  byte 5  byte 6  byte 7
1336              +------++------++------++------++------++------++------++------+
1337              xxxxAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCxxxxxxxxxxx
1338              ^               ^               ^    ^
1339              bit number      16              32              48   53
1340              These are bit numbers as supplied by GDB.  Note that the
1341              bit numbers run from right to left once you've fetched the
1342              value!
1343
1344              A little-endian field diagram to ponder:
1345              byte 7  byte 6  byte 5  byte 4  byte 3  byte 2  byte 1  byte 0
1346              +------++------++------++------++------++------++------++------+
1347              xxxxxxxxxxxAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCxxxx
1348              ^               ^               ^           ^   ^
1349              bit number     48              32              16          4   0
1350
1351              In both cases, the most significant end is on the left
1352              (i.e. normal numeric writing order), which means that you
1353              don't go crazy thinking about `left' and `right' shifts.
1354
1355              We don't have to worry about masking yet:
1356              - If they contain garbage off the least significant end, then we
1357              must be looking at the low end of the field, and the right
1358              shift will wipe them out.
1359              - If they contain garbage off the most significant end, then we
1360              must be looking at the most significant end of the word, and
1361              the sign/zero extension will wipe them out.
1362              - If we're in the interior of the word, then there is no garbage
1363              on either end, because the ref operators zero-extend.  */
1364           if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
1365             gen_left_shift (ax, end - (offset + op_size));
1366           else
1367             gen_left_shift (ax, offset - start);
1368
1369           if (!last_frag)
1370             /* Bring the copy of the address up to the top.  */
1371             ax_simple (ax, aop_swap);
1372
1373           offset += op_size;
1374           fragment_count++;
1375         }
1376     }
1377
1378   /* Generate enough bitwise `or' operations to combine all the
1379      fragments we left on the stack.  */
1380   while (fragment_count-- > 1)
1381     ax_simple (ax, aop_bit_or);
1382
1383   /* Sign- or zero-extend the value as appropriate.  */
1384   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, end - start));
1385
1386   /* This is *not* an lvalue.  Ugh.  */
1387   value->kind = axs_rvalue;
1388   value->type = type;
1389 }
1390
1391 /* Generate bytecodes for field number FIELDNO of type TYPE.  OFFSET
1392    is an accumulated offset (in bytes), will be nonzero for objects
1393    embedded in other objects, like C++ base classes.  Behavior should
1394    generally follow value_primitive_field.  */
1395
1396 static void
1397 gen_primitive_field (struct expression *exp,
1398                      struct agent_expr *ax, struct axs_value *value,
1399                      int offset, int fieldno, struct type *type)
1400 {
1401   /* Is this a bitfield?  */
1402   if (TYPE_FIELD_PACKED (type, fieldno))
1403     gen_bitfield_ref (exp, ax, value, TYPE_FIELD_TYPE (type, fieldno),
1404                       (offset * TARGET_CHAR_BIT
1405                        + TYPE_FIELD_BITPOS (type, fieldno)),
1406                       (offset * TARGET_CHAR_BIT
1407                        + TYPE_FIELD_BITPOS (type, fieldno)
1408                        + TYPE_FIELD_BITSIZE (type, fieldno)));
1409   else
1410     {
1411       gen_offset (ax, offset
1412                   + TYPE_FIELD_BITPOS (type, fieldno) / TARGET_CHAR_BIT);
1413       value->kind = axs_lvalue_memory;
1414       value->type = TYPE_FIELD_TYPE (type, fieldno);
1415     }
1416 }
1417
1418 /* Search for the given field in either the given type or one of its
1419    base classes.  Return 1 if found, 0 if not.  */
1420
1421 static int
1422 gen_struct_ref_recursive (struct expression *exp, struct agent_expr *ax,
1423                           struct axs_value *value,
1424                           char *field, int offset, struct type *type)
1425 {
1426   int i, rslt;
1427   int nbases = TYPE_N_BASECLASSES (type);
1428
1429   CHECK_TYPEDEF (type);
1430
1431   for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
1432     {
1433       char *this_name = TYPE_FIELD_NAME (type, i);
1434
1435       if (this_name)
1436         {
1437           if (strcmp (field, this_name) == 0)
1438             {
1439               /* Note that bytecodes for the struct's base (aka
1440                  "this") will have been generated already, which will
1441                  be unnecessary but not harmful if the static field is
1442                  being handled as a global.  */
1443               if (field_is_static (&TYPE_FIELD (type, i)))
1444                 {
1445                   gen_static_field (exp->gdbarch, ax, value, type, i);
1446                   if (value->optimized_out)
1447                     error (_("static field `%s' has been optimized out, cannot use"),
1448                            field);
1449                   return 1;
1450                 }
1451
1452               gen_primitive_field (exp, ax, value, offset, i, type);
1453               return 1;
1454             }
1455 #if 0 /* is this right? */
1456           if (this_name[0] == '\0')
1457             internal_error (__FILE__, __LINE__,
1458                             _("find_field: anonymous unions not supported"));
1459 #endif
1460         }
1461     }
1462
1463   /* Now scan through base classes recursively.  */
1464   for (i = 0; i < nbases; i++)
1465     {
1466       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
1467
1468       rslt = gen_struct_ref_recursive (exp, ax, value, field,
1469                                        offset + TYPE_BASECLASS_BITPOS (type, i) / TARGET_CHAR_BIT,
1470                                        basetype);
1471       if (rslt)
1472         return 1;
1473     }
1474
1475   /* Not found anywhere, flag so caller can complain.  */
1476   return 0;
1477 }
1478
1479 /* Generate code to reference the member named FIELD of a structure or
1480    union.  The top of the stack, as described by VALUE, should have
1481    type (pointer to a)* struct/union.  OPERATOR_NAME is the name of
1482    the operator being compiled, and OPERAND_NAME is the kind of thing
1483    it operates on; we use them in error messages.  */
1484 static void
1485 gen_struct_ref (struct expression *exp, struct agent_expr *ax,
1486                 struct axs_value *value, char *field,
1487                 char *operator_name, char *operand_name)
1488 {
1489   struct type *type;
1490   int found;
1491
1492   /* Follow pointers until we reach a non-pointer.  These aren't the C
1493      semantics, but they're what the normal GDB evaluator does, so we
1494      should at least be consistent.  */
1495   while (pointer_type (value->type))
1496     {
1497       require_rvalue (ax, value);
1498       gen_deref (ax, value);
1499     }
1500   type = check_typedef (value->type);
1501
1502   /* This must yield a structure or a union.  */
1503   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
1504       && TYPE_CODE (type) != TYPE_CODE_UNION)
1505     error (_("The left operand of `%s' is not a %s."),
1506            operator_name, operand_name);
1507
1508   /* And it must be in memory; we don't deal with structure rvalues,
1509      or structures living in registers.  */
1510   if (value->kind != axs_lvalue_memory)
1511     error (_("Structure does not live in memory."));
1512
1513   /* Search through fields and base classes recursively.  */
1514   found = gen_struct_ref_recursive (exp, ax, value, field, 0, type);
1515   
1516   if (!found)
1517     error (_("Couldn't find member named `%s' in struct/union/class `%s'"),
1518            field, TYPE_TAG_NAME (type));
1519 }
1520
1521 static int
1522 gen_namespace_elt (struct expression *exp,
1523                    struct agent_expr *ax, struct axs_value *value,
1524                    const struct type *curtype, char *name);
1525 static int
1526 gen_maybe_namespace_elt (struct expression *exp,
1527                          struct agent_expr *ax, struct axs_value *value,
1528                          const struct type *curtype, char *name);
1529
1530 static void
1531 gen_static_field (struct gdbarch *gdbarch,
1532                   struct agent_expr *ax, struct axs_value *value,
1533                   struct type *type, int fieldno)
1534 {
1535   if (TYPE_FIELD_LOC_KIND (type, fieldno) == FIELD_LOC_KIND_PHYSADDR)
1536     {
1537       ax_const_l (ax, TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
1538       value->kind = axs_lvalue_memory;
1539       value->type = TYPE_FIELD_TYPE (type, fieldno);
1540       value->optimized_out = 0;
1541     }
1542   else
1543     {
1544       char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
1545       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
1546
1547       if (sym)
1548         {
1549           gen_var_ref (gdbarch, ax, value, sym);
1550   
1551           /* Don't error if the value was optimized out, we may be
1552              scanning all static fields and just want to pass over this
1553              and continue with the rest.  */
1554         }
1555       else
1556         {
1557           /* Silently assume this was optimized out; class printing
1558              will let the user know why the data is missing.  */
1559           value->optimized_out = 1;
1560         }
1561     }
1562 }
1563
1564 static int
1565 gen_struct_elt_for_reference (struct expression *exp,
1566                               struct agent_expr *ax, struct axs_value *value,
1567                               struct type *type, char *fieldname)
1568 {
1569   struct type *t = type;
1570   int i;
1571   struct value *v, *result;
1572
1573   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
1574       && TYPE_CODE (t) != TYPE_CODE_UNION)
1575     internal_error (__FILE__, __LINE__,
1576                     _("non-aggregate type to gen_struct_elt_for_reference"));
1577
1578   for (i = TYPE_NFIELDS (t) - 1; i >= TYPE_N_BASECLASSES (t); i--)
1579     {
1580       char *t_field_name = TYPE_FIELD_NAME (t, i);
1581
1582       if (t_field_name && strcmp (t_field_name, fieldname) == 0)
1583         {
1584           if (field_is_static (&TYPE_FIELD (t, i)))
1585             {
1586               gen_static_field (exp->gdbarch, ax, value, t, i);
1587               if (value->optimized_out)
1588                 error (_("static field `%s' has been optimized out, cannot use"),
1589                        fieldname);
1590               return 1;
1591             }
1592           if (TYPE_FIELD_PACKED (t, i))
1593             error (_("pointers to bitfield members not allowed"));
1594
1595           /* FIXME we need a way to do "want_address" equivalent */       
1596
1597           error (_("Cannot reference non-static field \"%s\""), fieldname);
1598         }
1599     }
1600
1601   /* FIXME add other scoped-reference cases here */
1602
1603   /* Do a last-ditch lookup.  */
1604   return gen_maybe_namespace_elt (exp, ax, value, type, fieldname);
1605 }
1606
1607 /* C++: Return the member NAME of the namespace given by the type
1608    CURTYPE.  */
1609
1610 static int
1611 gen_namespace_elt (struct expression *exp,
1612                    struct agent_expr *ax, struct axs_value *value,
1613                    const struct type *curtype, char *name)
1614 {
1615   int found = gen_maybe_namespace_elt (exp, ax, value, curtype, name);
1616
1617   if (!found)
1618     error (_("No symbol \"%s\" in namespace \"%s\"."), 
1619            name, TYPE_TAG_NAME (curtype));
1620
1621   return found;
1622 }
1623
1624 /* A helper function used by value_namespace_elt and
1625    value_struct_elt_for_reference.  It looks up NAME inside the
1626    context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
1627    is a class and NAME refers to a type in CURTYPE itself (as opposed
1628    to, say, some base class of CURTYPE).  */
1629
1630 static int
1631 gen_maybe_namespace_elt (struct expression *exp,
1632                          struct agent_expr *ax, struct axs_value *value,
1633                          const struct type *curtype, char *name)
1634 {
1635   const char *namespace_name = TYPE_TAG_NAME (curtype);
1636   struct symbol *sym;
1637
1638   sym = cp_lookup_symbol_namespace (namespace_name, name,
1639                                     block_for_pc (ax->scope),
1640                                     VAR_DOMAIN);
1641
1642   if (sym == NULL)
1643     return 0;
1644
1645   gen_var_ref (exp->gdbarch, ax, value, sym);
1646
1647   if (value->optimized_out)
1648     error (_("`%s' has been optimized out, cannot use"),
1649            SYMBOL_PRINT_NAME (sym));
1650
1651   return 1;
1652 }
1653
1654
1655 static int
1656 gen_aggregate_elt_ref (struct expression *exp,
1657                        struct agent_expr *ax, struct axs_value *value,
1658                        struct type *type, char *field,
1659                        char *operator_name, char *operand_name)
1660 {
1661   switch (TYPE_CODE (type))
1662     {
1663     case TYPE_CODE_STRUCT:
1664     case TYPE_CODE_UNION:
1665       return gen_struct_elt_for_reference (exp, ax, value, type, field);
1666       break;
1667     case TYPE_CODE_NAMESPACE:
1668       return gen_namespace_elt (exp, ax, value, type, field);
1669       break;
1670     default:
1671       internal_error (__FILE__, __LINE__,
1672                       _("non-aggregate type in gen_aggregate_elt_ref"));
1673     }
1674
1675   return 0;
1676 }
1677
1678 /* Generate code for GDB's magical `repeat' operator.  
1679    LVALUE @ INT creates an array INT elements long, and whose elements
1680    have the same type as LVALUE, located in memory so that LVALUE is
1681    its first element.  For example, argv[0]@argc gives you the array
1682    of command-line arguments.
1683
1684    Unfortunately, because we have to know the types before we actually
1685    have a value for the expression, we can't implement this perfectly
1686    without changing the type system, having values that occupy two
1687    stack slots, doing weird things with sizeof, etc.  So we require
1688    the right operand to be a constant expression.  */
1689 static void
1690 gen_repeat (struct expression *exp, union exp_element **pc,
1691             struct agent_expr *ax, struct axs_value *value)
1692 {
1693   struct axs_value value1;
1694   /* We don't want to turn this into an rvalue, so no conversions
1695      here.  */
1696   gen_expr (exp, pc, ax, &value1);
1697   if (value1.kind != axs_lvalue_memory)
1698     error (_("Left operand of `@' must be an object in memory."));
1699
1700   /* Evaluate the length; it had better be a constant.  */
1701   {
1702     struct value *v = const_expr (pc);
1703     int length;
1704
1705     if (!v)
1706       error (_("Right operand of `@' must be a constant, in agent expressions."));
1707     if (TYPE_CODE (value_type (v)) != TYPE_CODE_INT)
1708       error (_("Right operand of `@' must be an integer."));
1709     length = value_as_long (v);
1710     if (length <= 0)
1711       error (_("Right operand of `@' must be positive."));
1712
1713     /* The top of the stack is already the address of the object, so
1714        all we need to do is frob the type of the lvalue.  */
1715     {
1716       /* FIXME-type-allocation: need a way to free this type when we are
1717          done with it.  */
1718       struct type *array
1719         = lookup_array_range_type (value1.type, 0, length - 1);
1720
1721       value->kind = axs_lvalue_memory;
1722       value->type = array;
1723     }
1724   }
1725 }
1726
1727
1728 /* Emit code for the `sizeof' operator.
1729    *PC should point at the start of the operand expression; we advance it
1730    to the first instruction after the operand.  */
1731 static void
1732 gen_sizeof (struct expression *exp, union exp_element **pc,
1733             struct agent_expr *ax, struct axs_value *value,
1734             struct type *size_type)
1735 {
1736   /* We don't care about the value of the operand expression; we only
1737      care about its type.  However, in the current arrangement, the
1738      only way to find an expression's type is to generate code for it.
1739      So we generate code for the operand, and then throw it away,
1740      replacing it with code that simply pushes its size.  */
1741   int start = ax->len;
1742   gen_expr (exp, pc, ax, value);
1743
1744   /* Throw away the code we just generated.  */
1745   ax->len = start;
1746
1747   ax_const_l (ax, TYPE_LENGTH (value->type));
1748   value->kind = axs_rvalue;
1749   value->type = size_type;
1750 }
1751 \f
1752
1753 /* Generating bytecode from GDB expressions: general recursive thingy  */
1754
1755 /* XXX: i18n */
1756 /* A gen_expr function written by a Gen-X'er guy.
1757    Append code for the subexpression of EXPR starting at *POS_P to AX.  */
1758 static void
1759 gen_expr (struct expression *exp, union exp_element **pc,
1760           struct agent_expr *ax, struct axs_value *value)
1761 {
1762   /* Used to hold the descriptions of operand expressions.  */
1763   struct axs_value value1, value2, value3;
1764   enum exp_opcode op = (*pc)[0].opcode, op2;
1765   int if1, go1, if2, go2, end;
1766   struct type *int_type = builtin_type (exp->gdbarch)->builtin_int;
1767
1768   /* If we're looking at a constant expression, just push its value.  */
1769   {
1770     struct value *v = maybe_const_expr (pc);
1771
1772     if (v)
1773       {
1774         ax_const_l (ax, value_as_long (v));
1775         value->kind = axs_rvalue;
1776         value->type = check_typedef (value_type (v));
1777         return;
1778       }
1779   }
1780
1781   /* Otherwise, go ahead and generate code for it.  */
1782   switch (op)
1783     {
1784       /* Binary arithmetic operators.  */
1785     case BINOP_ADD:
1786     case BINOP_SUB:
1787     case BINOP_MUL:
1788     case BINOP_DIV:
1789     case BINOP_REM:
1790     case BINOP_LSH:
1791     case BINOP_RSH:
1792     case BINOP_SUBSCRIPT:
1793     case BINOP_BITWISE_AND:
1794     case BINOP_BITWISE_IOR:
1795     case BINOP_BITWISE_XOR:
1796     case BINOP_EQUAL:
1797     case BINOP_NOTEQUAL:
1798     case BINOP_LESS:
1799     case BINOP_GTR:
1800     case BINOP_LEQ:
1801     case BINOP_GEQ:
1802       (*pc)++;
1803       gen_expr (exp, pc, ax, &value1);
1804       gen_usual_unary (exp, ax, &value1);
1805       gen_expr_binop_rest (exp, op, pc, ax, value, &value1, &value2);
1806       break;
1807
1808     case BINOP_LOGICAL_AND:
1809       (*pc)++;
1810       /* Generate the obvious sequence of tests and jumps.  */
1811       gen_expr (exp, pc, ax, &value1);
1812       gen_usual_unary (exp, ax, &value1);
1813       if1 = ax_goto (ax, aop_if_goto);
1814       go1 = ax_goto (ax, aop_goto);
1815       ax_label (ax, if1, ax->len);
1816       gen_expr (exp, pc, ax, &value2);
1817       gen_usual_unary (exp, ax, &value2);
1818       if2 = ax_goto (ax, aop_if_goto);
1819       go2 = ax_goto (ax, aop_goto);
1820       ax_label (ax, if2, ax->len);
1821       ax_const_l (ax, 1);
1822       end = ax_goto (ax, aop_goto);
1823       ax_label (ax, go1, ax->len);
1824       ax_label (ax, go2, ax->len);
1825       ax_const_l (ax, 0);
1826       ax_label (ax, end, ax->len);
1827       value->kind = axs_rvalue;
1828       value->type = int_type;
1829       break;
1830
1831     case BINOP_LOGICAL_OR:
1832       (*pc)++;
1833       /* Generate the obvious sequence of tests and jumps.  */
1834       gen_expr (exp, pc, ax, &value1);
1835       gen_usual_unary (exp, ax, &value1);
1836       if1 = ax_goto (ax, aop_if_goto);
1837       gen_expr (exp, pc, ax, &value2);
1838       gen_usual_unary (exp, ax, &value2);
1839       if2 = ax_goto (ax, aop_if_goto);
1840       ax_const_l (ax, 0);
1841       end = ax_goto (ax, aop_goto);
1842       ax_label (ax, if1, ax->len);
1843       ax_label (ax, if2, ax->len);
1844       ax_const_l (ax, 1);
1845       ax_label (ax, end, ax->len);
1846       value->kind = axs_rvalue;
1847       value->type = int_type;
1848       break;
1849
1850     case TERNOP_COND:
1851       (*pc)++;
1852       gen_expr (exp, pc, ax, &value1);
1853       gen_usual_unary (exp, ax, &value1);
1854       /* For (A ? B : C), it's easiest to generate subexpression
1855          bytecodes in order, but if_goto jumps on true, so we invert
1856          the sense of A.  Then we can do B by dropping through, and
1857          jump to do C.  */
1858       gen_logical_not (ax, &value1, int_type);
1859       if1 = ax_goto (ax, aop_if_goto);
1860       gen_expr (exp, pc, ax, &value2);
1861       gen_usual_unary (exp, ax, &value2);
1862       end = ax_goto (ax, aop_goto);
1863       ax_label (ax, if1, ax->len);
1864       gen_expr (exp, pc, ax, &value3);
1865       gen_usual_unary (exp, ax, &value3);
1866       ax_label (ax, end, ax->len);
1867       /* This is arbitary - what if B and C are incompatible types? */
1868       value->type = value2.type;
1869       value->kind = value2.kind;
1870       break;
1871
1872     case BINOP_ASSIGN:
1873       (*pc)++;
1874       if ((*pc)[0].opcode == OP_INTERNALVAR)
1875         {
1876           char *name = internalvar_name ((*pc)[1].internalvar);
1877           struct trace_state_variable *tsv;
1878           (*pc) += 3;
1879           gen_expr (exp, pc, ax, value);
1880           tsv = find_trace_state_variable (name);
1881           if (tsv)
1882             {
1883               ax_tsv (ax, aop_setv, tsv->number);
1884               if (trace_kludge)
1885                 ax_tsv (ax, aop_tracev, tsv->number);
1886             }
1887           else
1888             error (_("$%s is not a trace state variable, may not assign to it"), name);
1889         }
1890       else
1891         error (_("May only assign to trace state variables"));
1892       break;
1893
1894     case BINOP_ASSIGN_MODIFY:
1895       (*pc)++;
1896       op2 = (*pc)[0].opcode;
1897       (*pc)++;
1898       (*pc)++;
1899       if ((*pc)[0].opcode == OP_INTERNALVAR)
1900         {
1901           char *name = internalvar_name ((*pc)[1].internalvar);
1902           struct trace_state_variable *tsv;
1903           (*pc) += 3;
1904           tsv = find_trace_state_variable (name);
1905           if (tsv)
1906             {
1907               /* The tsv will be the left half of the binary operation.  */
1908               ax_tsv (ax, aop_getv, tsv->number);
1909               if (trace_kludge)
1910                 ax_tsv (ax, aop_tracev, tsv->number);
1911               /* Trace state variables are always 64-bit integers.  */
1912               value1.kind = axs_rvalue;
1913               value1.type = builtin_type (exp->gdbarch)->builtin_long_long;
1914               /* Now do right half of expression.  */
1915               gen_expr_binop_rest (exp, op2, pc, ax, value, &value1, &value2);
1916               /* We have a result of the binary op, set the tsv.  */
1917               ax_tsv (ax, aop_setv, tsv->number);
1918               if (trace_kludge)
1919                 ax_tsv (ax, aop_tracev, tsv->number);
1920             }
1921           else
1922             error (_("$%s is not a trace state variable, may not assign to it"), name);
1923         }
1924       else
1925         error (_("May only assign to trace state variables"));
1926       break;
1927
1928       /* Note that we need to be a little subtle about generating code
1929          for comma.  In C, we can do some optimizations here because
1930          we know the left operand is only being evaluated for effect.
1931          However, if the tracing kludge is in effect, then we always
1932          need to evaluate the left hand side fully, so that all the
1933          variables it mentions get traced.  */
1934     case BINOP_COMMA:
1935       (*pc)++;
1936       gen_expr (exp, pc, ax, &value1);
1937       /* Don't just dispose of the left operand.  We might be tracing,
1938          in which case we want to emit code to trace it if it's an
1939          lvalue.  */
1940       gen_traced_pop (exp->gdbarch, ax, &value1);
1941       gen_expr (exp, pc, ax, value);
1942       /* It's the consumer's responsibility to trace the right operand.  */
1943       break;
1944
1945     case OP_LONG:               /* some integer constant */
1946       {
1947         struct type *type = (*pc)[1].type;
1948         LONGEST k = (*pc)[2].longconst;
1949         (*pc) += 4;
1950         gen_int_literal (ax, value, k, type);
1951       }
1952       break;
1953
1954     case OP_VAR_VALUE:
1955       gen_var_ref (exp->gdbarch, ax, value, (*pc)[2].symbol);
1956
1957       if (value->optimized_out)
1958         error (_("`%s' has been optimized out, cannot use"),
1959                SYMBOL_PRINT_NAME ((*pc)[2].symbol));
1960
1961       (*pc) += 4;
1962       break;
1963
1964     case OP_REGISTER:
1965       {
1966         const char *name = &(*pc)[2].string;
1967         int reg;
1968         (*pc) += 4 + BYTES_TO_EXP_ELEM ((*pc)[1].longconst + 1);
1969         reg = user_reg_map_name_to_regnum (exp->gdbarch, name, strlen (name));
1970         if (reg == -1)
1971           internal_error (__FILE__, __LINE__,
1972                           _("Register $%s not available"), name);
1973         if (reg >= gdbarch_num_regs (exp->gdbarch))
1974           error (_("'%s' is a pseudo-register; "
1975                    "GDB cannot yet trace pseudoregister contents."),
1976                  name);
1977         value->kind = axs_lvalue_register;
1978         value->u.reg = reg;
1979         value->type = register_type (exp->gdbarch, reg);
1980       }
1981       break;
1982
1983     case OP_INTERNALVAR:
1984       {
1985         const char *name = internalvar_name ((*pc)[1].internalvar);
1986         struct trace_state_variable *tsv;
1987         (*pc) += 3;
1988         tsv = find_trace_state_variable (name);
1989         if (tsv)
1990           {
1991             ax_tsv (ax, aop_getv, tsv->number);
1992             if (trace_kludge)
1993               ax_tsv (ax, aop_tracev, tsv->number);
1994             /* Trace state variables are always 64-bit integers.  */
1995             value->kind = axs_rvalue;
1996             value->type = builtin_type (exp->gdbarch)->builtin_long_long;
1997           }
1998         else
1999           error (_("$%s is not a trace state variable; GDB agent expressions cannot use convenience variables."), name);
2000       }
2001       break;
2002
2003       /* Weirdo operator: see comments for gen_repeat for details.  */
2004     case BINOP_REPEAT:
2005       /* Note that gen_repeat handles its own argument evaluation.  */
2006       (*pc)++;
2007       gen_repeat (exp, pc, ax, value);
2008       break;
2009
2010     case UNOP_CAST:
2011       {
2012         struct type *type = (*pc)[1].type;
2013         (*pc) += 3;
2014         gen_expr (exp, pc, ax, value);
2015         gen_cast (ax, value, type);
2016       }
2017       break;
2018
2019     case UNOP_MEMVAL:
2020       {
2021         struct type *type = check_typedef ((*pc)[1].type);
2022         (*pc) += 3;
2023         gen_expr (exp, pc, ax, value);
2024         /* I'm not sure I understand UNOP_MEMVAL entirely.  I think
2025            it's just a hack for dealing with minsyms; you take some
2026            integer constant, pretend it's the address of an lvalue of
2027            the given type, and dereference it.  */
2028         if (value->kind != axs_rvalue)
2029           /* This would be weird.  */
2030           internal_error (__FILE__, __LINE__,
2031                           _("gen_expr: OP_MEMVAL operand isn't an rvalue???"));
2032         value->type = type;
2033         value->kind = axs_lvalue_memory;
2034       }
2035       break;
2036
2037     case UNOP_PLUS:
2038       (*pc)++;
2039       /* + FOO is equivalent to 0 + FOO, which can be optimized. */
2040       gen_expr (exp, pc, ax, value);
2041       gen_usual_unary (exp, ax, value);
2042       break;
2043       
2044     case UNOP_NEG:
2045       (*pc)++;
2046       /* -FOO is equivalent to 0 - FOO.  */
2047       gen_int_literal (ax, &value1, 0,
2048                        builtin_type (exp->gdbarch)->builtin_int);
2049       gen_usual_unary (exp, ax, &value1);       /* shouldn't do much */
2050       gen_expr (exp, pc, ax, &value2);
2051       gen_usual_unary (exp, ax, &value2);
2052       gen_usual_arithmetic (exp, ax, &value1, &value2);
2053       gen_binop (ax, value, &value1, &value2, aop_sub, aop_sub, 1, "negation");
2054       break;
2055
2056     case UNOP_LOGICAL_NOT:
2057       (*pc)++;
2058       gen_expr (exp, pc, ax, value);
2059       gen_usual_unary (exp, ax, value);
2060       gen_logical_not (ax, value, int_type);
2061       break;
2062
2063     case UNOP_COMPLEMENT:
2064       (*pc)++;
2065       gen_expr (exp, pc, ax, value);
2066       gen_usual_unary (exp, ax, value);
2067       gen_integral_promotions (exp, ax, value);
2068       gen_complement (ax, value);
2069       break;
2070
2071     case UNOP_IND:
2072       (*pc)++;
2073       gen_expr (exp, pc, ax, value);
2074       gen_usual_unary (exp, ax, value);
2075       if (!pointer_type (value->type))
2076         error (_("Argument of unary `*' is not a pointer."));
2077       gen_deref (ax, value);
2078       break;
2079
2080     case UNOP_ADDR:
2081       (*pc)++;
2082       gen_expr (exp, pc, ax, value);
2083       gen_address_of (ax, value);
2084       break;
2085
2086     case UNOP_SIZEOF:
2087       (*pc)++;
2088       /* Notice that gen_sizeof handles its own operand, unlike most
2089          of the other unary operator functions.  This is because we
2090          have to throw away the code we generate.  */
2091       gen_sizeof (exp, pc, ax, value,
2092                   builtin_type (exp->gdbarch)->builtin_int);
2093       break;
2094
2095     case STRUCTOP_STRUCT:
2096     case STRUCTOP_PTR:
2097       {
2098         int length = (*pc)[1].longconst;
2099         char *name = &(*pc)[2].string;
2100
2101         (*pc) += 4 + BYTES_TO_EXP_ELEM (length + 1);
2102         gen_expr (exp, pc, ax, value);
2103         if (op == STRUCTOP_STRUCT)
2104           gen_struct_ref (exp, ax, value, name, ".", "structure or union");
2105         else if (op == STRUCTOP_PTR)
2106           gen_struct_ref (exp, ax, value, name, "->",
2107                           "pointer to a structure or union");
2108         else
2109           /* If this `if' chain doesn't handle it, then the case list
2110              shouldn't mention it, and we shouldn't be here.  */
2111           internal_error (__FILE__, __LINE__,
2112                           _("gen_expr: unhandled struct case"));
2113       }
2114       break;
2115
2116     case OP_THIS:
2117       {
2118         char *this_name;
2119         struct symbol *func, *sym;
2120         struct block *b;
2121
2122         func = block_linkage_function (block_for_pc (ax->scope));
2123         this_name = language_def (SYMBOL_LANGUAGE (func))->la_name_of_this;
2124         b = SYMBOL_BLOCK_VALUE (func);
2125
2126         /* Calling lookup_block_symbol is necessary to get the LOC_REGISTER
2127            symbol instead of the LOC_ARG one (if both exist).  */
2128         sym = lookup_block_symbol (b, this_name, VAR_DOMAIN);
2129         if (!sym)
2130           error (_("no `%s' found"), this_name);
2131
2132         gen_var_ref (exp->gdbarch, ax, value, sym);
2133
2134         if (value->optimized_out)
2135           error (_("`%s' has been optimized out, cannot use"),
2136                  SYMBOL_PRINT_NAME (sym));
2137
2138         (*pc) += 2;
2139       }
2140       break;
2141
2142     case OP_SCOPE:
2143       {
2144         struct type *type = (*pc)[1].type;
2145         int length = longest_to_int ((*pc)[2].longconst);
2146         char *name = &(*pc)[3].string;
2147         int found;
2148
2149         found = gen_aggregate_elt_ref (exp, ax, value, type, name,
2150                                        "?", "??");
2151         if (!found)
2152           error (_("There is no field named %s"), name);
2153         (*pc) += 5 + BYTES_TO_EXP_ELEM (length + 1);
2154       }
2155       break;
2156
2157     case OP_TYPE:
2158       error (_("Attempt to use a type name as an expression."));
2159
2160     default:
2161       error (_("Unsupported operator %s (%d) in expression."),
2162              op_string (op), op);
2163     }
2164 }
2165
2166 /* This handles the middle-to-right-side of code generation for binary
2167    expressions, which is shared between regular binary operations and
2168    assign-modify (+= and friends) expressions.  */
2169
2170 static void
2171 gen_expr_binop_rest (struct expression *exp,
2172                      enum exp_opcode op, union exp_element **pc,
2173                      struct agent_expr *ax, struct axs_value *value,
2174                      struct axs_value *value1, struct axs_value *value2)
2175 {
2176   struct type *int_type = builtin_type (exp->gdbarch)->builtin_int;
2177
2178   gen_expr (exp, pc, ax, value2);
2179   gen_usual_unary (exp, ax, value2);
2180   gen_usual_arithmetic (exp, ax, value1, value2);
2181   switch (op)
2182     {
2183     case BINOP_ADD:
2184       if (TYPE_CODE (value1->type) == TYPE_CODE_INT
2185           && pointer_type (value2->type))
2186         {
2187           /* Swap the values and proceed normally.  */
2188           ax_simple (ax, aop_swap);
2189           gen_ptradd (ax, value, value2, value1);
2190         }
2191       else if (pointer_type (value1->type)
2192                && TYPE_CODE (value2->type) == TYPE_CODE_INT)
2193         gen_ptradd (ax, value, value1, value2);
2194       else
2195         gen_binop (ax, value, value1, value2,
2196                    aop_add, aop_add, 1, "addition");
2197       break;
2198     case BINOP_SUB:
2199       if (pointer_type (value1->type)
2200           && TYPE_CODE (value2->type) == TYPE_CODE_INT)
2201         gen_ptrsub (ax,value, value1, value2);
2202       else if (pointer_type (value1->type)
2203                && pointer_type (value2->type))
2204         /* FIXME --- result type should be ptrdiff_t */
2205         gen_ptrdiff (ax, value, value1, value2,
2206                      builtin_type (exp->gdbarch)->builtin_long);
2207       else
2208         gen_binop (ax, value, value1, value2,
2209                    aop_sub, aop_sub, 1, "subtraction");
2210       break;
2211     case BINOP_MUL:
2212       gen_binop (ax, value, value1, value2,
2213                  aop_mul, aop_mul, 1, "multiplication");
2214       break;
2215     case BINOP_DIV:
2216       gen_binop (ax, value, value1, value2,
2217                  aop_div_signed, aop_div_unsigned, 1, "division");
2218       break;
2219     case BINOP_REM:
2220       gen_binop (ax, value, value1, value2,
2221                  aop_rem_signed, aop_rem_unsigned, 1, "remainder");
2222       break;
2223     case BINOP_LSH:
2224       gen_binop (ax, value, value1, value2,
2225                  aop_lsh, aop_lsh, 1, "left shift");
2226       break;
2227     case BINOP_RSH:
2228       gen_binop (ax, value, value1, value2,
2229                  aop_rsh_signed, aop_rsh_unsigned, 1, "right shift");
2230       break;
2231     case BINOP_SUBSCRIPT:
2232       {
2233         struct type *type;
2234
2235         if (binop_types_user_defined_p (op, value1->type, value2->type))
2236           {
2237             error (_("\
2238 cannot subscript requested type: cannot call user defined functions"));
2239           }
2240         else
2241           {
2242             /* If the user attempts to subscript something that is not
2243                an array or pointer type (like a plain int variable for
2244                example), then report this as an error.  */
2245             type = check_typedef (value1->type);
2246             if (TYPE_CODE (type) != TYPE_CODE_ARRAY
2247                 && TYPE_CODE (type) != TYPE_CODE_PTR)
2248               {
2249                 if (TYPE_NAME (type))
2250                   error (_("cannot subscript something of type `%s'"),
2251                          TYPE_NAME (type));
2252                 else
2253                   error (_("cannot subscript requested type"));
2254               }
2255           }
2256
2257         if (!is_integral_type (value2->type))
2258           error (_("Argument to arithmetic operation not a number or boolean."));
2259
2260         gen_ptradd (ax, value, value1, value2);
2261         gen_deref (ax, value);
2262         break;
2263       }
2264     case BINOP_BITWISE_AND:
2265       gen_binop (ax, value, value1, value2,
2266                  aop_bit_and, aop_bit_and, 0, "bitwise and");
2267       break;
2268
2269     case BINOP_BITWISE_IOR:
2270       gen_binop (ax, value, value1, value2,
2271                  aop_bit_or, aop_bit_or, 0, "bitwise or");
2272       break;
2273       
2274     case BINOP_BITWISE_XOR:
2275       gen_binop (ax, value, value1, value2,
2276                  aop_bit_xor, aop_bit_xor, 0, "bitwise exclusive-or");
2277       break;
2278
2279     case BINOP_EQUAL:
2280       gen_equal (ax, value, value1, value2, int_type);
2281       break;
2282
2283     case BINOP_NOTEQUAL:
2284       gen_equal (ax, value, value1, value2, int_type);
2285       gen_logical_not (ax, value, int_type);
2286       break;
2287
2288     case BINOP_LESS:
2289       gen_less (ax, value, value1, value2, int_type);
2290       break;
2291
2292     case BINOP_GTR:
2293       ax_simple (ax, aop_swap);
2294       gen_less (ax, value, value1, value2, int_type);
2295       break;
2296
2297     case BINOP_LEQ:
2298       ax_simple (ax, aop_swap);
2299       gen_less (ax, value, value1, value2, int_type);
2300       gen_logical_not (ax, value, int_type);
2301       break;
2302
2303     case BINOP_GEQ:
2304       gen_less (ax, value, value1, value2, int_type);
2305       gen_logical_not (ax, value, int_type);
2306       break;
2307
2308     default:
2309       /* We should only list operators in the outer case statement
2310          that we actually handle in the inner case statement.  */
2311       internal_error (__FILE__, __LINE__,
2312                       _("gen_expr: op case sets don't match"));
2313     }
2314 }
2315 \f
2316
2317 /* Given a single variable and a scope, generate bytecodes to trace
2318    its value.  This is for use in situations where we have only a
2319    variable's name, and no parsed expression; for instance, when the
2320    name comes from a list of local variables of a function.  */
2321
2322 struct agent_expr *
2323 gen_trace_for_var (CORE_ADDR scope, struct gdbarch *gdbarch,
2324                    struct symbol *var)
2325 {
2326   struct cleanup *old_chain = 0;
2327   struct agent_expr *ax = new_agent_expr (scope);
2328   struct axs_value value;
2329
2330   old_chain = make_cleanup_free_agent_expr (ax);
2331
2332   trace_kludge = 1;
2333   gen_var_ref (gdbarch, ax, &value, var);
2334
2335   /* If there is no actual variable to trace, flag it by returning
2336      an empty agent expression.  */
2337   if (value.optimized_out)
2338     {
2339       do_cleanups (old_chain);
2340       return NULL;
2341     }
2342
2343   /* Make sure we record the final object, and get rid of it.  */
2344   gen_traced_pop (gdbarch, ax, &value);
2345
2346   /* Oh, and terminate.  */
2347   ax_simple (ax, aop_end);
2348
2349   /* We have successfully built the agent expr, so cancel the cleanup
2350      request.  If we add more cleanups that we always want done, this
2351      will have to get more complicated.  */
2352   discard_cleanups (old_chain);
2353   return ax;
2354 }
2355
2356 /* Generating bytecode from GDB expressions: driver */
2357
2358 /* Given a GDB expression EXPR, return bytecode to trace its value.
2359    The result will use the `trace' and `trace_quick' bytecodes to
2360    record the value of all memory touched by the expression.  The
2361    caller can then use the ax_reqs function to discover which
2362    registers it relies upon.  */
2363 struct agent_expr *
2364 gen_trace_for_expr (CORE_ADDR scope, struct expression *expr)
2365 {
2366   struct cleanup *old_chain = 0;
2367   struct agent_expr *ax = new_agent_expr (scope);
2368   union exp_element *pc;
2369   struct axs_value value;
2370
2371   old_chain = make_cleanup_free_agent_expr (ax);
2372
2373   pc = expr->elts;
2374   trace_kludge = 1;
2375   gen_expr (expr, &pc, ax, &value);
2376
2377   /* Make sure we record the final object, and get rid of it.  */
2378   gen_traced_pop (expr->gdbarch, ax, &value);
2379
2380   /* Oh, and terminate.  */
2381   ax_simple (ax, aop_end);
2382
2383   /* We have successfully built the agent expr, so cancel the cleanup
2384      request.  If we add more cleanups that we always want done, this
2385      will have to get more complicated.  */
2386   discard_cleanups (old_chain);
2387   return ax;
2388 }
2389
2390 /* Given a GDB expression EXPR, return a bytecode sequence that will
2391    evaluate and return a result.  The bytecodes will do a direct
2392    evaluation, using the current data on the target, rather than
2393    recording blocks of memory and registers for later use, as
2394    gen_trace_for_expr does.  The generated bytecode sequence leaves
2395    the result of expression evaluation on the top of the stack.  */
2396
2397 struct agent_expr *
2398 gen_eval_for_expr (CORE_ADDR scope, struct expression *expr)
2399 {
2400   struct cleanup *old_chain = 0;
2401   struct agent_expr *ax = new_agent_expr (scope);
2402   union exp_element *pc;
2403   struct axs_value value;
2404
2405   old_chain = make_cleanup_free_agent_expr (ax);
2406
2407   pc = expr->elts;
2408   trace_kludge = 0;
2409   gen_expr (expr, &pc, ax, &value);
2410
2411   /* Oh, and terminate.  */
2412   ax_simple (ax, aop_end);
2413
2414   /* We have successfully built the agent expr, so cancel the cleanup
2415      request.  If we add more cleanups that we always want done, this
2416      will have to get more complicated.  */
2417   discard_cleanups (old_chain);
2418   return ax;
2419 }
2420
2421 static void
2422 agent_command (char *exp, int from_tty)
2423 {
2424   struct cleanup *old_chain = 0;
2425   struct expression *expr;
2426   struct agent_expr *agent;
2427   struct frame_info *fi = get_current_frame (); /* need current scope */
2428
2429   /* We don't deal with overlay debugging at the moment.  We need to
2430      think more carefully about this.  If you copy this code into
2431      another command, change the error message; the user shouldn't
2432      have to know anything about agent expressions.  */
2433   if (overlay_debugging)
2434     error (_("GDB can't do agent expression translation with overlays."));
2435
2436   if (exp == 0)
2437     error_no_arg (_("expression to translate"));
2438
2439   expr = parse_expression (exp);
2440   old_chain = make_cleanup (free_current_contents, &expr);
2441   agent = gen_trace_for_expr (get_frame_pc (fi), expr);
2442   make_cleanup_free_agent_expr (agent);
2443   ax_print (gdb_stdout, agent);
2444
2445   /* It would be nice to call ax_reqs here to gather some general info
2446      about the expression, and then print out the result.  */
2447
2448   do_cleanups (old_chain);
2449   dont_repeat ();
2450 }
2451
2452 /* Parse the given expression, compile it into an agent expression
2453    that does direct evaluation, and display the resulting
2454    expression.  */
2455
2456 static void
2457 agent_eval_command (char *exp, int from_tty)
2458 {
2459   struct cleanup *old_chain = 0;
2460   struct expression *expr;
2461   struct agent_expr *agent;
2462   struct frame_info *fi = get_current_frame (); /* need current scope */
2463
2464   /* We don't deal with overlay debugging at the moment.  We need to
2465      think more carefully about this.  If you copy this code into
2466      another command, change the error message; the user shouldn't
2467      have to know anything about agent expressions.  */
2468   if (overlay_debugging)
2469     error (_("GDB can't do agent expression translation with overlays."));
2470
2471   if (exp == 0)
2472     error_no_arg (_("expression to translate"));
2473
2474   expr = parse_expression (exp);
2475   old_chain = make_cleanup (free_current_contents, &expr);
2476   agent = gen_eval_for_expr (get_frame_pc (fi), expr);
2477   make_cleanup_free_agent_expr (agent);
2478   ax_print (gdb_stdout, agent);
2479
2480   /* It would be nice to call ax_reqs here to gather some general info
2481      about the expression, and then print out the result.  */
2482
2483   do_cleanups (old_chain);
2484   dont_repeat ();
2485 }
2486 \f
2487
2488 /* Initialization code.  */
2489
2490 void _initialize_ax_gdb (void);
2491 void
2492 _initialize_ax_gdb (void)
2493 {
2494   add_cmd ("agent", class_maintenance, agent_command,
2495            _("Translate an expression into remote agent bytecode for tracing."),
2496            &maintenancelist);
2497
2498   add_cmd ("agent-eval", class_maintenance, agent_eval_command,
2499            _("Translate an expression into remote agent bytecode for evaluation."),
2500            &maintenancelist);
2501 }