2003-01-13 Andrew Cagney <ac131313@redhat.com>
[platform/upstream/binutils.git] / gdb / ax-gdb.c
1 /* GDB-specific functions for operating on agent expressions.
2
3    Copyright 1998, 1999, 2000, 2001, 2003 Free Software Foundation,
4    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 2 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, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330,
21    Boston, MA 02111-1307, USA.  */
22
23 #include "defs.h"
24 #include "symtab.h"
25 #include "symfile.h"
26 #include "gdbtypes.h"
27 #include "value.h"
28 #include "expression.h"
29 #include "command.h"
30 #include "gdbcmd.h"
31 #include "frame.h"
32 #include "target.h"
33 #include "ax.h"
34 #include "ax-gdb.h"
35 #include "gdb_string.h"
36
37 /* To make sense of this file, you should read doc/agentexpr.texi.
38    Then look at the types and enums in ax-gdb.h.  For the code itself,
39    look at gen_expr, towards the bottom; that's the main function that
40    looks at the GDB expressions and calls everything else to generate
41    code.
42
43    I'm beginning to wonder whether it wouldn't be nicer to internally
44    generate trees, with types, and then spit out the bytecode in
45    linear form afterwards; we could generate fewer `swap', `ext', and
46    `zero_ext' bytecodes that way; it would make good constant folding
47    easier, too.  But at the moment, I think we should be willing to
48    pay for the simplicity of this code with less-than-optimal bytecode
49    strings.
50
51    Remember, "GBD" stands for "Great Britain, Dammit!"  So be careful.  */
52 \f
53
54
55 /* Prototypes for local functions. */
56
57 /* There's a standard order to the arguments of these functions:
58    union exp_element ** --- pointer into expression
59    struct agent_expr * --- agent expression buffer to generate code into
60    struct axs_value * --- describes value left on top of stack  */
61
62 static struct value *const_var_ref (struct symbol *var);
63 static struct value *const_expr (union exp_element **pc);
64 static struct value *maybe_const_expr (union exp_element **pc);
65
66 static void gen_traced_pop (struct agent_expr *, struct axs_value *);
67
68 static void gen_sign_extend (struct agent_expr *, struct type *);
69 static void gen_extend (struct agent_expr *, struct type *);
70 static void gen_fetch (struct agent_expr *, struct type *);
71 static void gen_left_shift (struct agent_expr *, int);
72
73
74 static void gen_frame_args_address (struct agent_expr *);
75 static void gen_frame_locals_address (struct agent_expr *);
76 static void gen_offset (struct agent_expr *ax, int offset);
77 static void gen_sym_offset (struct agent_expr *, struct symbol *);
78 static void gen_var_ref (struct agent_expr *ax,
79                          struct axs_value *value, struct symbol *var);
80
81
82 static void gen_int_literal (struct agent_expr *ax,
83                              struct axs_value *value,
84                              LONGEST k, struct type *type);
85
86
87 static void require_rvalue (struct agent_expr *ax, struct axs_value *value);
88 static void gen_usual_unary (struct agent_expr *ax, struct axs_value *value);
89 static int type_wider_than (struct type *type1, struct type *type2);
90 static struct type *max_type (struct type *type1, struct type *type2);
91 static void gen_conversion (struct agent_expr *ax,
92                             struct type *from, struct type *to);
93 static int is_nontrivial_conversion (struct type *from, struct type *to);
94 static void gen_usual_arithmetic (struct agent_expr *ax,
95                                   struct axs_value *value1,
96                                   struct axs_value *value2);
97 static void gen_integral_promotions (struct agent_expr *ax,
98                                      struct axs_value *value);
99 static void gen_cast (struct agent_expr *ax,
100                       struct axs_value *value, struct type *type);
101 static void gen_scale (struct agent_expr *ax,
102                        enum agent_op op, struct type *type);
103 static void gen_add (struct agent_expr *ax,
104                      struct axs_value *value,
105                      struct axs_value *value1,
106                      struct axs_value *value2, char *name);
107 static void gen_sub (struct agent_expr *ax,
108                      struct axs_value *value,
109                      struct axs_value *value1, struct axs_value *value2);
110 static void gen_binop (struct agent_expr *ax,
111                        struct axs_value *value,
112                        struct axs_value *value1,
113                        struct axs_value *value2,
114                        enum agent_op op,
115                        enum agent_op op_unsigned, int may_carry, char *name);
116 static void gen_logical_not (struct agent_expr *ax, struct axs_value *value);
117 static void gen_complement (struct agent_expr *ax, struct axs_value *value);
118 static void gen_deref (struct agent_expr *, struct axs_value *);
119 static void gen_address_of (struct agent_expr *, struct axs_value *);
120 static int find_field (struct type *type, char *name);
121 static void gen_bitfield_ref (struct agent_expr *ax,
122                               struct axs_value *value,
123                               struct type *type, int start, int end);
124 static void gen_struct_ref (struct agent_expr *ax,
125                             struct axs_value *value,
126                             char *field,
127                             char *operator_name, char *operand_name);
128 static void gen_repeat (union exp_element **pc,
129                         struct agent_expr *ax, struct axs_value *value);
130 static void gen_sizeof (union exp_element **pc,
131                         struct agent_expr *ax, struct axs_value *value);
132 static void gen_expr (union exp_element **pc,
133                       struct agent_expr *ax, struct axs_value *value);
134
135 static void print_axs_value (struct ui_file *f, struct axs_value * value);
136 static void agent_command (char *exp, int from_tty);
137 \f
138
139 /* Detecting constant expressions.  */
140
141 /* If the variable reference at *PC is a constant, return its value.
142    Otherwise, return zero.
143
144    Hey, Wally!  How can a variable reference be a constant?
145
146    Well, Beav, this function really handles the OP_VAR_VALUE operator,
147    not specifically variable references.  GDB uses OP_VAR_VALUE to
148    refer to any kind of symbolic reference: function names, enum
149    elements, and goto labels are all handled through the OP_VAR_VALUE
150    operator, even though they're constants.  It makes sense given the
151    situation.
152
153    Gee, Wally, don'cha wonder sometimes if data representations that
154    subvert commonly accepted definitions of terms in favor of heavily
155    context-specific interpretations are really just a tool of the
156    programming hegemony to preserve their power and exclude the
157    proletariat?  */
158
159 static struct value *
160 const_var_ref (struct symbol *var)
161 {
162   struct type *type = SYMBOL_TYPE (var);
163
164   switch (SYMBOL_CLASS (var))
165     {
166     case LOC_CONST:
167       return value_from_longest (type, (LONGEST) SYMBOL_VALUE (var));
168
169     case LOC_LABEL:
170       return value_from_pointer (type, (CORE_ADDR) SYMBOL_VALUE_ADDRESS (var));
171
172     default:
173       return 0;
174     }
175 }
176
177
178 /* If the expression starting at *PC has a constant value, return it.
179    Otherwise, return zero.  If we return a value, then *PC will be
180    advanced to the end of it.  If we return zero, *PC could be
181    anywhere.  */
182 static struct value *
183 const_expr (union exp_element **pc)
184 {
185   enum exp_opcode op = (*pc)->opcode;
186   struct value *v1;
187
188   switch (op)
189     {
190     case OP_LONG:
191       {
192         struct type *type = (*pc)[1].type;
193         LONGEST k = (*pc)[2].longconst;
194         (*pc) += 4;
195         return value_from_longest (type, k);
196       }
197
198     case OP_VAR_VALUE:
199       {
200         struct value *v = const_var_ref ((*pc)[2].symbol);
201         (*pc) += 4;
202         return v;
203       }
204
205       /* We could add more operators in here.  */
206
207     case UNOP_NEG:
208       (*pc)++;
209       v1 = const_expr (pc);
210       if (v1)
211         return value_neg (v1);
212       else
213         return 0;
214
215     default:
216       return 0;
217     }
218 }
219
220
221 /* Like const_expr, but guarantee also that *PC is undisturbed if the
222    expression is not constant.  */
223 static struct value *
224 maybe_const_expr (union exp_element **pc)
225 {
226   union exp_element *tentative_pc = *pc;
227   struct value *v = const_expr (&tentative_pc);
228
229   /* If we got a value, then update the real PC.  */
230   if (v)
231     *pc = tentative_pc;
232
233   return v;
234 }
235 \f
236
237 /* Generating bytecode from GDB expressions: general assumptions */
238
239 /* Here are a few general assumptions made throughout the code; if you
240    want to make a change that contradicts one of these, then you'd
241    better scan things pretty thoroughly.
242
243    - We assume that all values occupy one stack element.  For example,
244    sometimes we'll swap to get at the left argument to a binary
245    operator.  If we decide that void values should occupy no stack
246    elements, or that synthetic arrays (whose size is determined at
247    run time, created by the `@' operator) should occupy two stack
248    elements (address and length), then this will cause trouble.
249
250    - We assume the stack elements are infinitely wide, and that we
251    don't have to worry what happens if the user requests an
252    operation that is wider than the actual interpreter's stack.
253    That is, it's up to the interpreter to handle directly all the
254    integer widths the user has access to.  (Woe betide the language
255    with bignums!)
256
257    - We don't support side effects.  Thus, we don't have to worry about
258    GCC's generalized lvalues, function calls, etc.
259
260    - We don't support floating point.  Many places where we switch on
261    some type don't bother to include cases for floating point; there
262    may be even more subtle ways this assumption exists.  For
263    example, the arguments to % must be integers.
264
265    - We assume all subexpressions have a static, unchanging type.  If
266    we tried to support convenience variables, this would be a
267    problem.
268
269    - All values on the stack should always be fully zero- or
270    sign-extended.
271
272    (I wasn't sure whether to choose this or its opposite --- that
273    only addresses are assumed extended --- but it turns out that
274    neither convention completely eliminates spurious extend
275    operations (if everything is always extended, then you have to
276    extend after add, because it could overflow; if nothing is
277    extended, then you end up producing extends whenever you change
278    sizes), and this is simpler.)  */
279 \f
280
281 /* Generating bytecode from GDB expressions: the `trace' kludge  */
282
283 /* The compiler in this file is a general-purpose mechanism for
284    translating GDB expressions into bytecode.  One ought to be able to
285    find a million and one uses for it.
286
287    However, at the moment it is HOPELESSLY BRAIN-DAMAGED for the sake
288    of expediency.  Let he who is without sin cast the first stone.
289
290    For the data tracing facility, we need to insert `trace' bytecodes
291    before each data fetch; this records all the memory that the
292    expression touches in the course of evaluation, so that memory will
293    be available when the user later tries to evaluate the expression
294    in GDB.
295
296    This should be done (I think) in a post-processing pass, that walks
297    an arbitrary agent expression and inserts `trace' operations at the
298    appropriate points.  But it's much faster to just hack them
299    directly into the code.  And since we're in a crunch, that's what
300    I've done.
301
302    Setting the flag trace_kludge to non-zero enables the code that
303    emits the trace bytecodes at the appropriate points.  */
304 static int trace_kludge;
305
306 /* Trace the lvalue on the stack, if it needs it.  In either case, pop
307    the value.  Useful on the left side of a comma, and at the end of
308    an expression being used for tracing.  */
309 static void
310 gen_traced_pop (struct agent_expr *ax, struct axs_value *value)
311 {
312   if (trace_kludge)
313     switch (value->kind)
314       {
315       case axs_rvalue:
316         /* We don't trace rvalues, just the lvalues necessary to
317            produce them.  So just dispose of this value.  */
318         ax_simple (ax, aop_pop);
319         break;
320
321       case axs_lvalue_memory:
322         {
323           int length = TYPE_LENGTH (value->type);
324
325           /* There's no point in trying to use a trace_quick bytecode
326              here, since "trace_quick SIZE pop" is three bytes, whereas
327              "const8 SIZE trace" is also three bytes, does the same
328              thing, and the simplest code which generates that will also
329              work correctly for objects with large sizes.  */
330           ax_const_l (ax, length);
331           ax_simple (ax, aop_trace);
332         }
333         break;
334
335       case axs_lvalue_register:
336         /* We need to mention the register somewhere in the bytecode,
337            so ax_reqs will pick it up and add it to the mask of
338            registers used.  */
339         ax_reg (ax, value->u.reg);
340         ax_simple (ax, aop_pop);
341         break;
342       }
343   else
344     /* If we're not tracing, just pop the value.  */
345     ax_simple (ax, aop_pop);
346 }
347 \f
348
349
350 /* Generating bytecode from GDB expressions: helper functions */
351
352 /* Assume that the lower bits of the top of the stack is a value of
353    type TYPE, and the upper bits are zero.  Sign-extend if necessary.  */
354 static void
355 gen_sign_extend (struct agent_expr *ax, struct type *type)
356 {
357   /* Do we need to sign-extend this?  */
358   if (!TYPE_UNSIGNED (type))
359     ax_ext (ax, TYPE_LENGTH (type) * TARGET_CHAR_BIT);
360 }
361
362
363 /* Assume the lower bits of the top of the stack hold a value of type
364    TYPE, and the upper bits are garbage.  Sign-extend or truncate as
365    needed.  */
366 static void
367 gen_extend (struct agent_expr *ax, struct type *type)
368 {
369   int bits = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
370   /* I just had to.  */
371   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, bits));
372 }
373
374
375 /* Assume that the top of the stack contains a value of type "pointer
376    to TYPE"; generate code to fetch its value.  Note that TYPE is the
377    target type, not the pointer type.  */
378 static void
379 gen_fetch (struct agent_expr *ax, struct type *type)
380 {
381   if (trace_kludge)
382     {
383       /* Record the area of memory we're about to fetch.  */
384       ax_trace_quick (ax, TYPE_LENGTH (type));
385     }
386
387   switch (TYPE_CODE (type))
388     {
389     case TYPE_CODE_PTR:
390     case TYPE_CODE_ENUM:
391     case TYPE_CODE_INT:
392     case TYPE_CODE_CHAR:
393       /* It's a scalar value, so we know how to dereference it.  How
394          many bytes long is it?  */
395       switch (TYPE_LENGTH (type))
396         {
397         case 8 / TARGET_CHAR_BIT:
398           ax_simple (ax, aop_ref8);
399           break;
400         case 16 / TARGET_CHAR_BIT:
401           ax_simple (ax, aop_ref16);
402           break;
403         case 32 / TARGET_CHAR_BIT:
404           ax_simple (ax, aop_ref32);
405           break;
406         case 64 / TARGET_CHAR_BIT:
407           ax_simple (ax, aop_ref64);
408           break;
409
410           /* Either our caller shouldn't have asked us to dereference
411              that pointer (other code's fault), or we're not
412              implementing something we should be (this code's fault).
413              In any case, it's a bug the user shouldn't see.  */
414         default:
415           internal_error (__FILE__, __LINE__,
416                           "gen_fetch: strange size");
417         }
418
419       gen_sign_extend (ax, type);
420       break;
421
422     default:
423       /* Either our caller shouldn't have asked us to dereference that
424          pointer (other code's fault), or we're not implementing
425          something we should be (this code's fault).  In any case,
426          it's a bug the user shouldn't see.  */
427       internal_error (__FILE__, __LINE__,
428                       "gen_fetch: bad type code");
429     }
430 }
431
432
433 /* Generate code to left shift the top of the stack by DISTANCE bits, or
434    right shift it by -DISTANCE bits if DISTANCE < 0.  This generates
435    unsigned (logical) right shifts.  */
436 static void
437 gen_left_shift (struct agent_expr *ax, int distance)
438 {
439   if (distance > 0)
440     {
441       ax_const_l (ax, distance);
442       ax_simple (ax, aop_lsh);
443     }
444   else if (distance < 0)
445     {
446       ax_const_l (ax, -distance);
447       ax_simple (ax, aop_rsh_unsigned);
448     }
449 }
450 \f
451
452
453 /* Generating bytecode from GDB expressions: symbol references */
454
455 /* Generate code to push the base address of the argument portion of
456    the top stack frame.  */
457 static void
458 gen_frame_args_address (struct agent_expr *ax)
459 {
460   int frame_reg;
461   LONGEST frame_offset;
462
463   TARGET_VIRTUAL_FRAME_POINTER (ax->scope, &frame_reg, &frame_offset);
464   ax_reg (ax, frame_reg);
465   gen_offset (ax, frame_offset);
466 }
467
468
469 /* Generate code to push the base address of the locals portion of the
470    top stack frame.  */
471 static void
472 gen_frame_locals_address (struct agent_expr *ax)
473 {
474   int frame_reg;
475   LONGEST frame_offset;
476
477   TARGET_VIRTUAL_FRAME_POINTER (ax->scope, &frame_reg, &frame_offset);
478   ax_reg (ax, frame_reg);
479   gen_offset (ax, frame_offset);
480 }
481
482
483 /* Generate code to add OFFSET to the top of the stack.  Try to
484    generate short and readable code.  We use this for getting to
485    variables on the stack, and structure members.  If we were
486    programming in ML, it would be clearer why these are the same
487    thing.  */
488 static void
489 gen_offset (struct agent_expr *ax, int offset)
490 {
491   /* It would suffice to simply push the offset and add it, but this
492      makes it easier to read positive and negative offsets in the
493      bytecode.  */
494   if (offset > 0)
495     {
496       ax_const_l (ax, offset);
497       ax_simple (ax, aop_add);
498     }
499   else if (offset < 0)
500     {
501       ax_const_l (ax, -offset);
502       ax_simple (ax, aop_sub);
503     }
504 }
505
506
507 /* In many cases, a symbol's value is the offset from some other
508    address (stack frame, base register, etc.)  Generate code to add
509    VAR's value to the top of the stack.  */
510 static void
511 gen_sym_offset (struct agent_expr *ax, struct symbol *var)
512 {
513   gen_offset (ax, SYMBOL_VALUE (var));
514 }
515
516
517 /* Generate code for a variable reference to AX.  The variable is the
518    symbol VAR.  Set VALUE to describe the result.  */
519
520 static void
521 gen_var_ref (struct agent_expr *ax, struct axs_value *value, struct symbol *var)
522 {
523   /* Dereference any typedefs. */
524   value->type = check_typedef (SYMBOL_TYPE (var));
525
526   /* I'm imitating the code in read_var_value.  */
527   switch (SYMBOL_CLASS (var))
528     {
529     case LOC_CONST:             /* A constant, like an enum value.  */
530       ax_const_l (ax, (LONGEST) SYMBOL_VALUE (var));
531       value->kind = axs_rvalue;
532       break;
533
534     case LOC_LABEL:             /* A goto label, being used as a value.  */
535       ax_const_l (ax, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
536       value->kind = axs_rvalue;
537       break;
538
539     case LOC_CONST_BYTES:
540       internal_error (__FILE__, __LINE__,
541                       "gen_var_ref: LOC_CONST_BYTES symbols are not supported");
542
543       /* Variable at a fixed location in memory.  Easy.  */
544     case LOC_STATIC:
545       /* Push the address of the variable.  */
546       ax_const_l (ax, SYMBOL_VALUE_ADDRESS (var));
547       value->kind = axs_lvalue_memory;
548       break;
549
550     case LOC_ARG:               /* var lives in argument area of frame */
551       gen_frame_args_address (ax);
552       gen_sym_offset (ax, var);
553       value->kind = axs_lvalue_memory;
554       break;
555
556     case LOC_REF_ARG:           /* As above, but the frame slot really
557                                    holds the address of the variable.  */
558       gen_frame_args_address (ax);
559       gen_sym_offset (ax, var);
560       /* Don't assume any particular pointer size.  */
561       gen_fetch (ax, lookup_pointer_type (builtin_type_void));
562       value->kind = axs_lvalue_memory;
563       break;
564
565     case LOC_LOCAL:             /* var lives in locals area of frame */
566     case LOC_LOCAL_ARG:
567       gen_frame_locals_address (ax);
568       gen_sym_offset (ax, var);
569       value->kind = axs_lvalue_memory;
570       break;
571
572     case LOC_BASEREG:           /* relative to some base register */
573     case LOC_BASEREG_ARG:
574       ax_reg (ax, SYMBOL_BASEREG (var));
575       gen_sym_offset (ax, var);
576       value->kind = axs_lvalue_memory;
577       break;
578
579     case LOC_TYPEDEF:
580       error ("Cannot compute value of typedef `%s'.",
581              SYMBOL_SOURCE_NAME (var));
582       break;
583
584     case LOC_BLOCK:
585       ax_const_l (ax, BLOCK_START (SYMBOL_BLOCK_VALUE (var)));
586       value->kind = axs_rvalue;
587       break;
588
589     case LOC_REGISTER:
590     case LOC_REGPARM:
591       /* Don't generate any code at all; in the process of treating
592          this as an lvalue or rvalue, the caller will generate the
593          right code.  */
594       value->kind = axs_lvalue_register;
595       value->u.reg = SYMBOL_VALUE (var);
596       break;
597
598       /* A lot like LOC_REF_ARG, but the pointer lives directly in a
599          register, not on the stack.  Simpler than LOC_REGISTER and
600          LOC_REGPARM, because it's just like any other case where the
601          thing has a real address.  */
602     case LOC_REGPARM_ADDR:
603       ax_reg (ax, SYMBOL_VALUE (var));
604       value->kind = axs_lvalue_memory;
605       break;
606
607     case LOC_UNRESOLVED:
608       {
609         struct minimal_symbol *msym
610         = lookup_minimal_symbol (SYMBOL_NAME (var), NULL, NULL);
611         if (!msym)
612           error ("Couldn't resolve symbol `%s'.", SYMBOL_SOURCE_NAME (var));
613
614         /* Push the address of the variable.  */
615         ax_const_l (ax, SYMBOL_VALUE_ADDRESS (msym));
616         value->kind = axs_lvalue_memory;
617       }
618       break;
619
620     case LOC_OPTIMIZED_OUT:
621       error ("The variable `%s' has been optimized out.",
622              SYMBOL_SOURCE_NAME (var));
623       break;
624
625     default:
626       error ("Cannot find value of botched symbol `%s'.",
627              SYMBOL_SOURCE_NAME (var));
628       break;
629     }
630 }
631 \f
632
633
634 /* Generating bytecode from GDB expressions: literals */
635
636 static void
637 gen_int_literal (struct agent_expr *ax, struct axs_value *value, LONGEST k,
638                  struct type *type)
639 {
640   ax_const_l (ax, k);
641   value->kind = axs_rvalue;
642   value->type = type;
643 }
644 \f
645
646
647 /* Generating bytecode from GDB expressions: unary conversions, casts */
648
649 /* Take what's on the top of the stack (as described by VALUE), and
650    try to make an rvalue out of it.  Signal an error if we can't do
651    that.  */
652 static void
653 require_rvalue (struct agent_expr *ax, struct axs_value *value)
654 {
655   switch (value->kind)
656     {
657     case axs_rvalue:
658       /* It's already an rvalue.  */
659       break;
660
661     case axs_lvalue_memory:
662       /* The top of stack is the address of the object.  Dereference.  */
663       gen_fetch (ax, value->type);
664       break;
665
666     case axs_lvalue_register:
667       /* There's nothing on the stack, but value->u.reg is the
668          register number containing the value.
669
670          When we add floating-point support, this is going to have to
671          change.  What about SPARC register pairs, for example?  */
672       ax_reg (ax, value->u.reg);
673       gen_extend (ax, value->type);
674       break;
675     }
676
677   value->kind = axs_rvalue;
678 }
679
680
681 /* Assume the top of the stack is described by VALUE, and perform the
682    usual unary conversions.  This is motivated by ANSI 6.2.2, but of
683    course GDB expressions are not ANSI; they're the mishmash union of
684    a bunch of languages.  Rah.
685
686    NOTE!  This function promises to produce an rvalue only when the
687    incoming value is of an appropriate type.  In other words, the
688    consumer of the value this function produces may assume the value
689    is an rvalue only after checking its type.
690
691    The immediate issue is that if the user tries to use a structure or
692    union as an operand of, say, the `+' operator, we don't want to try
693    to convert that structure to an rvalue; require_rvalue will bomb on
694    structs and unions.  Rather, we want to simply pass the struct
695    lvalue through unchanged, and let `+' raise an error.  */
696
697 static void
698 gen_usual_unary (struct agent_expr *ax, struct axs_value *value)
699 {
700   /* We don't have to generate any code for the usual integral
701      conversions, since values are always represented as full-width on
702      the stack.  Should we tweak the type?  */
703
704   /* Some types require special handling.  */
705   switch (TYPE_CODE (value->type))
706     {
707       /* Functions get converted to a pointer to the function.  */
708     case TYPE_CODE_FUNC:
709       value->type = lookup_pointer_type (value->type);
710       value->kind = axs_rvalue; /* Should always be true, but just in case.  */
711       break;
712
713       /* Arrays get converted to a pointer to their first element, and
714          are no longer an lvalue.  */
715     case TYPE_CODE_ARRAY:
716       {
717         struct type *elements = TYPE_TARGET_TYPE (value->type);
718         value->type = lookup_pointer_type (elements);
719         value->kind = axs_rvalue;
720         /* We don't need to generate any code; the address of the array
721            is also the address of its first element.  */
722       }
723       break;
724
725       /* Don't try to convert structures and unions to rvalues.  Let the
726          consumer signal an error.  */
727     case TYPE_CODE_STRUCT:
728     case TYPE_CODE_UNION:
729       return;
730
731       /* If the value is an enum, call it an integer.  */
732     case TYPE_CODE_ENUM:
733       value->type = builtin_type_int;
734       break;
735     }
736
737   /* If the value is an lvalue, dereference it.  */
738   require_rvalue (ax, value);
739 }
740
741
742 /* Return non-zero iff the type TYPE1 is considered "wider" than the
743    type TYPE2, according to the rules described in gen_usual_arithmetic.  */
744 static int
745 type_wider_than (struct type *type1, struct type *type2)
746 {
747   return (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)
748           || (TYPE_LENGTH (type1) == TYPE_LENGTH (type2)
749               && TYPE_UNSIGNED (type1)
750               && !TYPE_UNSIGNED (type2)));
751 }
752
753
754 /* Return the "wider" of the two types TYPE1 and TYPE2.  */
755 static struct type *
756 max_type (struct type *type1, struct type *type2)
757 {
758   return type_wider_than (type1, type2) ? type1 : type2;
759 }
760
761
762 /* Generate code to convert a scalar value of type FROM to type TO.  */
763 static void
764 gen_conversion (struct agent_expr *ax, struct type *from, struct type *to)
765 {
766   /* Perhaps there is a more graceful way to state these rules.  */
767
768   /* If we're converting to a narrower type, then we need to clear out
769      the upper bits.  */
770   if (TYPE_LENGTH (to) < TYPE_LENGTH (from))
771     gen_extend (ax, from);
772
773   /* If the two values have equal width, but different signednesses,
774      then we need to extend.  */
775   else if (TYPE_LENGTH (to) == TYPE_LENGTH (from))
776     {
777       if (TYPE_UNSIGNED (from) != TYPE_UNSIGNED (to))
778         gen_extend (ax, to);
779     }
780
781   /* If we're converting to a wider type, and becoming unsigned, then
782      we need to zero out any possible sign bits.  */
783   else if (TYPE_LENGTH (to) > TYPE_LENGTH (from))
784     {
785       if (TYPE_UNSIGNED (to))
786         gen_extend (ax, to);
787     }
788 }
789
790
791 /* Return non-zero iff the type FROM will require any bytecodes to be
792    emitted to be converted to the type TO.  */
793 static int
794 is_nontrivial_conversion (struct type *from, struct type *to)
795 {
796   struct agent_expr *ax = new_agent_expr (0);
797   int nontrivial;
798
799   /* Actually generate the code, and see if anything came out.  At the
800      moment, it would be trivial to replicate the code in
801      gen_conversion here, but in the future, when we're supporting
802      floating point and the like, it may not be.  Doing things this
803      way allows this function to be independent of the logic in
804      gen_conversion.  */
805   gen_conversion (ax, from, to);
806   nontrivial = ax->len > 0;
807   free_agent_expr (ax);
808   return nontrivial;
809 }
810
811
812 /* Generate code to perform the "usual arithmetic conversions" (ANSI C
813    6.2.1.5) for the two operands of an arithmetic operator.  This
814    effectively finds a "least upper bound" type for the two arguments,
815    and promotes each argument to that type.  *VALUE1 and *VALUE2
816    describe the values as they are passed in, and as they are left.  */
817 static void
818 gen_usual_arithmetic (struct agent_expr *ax, struct axs_value *value1,
819                       struct axs_value *value2)
820 {
821   /* Do the usual binary conversions.  */
822   if (TYPE_CODE (value1->type) == TYPE_CODE_INT
823       && TYPE_CODE (value2->type) == TYPE_CODE_INT)
824     {
825       /* The ANSI integral promotions seem to work this way: Order the
826          integer types by size, and then by signedness: an n-bit
827          unsigned type is considered "wider" than an n-bit signed
828          type.  Promote to the "wider" of the two types, and always
829          promote at least to int.  */
830       struct type *target = max_type (builtin_type_int,
831                                       max_type (value1->type, value2->type));
832
833       /* Deal with value2, on the top of the stack.  */
834       gen_conversion (ax, value2->type, target);
835
836       /* Deal with value1, not on the top of the stack.  Don't
837          generate the `swap' instructions if we're not actually going
838          to do anything.  */
839       if (is_nontrivial_conversion (value1->type, target))
840         {
841           ax_simple (ax, aop_swap);
842           gen_conversion (ax, value1->type, target);
843           ax_simple (ax, aop_swap);
844         }
845
846       value1->type = value2->type = target;
847     }
848 }
849
850
851 /* Generate code to perform the integral promotions (ANSI 6.2.1.1) on
852    the value on the top of the stack, as described by VALUE.  Assume
853    the value has integral type.  */
854 static void
855 gen_integral_promotions (struct agent_expr *ax, struct axs_value *value)
856 {
857   if (!type_wider_than (value->type, builtin_type_int))
858     {
859       gen_conversion (ax, value->type, builtin_type_int);
860       value->type = builtin_type_int;
861     }
862   else if (!type_wider_than (value->type, builtin_type_unsigned_int))
863     {
864       gen_conversion (ax, value->type, builtin_type_unsigned_int);
865       value->type = builtin_type_unsigned_int;
866     }
867 }
868
869
870 /* Generate code for a cast to TYPE.  */
871 static void
872 gen_cast (struct agent_expr *ax, struct axs_value *value, struct type *type)
873 {
874   /* GCC does allow casts to yield lvalues, so this should be fixed
875      before merging these changes into the trunk.  */
876   require_rvalue (ax, value);
877   /* Dereference typedefs. */
878   type = check_typedef (type);
879
880   switch (TYPE_CODE (type))
881     {
882     case TYPE_CODE_PTR:
883       /* It's implementation-defined, and I'll bet this is what GCC
884          does.  */
885       break;
886
887     case TYPE_CODE_ARRAY:
888     case TYPE_CODE_STRUCT:
889     case TYPE_CODE_UNION:
890     case TYPE_CODE_FUNC:
891       error ("Illegal type cast: intended type must be scalar.");
892
893     case TYPE_CODE_ENUM:
894       /* We don't have to worry about the size of the value, because
895          all our integral values are fully sign-extended, and when
896          casting pointers we can do anything we like.  Is there any
897          way for us to actually know what GCC actually does with a
898          cast like this?  */
899       value->type = type;
900       break;
901
902     case TYPE_CODE_INT:
903       gen_conversion (ax, value->type, type);
904       break;
905
906     case TYPE_CODE_VOID:
907       /* We could pop the value, and rely on everyone else to check
908          the type and notice that this value doesn't occupy a stack
909          slot.  But for now, leave the value on the stack, and
910          preserve the "value == stack element" assumption.  */
911       break;
912
913     default:
914       error ("Casts to requested type are not yet implemented.");
915     }
916
917   value->type = type;
918 }
919 \f
920
921
922 /* Generating bytecode from GDB expressions: arithmetic */
923
924 /* Scale the integer on the top of the stack by the size of the target
925    of the pointer type TYPE.  */
926 static void
927 gen_scale (struct agent_expr *ax, enum agent_op op, struct type *type)
928 {
929   struct type *element = TYPE_TARGET_TYPE (type);
930
931   if (TYPE_LENGTH (element) != 1)
932     {
933       ax_const_l (ax, TYPE_LENGTH (element));
934       ax_simple (ax, op);
935     }
936 }
937
938
939 /* Generate code for an addition; non-trivial because we deal with
940    pointer arithmetic.  We set VALUE to describe the result value; we
941    assume VALUE1 and VALUE2 describe the two operands, and that
942    they've undergone the usual binary conversions.  Used by both
943    BINOP_ADD and BINOP_SUBSCRIPT.  NAME is used in error messages.  */
944 static void
945 gen_add (struct agent_expr *ax, struct axs_value *value,
946          struct axs_value *value1, struct axs_value *value2, char *name)
947 {
948   /* Is it INT+PTR?  */
949   if (TYPE_CODE (value1->type) == TYPE_CODE_INT
950       && TYPE_CODE (value2->type) == TYPE_CODE_PTR)
951     {
952       /* Swap the values and proceed normally.  */
953       ax_simple (ax, aop_swap);
954       gen_scale (ax, aop_mul, value2->type);
955       ax_simple (ax, aop_add);
956       gen_extend (ax, value2->type);    /* Catch overflow.  */
957       value->type = value2->type;
958     }
959
960   /* Is it PTR+INT?  */
961   else if (TYPE_CODE (value1->type) == TYPE_CODE_PTR
962            && TYPE_CODE (value2->type) == TYPE_CODE_INT)
963     {
964       gen_scale (ax, aop_mul, value1->type);
965       ax_simple (ax, aop_add);
966       gen_extend (ax, value1->type);    /* Catch overflow.  */
967       value->type = value1->type;
968     }
969
970   /* Must be number + number; the usual binary conversions will have
971      brought them both to the same width.  */
972   else if (TYPE_CODE (value1->type) == TYPE_CODE_INT
973            && TYPE_CODE (value2->type) == TYPE_CODE_INT)
974     {
975       ax_simple (ax, aop_add);
976       gen_extend (ax, value1->type);    /* Catch overflow.  */
977       value->type = value1->type;
978     }
979
980   else
981     error ("Illegal combination of types in %s.", name);
982
983   value->kind = axs_rvalue;
984 }
985
986
987 /* Generate code for an addition; non-trivial because we have to deal
988    with pointer arithmetic.  We set VALUE to describe the result
989    value; we assume VALUE1 and VALUE2 describe the two operands, and
990    that they've undergone the usual binary conversions.  */
991 static void
992 gen_sub (struct agent_expr *ax, struct axs_value *value,
993          struct axs_value *value1, struct axs_value *value2)
994 {
995   if (TYPE_CODE (value1->type) == TYPE_CODE_PTR)
996     {
997       /* Is it PTR - INT?  */
998       if (TYPE_CODE (value2->type) == TYPE_CODE_INT)
999         {
1000           gen_scale (ax, aop_mul, value1->type);
1001           ax_simple (ax, aop_sub);
1002           gen_extend (ax, value1->type);        /* Catch overflow.  */
1003           value->type = value1->type;
1004         }
1005
1006       /* Is it PTR - PTR?  Strictly speaking, the types ought to
1007          match, but this is what the normal GDB expression evaluator
1008          tests for.  */
1009       else if (TYPE_CODE (value2->type) == TYPE_CODE_PTR
1010                && (TYPE_LENGTH (TYPE_TARGET_TYPE (value1->type))
1011                    == TYPE_LENGTH (TYPE_TARGET_TYPE (value2->type))))
1012         {
1013           ax_simple (ax, aop_sub);
1014           gen_scale (ax, aop_div_unsigned, value1->type);
1015           value->type = builtin_type_long;      /* FIXME --- should be ptrdiff_t */
1016         }
1017       else
1018         error ("\
1019 First argument of `-' is a pointer, but second argument is neither\n\
1020 an integer nor a pointer of the same type.");
1021     }
1022
1023   /* Must be number + number.  */
1024   else if (TYPE_CODE (value1->type) == TYPE_CODE_INT
1025            && TYPE_CODE (value2->type) == TYPE_CODE_INT)
1026     {
1027       ax_simple (ax, aop_sub);
1028       gen_extend (ax, value1->type);    /* Catch overflow.  */
1029       value->type = value1->type;
1030     }
1031
1032   else
1033     error ("Illegal combination of types in subtraction.");
1034
1035   value->kind = axs_rvalue;
1036 }
1037
1038 /* Generate code for a binary operator that doesn't do pointer magic.
1039    We set VALUE to describe the result value; we assume VALUE1 and
1040    VALUE2 describe the two operands, and that they've undergone the
1041    usual binary conversions.  MAY_CARRY should be non-zero iff the
1042    result needs to be extended.  NAME is the English name of the
1043    operator, used in error messages */
1044 static void
1045 gen_binop (struct agent_expr *ax, struct axs_value *value,
1046            struct axs_value *value1, struct axs_value *value2, enum agent_op op,
1047            enum agent_op op_unsigned, int may_carry, char *name)
1048 {
1049   /* We only handle INT op INT.  */
1050   if ((TYPE_CODE (value1->type) != TYPE_CODE_INT)
1051       || (TYPE_CODE (value2->type) != TYPE_CODE_INT))
1052     error ("Illegal combination of types in %s.", name);
1053
1054   ax_simple (ax,
1055              TYPE_UNSIGNED (value1->type) ? op_unsigned : op);
1056   if (may_carry)
1057     gen_extend (ax, value1->type);      /* catch overflow */
1058   value->type = value1->type;
1059   value->kind = axs_rvalue;
1060 }
1061
1062
1063 static void
1064 gen_logical_not (struct agent_expr *ax, struct axs_value *value)
1065 {
1066   if (TYPE_CODE (value->type) != TYPE_CODE_INT
1067       && TYPE_CODE (value->type) != TYPE_CODE_PTR)
1068     error ("Illegal type of operand to `!'.");
1069
1070   gen_usual_unary (ax, value);
1071   ax_simple (ax, aop_log_not);
1072   value->type = builtin_type_int;
1073 }
1074
1075
1076 static void
1077 gen_complement (struct agent_expr *ax, struct axs_value *value)
1078 {
1079   if (TYPE_CODE (value->type) != TYPE_CODE_INT)
1080     error ("Illegal type of operand to `~'.");
1081
1082   gen_usual_unary (ax, value);
1083   gen_integral_promotions (ax, value);
1084   ax_simple (ax, aop_bit_not);
1085   gen_extend (ax, value->type);
1086 }
1087 \f
1088
1089
1090 /* Generating bytecode from GDB expressions: * & . -> @ sizeof */
1091
1092 /* Dereference the value on the top of the stack.  */
1093 static void
1094 gen_deref (struct agent_expr *ax, struct axs_value *value)
1095 {
1096   /* The caller should check the type, because several operators use
1097      this, and we don't know what error message to generate.  */
1098   if (TYPE_CODE (value->type) != TYPE_CODE_PTR)
1099     internal_error (__FILE__, __LINE__,
1100                     "gen_deref: expected a pointer");
1101
1102   /* We've got an rvalue now, which is a pointer.  We want to yield an
1103      lvalue, whose address is exactly that pointer.  So we don't
1104      actually emit any code; we just change the type from "Pointer to
1105      T" to "T", and mark the value as an lvalue in memory.  Leave it
1106      to the consumer to actually dereference it.  */
1107   value->type = check_typedef (TYPE_TARGET_TYPE (value->type));
1108   value->kind = ((TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1109                  ? axs_rvalue : axs_lvalue_memory);
1110 }
1111
1112
1113 /* Produce the address of the lvalue on the top of the stack.  */
1114 static void
1115 gen_address_of (struct agent_expr *ax, struct axs_value *value)
1116 {
1117   /* Special case for taking the address of a function.  The ANSI
1118      standard describes this as a special case, too, so this
1119      arrangement is not without motivation.  */
1120   if (TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1121     /* The value's already an rvalue on the stack, so we just need to
1122        change the type.  */
1123     value->type = lookup_pointer_type (value->type);
1124   else
1125     switch (value->kind)
1126       {
1127       case axs_rvalue:
1128         error ("Operand of `&' is an rvalue, which has no address.");
1129
1130       case axs_lvalue_register:
1131         error ("Operand of `&' is in a register, and has no address.");
1132
1133       case axs_lvalue_memory:
1134         value->kind = axs_rvalue;
1135         value->type = lookup_pointer_type (value->type);
1136         break;
1137       }
1138 }
1139
1140
1141 /* A lot of this stuff will have to change to support C++.  But we're
1142    not going to deal with that at the moment.  */
1143
1144 /* Find the field in the structure type TYPE named NAME, and return
1145    its index in TYPE's field array.  */
1146 static int
1147 find_field (struct type *type, char *name)
1148 {
1149   int i;
1150
1151   CHECK_TYPEDEF (type);
1152
1153   /* Make sure this isn't C++.  */
1154   if (TYPE_N_BASECLASSES (type) != 0)
1155     internal_error (__FILE__, __LINE__,
1156                     "find_field: derived classes supported");
1157
1158   for (i = 0; i < TYPE_NFIELDS (type); i++)
1159     {
1160       char *this_name = TYPE_FIELD_NAME (type, i);
1161
1162       if (this_name && strcmp (name, this_name) == 0)
1163         return i;
1164
1165       if (this_name[0] == '\0')
1166         internal_error (__FILE__, __LINE__,
1167                         "find_field: anonymous unions not supported");
1168     }
1169
1170   error ("Couldn't find member named `%s' in struct/union `%s'",
1171          name, TYPE_TAG_NAME (type));
1172
1173   return 0;
1174 }
1175
1176
1177 /* Generate code to push the value of a bitfield of a structure whose
1178    address is on the top of the stack.  START and END give the
1179    starting and one-past-ending *bit* numbers of the field within the
1180    structure.  */
1181 static void
1182 gen_bitfield_ref (struct agent_expr *ax, struct axs_value *value,
1183                   struct type *type, int start, int end)
1184 {
1185   /* Note that ops[i] fetches 8 << i bits.  */
1186   static enum agent_op ops[]
1187   =
1188   {aop_ref8, aop_ref16, aop_ref32, aop_ref64};
1189   static int num_ops = (sizeof (ops) / sizeof (ops[0]));
1190
1191   /* We don't want to touch any byte that the bitfield doesn't
1192      actually occupy; we shouldn't make any accesses we're not
1193      explicitly permitted to.  We rely here on the fact that the
1194      bytecode `ref' operators work on unaligned addresses.
1195
1196      It takes some fancy footwork to get the stack to work the way
1197      we'd like.  Say we're retrieving a bitfield that requires three
1198      fetches.  Initially, the stack just contains the address:
1199      addr
1200      For the first fetch, we duplicate the address
1201      addr addr
1202      then add the byte offset, do the fetch, and shift and mask as
1203      needed, yielding a fragment of the value, properly aligned for
1204      the final bitwise or:
1205      addr frag1
1206      then we swap, and repeat the process:
1207      frag1 addr                    --- address on top
1208      frag1 addr addr               --- duplicate it
1209      frag1 addr frag2              --- get second fragment
1210      frag1 frag2 addr              --- swap again
1211      frag1 frag2 frag3             --- get third fragment
1212      Notice that, since the third fragment is the last one, we don't
1213      bother duplicating the address this time.  Now we have all the
1214      fragments on the stack, and we can simply `or' them together,
1215      yielding the final value of the bitfield.  */
1216
1217   /* The first and one-after-last bits in the field, but rounded down
1218      and up to byte boundaries.  */
1219   int bound_start = (start / TARGET_CHAR_BIT) * TARGET_CHAR_BIT;
1220   int bound_end = (((end + TARGET_CHAR_BIT - 1)
1221                     / TARGET_CHAR_BIT)
1222                    * TARGET_CHAR_BIT);
1223
1224   /* current bit offset within the structure */
1225   int offset;
1226
1227   /* The index in ops of the opcode we're considering.  */
1228   int op;
1229
1230   /* The number of fragments we generated in the process.  Probably
1231      equal to the number of `one' bits in bytesize, but who cares?  */
1232   int fragment_count;
1233
1234   /* Dereference any typedefs. */
1235   type = check_typedef (type);
1236
1237   /* Can we fetch the number of bits requested at all?  */
1238   if ((end - start) > ((1 << num_ops) * 8))
1239     internal_error (__FILE__, __LINE__,
1240                     "gen_bitfield_ref: bitfield too wide");
1241
1242   /* Note that we know here that we only need to try each opcode once.
1243      That may not be true on machines with weird byte sizes.  */
1244   offset = bound_start;
1245   fragment_count = 0;
1246   for (op = num_ops - 1; op >= 0; op--)
1247     {
1248       /* number of bits that ops[op] would fetch */
1249       int op_size = 8 << op;
1250
1251       /* The stack at this point, from bottom to top, contains zero or
1252          more fragments, then the address.  */
1253
1254       /* Does this fetch fit within the bitfield?  */
1255       if (offset + op_size <= bound_end)
1256         {
1257           /* Is this the last fragment?  */
1258           int last_frag = (offset + op_size == bound_end);
1259
1260           if (!last_frag)
1261             ax_simple (ax, aop_dup);    /* keep a copy of the address */
1262
1263           /* Add the offset.  */
1264           gen_offset (ax, offset / TARGET_CHAR_BIT);
1265
1266           if (trace_kludge)
1267             {
1268               /* Record the area of memory we're about to fetch.  */
1269               ax_trace_quick (ax, op_size / TARGET_CHAR_BIT);
1270             }
1271
1272           /* Perform the fetch.  */
1273           ax_simple (ax, ops[op]);
1274
1275           /* Shift the bits we have to their proper position.
1276              gen_left_shift will generate right shifts when the operand
1277              is negative.
1278
1279              A big-endian field diagram to ponder:
1280              byte 0  byte 1  byte 2  byte 3  byte 4  byte 5  byte 6  byte 7
1281              +------++------++------++------++------++------++------++------+
1282              xxxxAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCxxxxxxxxxxx
1283              ^               ^               ^    ^
1284              bit number      16              32              48   53
1285              These are bit numbers as supplied by GDB.  Note that the
1286              bit numbers run from right to left once you've fetched the
1287              value!
1288
1289              A little-endian field diagram to ponder:
1290              byte 7  byte 6  byte 5  byte 4  byte 3  byte 2  byte 1  byte 0
1291              +------++------++------++------++------++------++------++------+
1292              xxxxxxxxxxxAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCxxxx
1293              ^               ^               ^           ^   ^
1294              bit number     48              32              16          4   0
1295
1296              In both cases, the most significant end is on the left
1297              (i.e. normal numeric writing order), which means that you
1298              don't go crazy thinking about `left' and `right' shifts.
1299
1300              We don't have to worry about masking yet:
1301              - If they contain garbage off the least significant end, then we
1302              must be looking at the low end of the field, and the right
1303              shift will wipe them out.
1304              - If they contain garbage off the most significant end, then we
1305              must be looking at the most significant end of the word, and
1306              the sign/zero extension will wipe them out.
1307              - If we're in the interior of the word, then there is no garbage
1308              on either end, because the ref operators zero-extend.  */
1309           if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
1310             gen_left_shift (ax, end - (offset + op_size));
1311           else
1312             gen_left_shift (ax, offset - start);
1313
1314           if (!last_frag)
1315             /* Bring the copy of the address up to the top.  */
1316             ax_simple (ax, aop_swap);
1317
1318           offset += op_size;
1319           fragment_count++;
1320         }
1321     }
1322
1323   /* Generate enough bitwise `or' operations to combine all the
1324      fragments we left on the stack.  */
1325   while (fragment_count-- > 1)
1326     ax_simple (ax, aop_bit_or);
1327
1328   /* Sign- or zero-extend the value as appropriate.  */
1329   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, end - start));
1330
1331   /* This is *not* an lvalue.  Ugh.  */
1332   value->kind = axs_rvalue;
1333   value->type = type;
1334 }
1335
1336
1337 /* Generate code to reference the member named FIELD of a structure or
1338    union.  The top of the stack, as described by VALUE, should have
1339    type (pointer to a)* struct/union.  OPERATOR_NAME is the name of
1340    the operator being compiled, and OPERAND_NAME is the kind of thing
1341    it operates on; we use them in error messages.  */
1342 static void
1343 gen_struct_ref (struct agent_expr *ax, struct axs_value *value, char *field,
1344                 char *operator_name, char *operand_name)
1345 {
1346   struct type *type;
1347   int i;
1348
1349   /* Follow pointers until we reach a non-pointer.  These aren't the C
1350      semantics, but they're what the normal GDB evaluator does, so we
1351      should at least be consistent.  */
1352   while (TYPE_CODE (value->type) == TYPE_CODE_PTR)
1353     {
1354       gen_usual_unary (ax, value);
1355       gen_deref (ax, value);
1356     }
1357   type = check_typedef (value->type);
1358
1359   /* This must yield a structure or a union.  */
1360   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
1361       && TYPE_CODE (type) != TYPE_CODE_UNION)
1362     error ("The left operand of `%s' is not a %s.",
1363            operator_name, operand_name);
1364
1365   /* And it must be in memory; we don't deal with structure rvalues,
1366      or structures living in registers.  */
1367   if (value->kind != axs_lvalue_memory)
1368     error ("Structure does not live in memory.");
1369
1370   i = find_field (type, field);
1371
1372   /* Is this a bitfield?  */
1373   if (TYPE_FIELD_PACKED (type, i))
1374     gen_bitfield_ref (ax, value, TYPE_FIELD_TYPE (type, i),
1375                       TYPE_FIELD_BITPOS (type, i),
1376                       (TYPE_FIELD_BITPOS (type, i)
1377                        + TYPE_FIELD_BITSIZE (type, i)));
1378   else
1379     {
1380       gen_offset (ax, TYPE_FIELD_BITPOS (type, i) / TARGET_CHAR_BIT);
1381       value->kind = axs_lvalue_memory;
1382       value->type = TYPE_FIELD_TYPE (type, i);
1383     }
1384 }
1385
1386
1387 /* Generate code for GDB's magical `repeat' operator.  
1388    LVALUE @ INT creates an array INT elements long, and whose elements
1389    have the same type as LVALUE, located in memory so that LVALUE is
1390    its first element.  For example, argv[0]@argc gives you the array
1391    of command-line arguments.
1392
1393    Unfortunately, because we have to know the types before we actually
1394    have a value for the expression, we can't implement this perfectly
1395    without changing the type system, having values that occupy two
1396    stack slots, doing weird things with sizeof, etc.  So we require
1397    the right operand to be a constant expression.  */
1398 static void
1399 gen_repeat (union exp_element **pc, struct agent_expr *ax,
1400             struct axs_value *value)
1401 {
1402   struct axs_value value1;
1403   /* We don't want to turn this into an rvalue, so no conversions
1404      here.  */
1405   gen_expr (pc, ax, &value1);
1406   if (value1.kind != axs_lvalue_memory)
1407     error ("Left operand of `@' must be an object in memory.");
1408
1409   /* Evaluate the length; it had better be a constant.  */
1410   {
1411     struct value *v = const_expr (pc);
1412     int length;
1413
1414     if (!v)
1415       error ("Right operand of `@' must be a constant, in agent expressions.");
1416     if (TYPE_CODE (v->type) != TYPE_CODE_INT)
1417       error ("Right operand of `@' must be an integer.");
1418     length = value_as_long (v);
1419     if (length <= 0)
1420       error ("Right operand of `@' must be positive.");
1421
1422     /* The top of the stack is already the address of the object, so
1423        all we need to do is frob the type of the lvalue.  */
1424     {
1425       /* FIXME-type-allocation: need a way to free this type when we are
1426          done with it.  */
1427       struct type *range
1428       = create_range_type (0, builtin_type_int, 0, length - 1);
1429       struct type *array = create_array_type (0, value1.type, range);
1430
1431       value->kind = axs_lvalue_memory;
1432       value->type = array;
1433     }
1434   }
1435 }
1436
1437
1438 /* Emit code for the `sizeof' operator.
1439    *PC should point at the start of the operand expression; we advance it
1440    to the first instruction after the operand.  */
1441 static void
1442 gen_sizeof (union exp_element **pc, struct agent_expr *ax,
1443             struct axs_value *value)
1444 {
1445   /* We don't care about the value of the operand expression; we only
1446      care about its type.  However, in the current arrangement, the
1447      only way to find an expression's type is to generate code for it.
1448      So we generate code for the operand, and then throw it away,
1449      replacing it with code that simply pushes its size.  */
1450   int start = ax->len;
1451   gen_expr (pc, ax, value);
1452
1453   /* Throw away the code we just generated.  */
1454   ax->len = start;
1455
1456   ax_const_l (ax, TYPE_LENGTH (value->type));
1457   value->kind = axs_rvalue;
1458   value->type = builtin_type_int;
1459 }
1460 \f
1461
1462 /* Generating bytecode from GDB expressions: general recursive thingy  */
1463
1464 /* A gen_expr function written by a Gen-X'er guy.
1465    Append code for the subexpression of EXPR starting at *POS_P to AX.  */
1466 static void
1467 gen_expr (union exp_element **pc, struct agent_expr *ax,
1468           struct axs_value *value)
1469 {
1470   /* Used to hold the descriptions of operand expressions.  */
1471   struct axs_value value1, value2;
1472   enum exp_opcode op = (*pc)[0].opcode;
1473
1474   /* If we're looking at a constant expression, just push its value.  */
1475   {
1476     struct value *v = maybe_const_expr (pc);
1477
1478     if (v)
1479       {
1480         ax_const_l (ax, value_as_long (v));
1481         value->kind = axs_rvalue;
1482         value->type = check_typedef (VALUE_TYPE (v));
1483         return;
1484       }
1485   }
1486
1487   /* Otherwise, go ahead and generate code for it.  */
1488   switch (op)
1489     {
1490       /* Binary arithmetic operators.  */
1491     case BINOP_ADD:
1492     case BINOP_SUB:
1493     case BINOP_MUL:
1494     case BINOP_DIV:
1495     case BINOP_REM:
1496     case BINOP_SUBSCRIPT:
1497     case BINOP_BITWISE_AND:
1498     case BINOP_BITWISE_IOR:
1499     case BINOP_BITWISE_XOR:
1500       (*pc)++;
1501       gen_expr (pc, ax, &value1);
1502       gen_usual_unary (ax, &value1);
1503       gen_expr (pc, ax, &value2);
1504       gen_usual_unary (ax, &value2);
1505       gen_usual_arithmetic (ax, &value1, &value2);
1506       switch (op)
1507         {
1508         case BINOP_ADD:
1509           gen_add (ax, value, &value1, &value2, "addition");
1510           break;
1511         case BINOP_SUB:
1512           gen_sub (ax, value, &value1, &value2);
1513           break;
1514         case BINOP_MUL:
1515           gen_binop (ax, value, &value1, &value2,
1516                      aop_mul, aop_mul, 1, "multiplication");
1517           break;
1518         case BINOP_DIV:
1519           gen_binop (ax, value, &value1, &value2,
1520                      aop_div_signed, aop_div_unsigned, 1, "division");
1521           break;
1522         case BINOP_REM:
1523           gen_binop (ax, value, &value1, &value2,
1524                      aop_rem_signed, aop_rem_unsigned, 1, "remainder");
1525           break;
1526         case BINOP_SUBSCRIPT:
1527           gen_add (ax, value, &value1, &value2, "array subscripting");
1528           if (TYPE_CODE (value->type) != TYPE_CODE_PTR)
1529             error ("Illegal combination of types in array subscripting.");
1530           gen_deref (ax, value);
1531           break;
1532         case BINOP_BITWISE_AND:
1533           gen_binop (ax, value, &value1, &value2,
1534                      aop_bit_and, aop_bit_and, 0, "bitwise and");
1535           break;
1536
1537         case BINOP_BITWISE_IOR:
1538           gen_binop (ax, value, &value1, &value2,
1539                      aop_bit_or, aop_bit_or, 0, "bitwise or");
1540           break;
1541
1542         case BINOP_BITWISE_XOR:
1543           gen_binop (ax, value, &value1, &value2,
1544                      aop_bit_xor, aop_bit_xor, 0, "bitwise exclusive-or");
1545           break;
1546
1547         default:
1548           /* We should only list operators in the outer case statement
1549              that we actually handle in the inner case statement.  */
1550           internal_error (__FILE__, __LINE__,
1551                           "gen_expr: op case sets don't match");
1552         }
1553       break;
1554
1555       /* Note that we need to be a little subtle about generating code
1556          for comma.  In C, we can do some optimizations here because
1557          we know the left operand is only being evaluated for effect.
1558          However, if the tracing kludge is in effect, then we always
1559          need to evaluate the left hand side fully, so that all the
1560          variables it mentions get traced.  */
1561     case BINOP_COMMA:
1562       (*pc)++;
1563       gen_expr (pc, ax, &value1);
1564       /* Don't just dispose of the left operand.  We might be tracing,
1565          in which case we want to emit code to trace it if it's an
1566          lvalue.  */
1567       gen_traced_pop (ax, &value1);
1568       gen_expr (pc, ax, value);
1569       /* It's the consumer's responsibility to trace the right operand.  */
1570       break;
1571
1572     case OP_LONG:               /* some integer constant */
1573       {
1574         struct type *type = (*pc)[1].type;
1575         LONGEST k = (*pc)[2].longconst;
1576         (*pc) += 4;
1577         gen_int_literal (ax, value, k, type);
1578       }
1579       break;
1580
1581     case OP_VAR_VALUE:
1582       gen_var_ref (ax, value, (*pc)[2].symbol);
1583       (*pc) += 4;
1584       break;
1585
1586     case OP_REGISTER:
1587       {
1588         int reg = (int) (*pc)[1].longconst;
1589         (*pc) += 3;
1590         value->kind = axs_lvalue_register;
1591         value->u.reg = reg;
1592         value->type = REGISTER_VIRTUAL_TYPE (reg);
1593       }
1594       break;
1595
1596     case OP_INTERNALVAR:
1597       error ("GDB agent expressions cannot use convenience variables.");
1598
1599       /* Weirdo operator: see comments for gen_repeat for details.  */
1600     case BINOP_REPEAT:
1601       /* Note that gen_repeat handles its own argument evaluation.  */
1602       (*pc)++;
1603       gen_repeat (pc, ax, value);
1604       break;
1605
1606     case UNOP_CAST:
1607       {
1608         struct type *type = (*pc)[1].type;
1609         (*pc) += 3;
1610         gen_expr (pc, ax, value);
1611         gen_cast (ax, value, type);
1612       }
1613       break;
1614
1615     case UNOP_MEMVAL:
1616       {
1617         struct type *type = check_typedef ((*pc)[1].type);
1618         (*pc) += 3;
1619         gen_expr (pc, ax, value);
1620         /* I'm not sure I understand UNOP_MEMVAL entirely.  I think
1621            it's just a hack for dealing with minsyms; you take some
1622            integer constant, pretend it's the address of an lvalue of
1623            the given type, and dereference it.  */
1624         if (value->kind != axs_rvalue)
1625           /* This would be weird.  */
1626           internal_error (__FILE__, __LINE__,
1627                           "gen_expr: OP_MEMVAL operand isn't an rvalue???");
1628         value->type = type;
1629         value->kind = axs_lvalue_memory;
1630       }
1631       break;
1632
1633     case UNOP_NEG:
1634       (*pc)++;
1635       /* -FOO is equivalent to 0 - FOO.  */
1636       gen_int_literal (ax, &value1, (LONGEST) 0, builtin_type_int);
1637       gen_usual_unary (ax, &value1);    /* shouldn't do much */
1638       gen_expr (pc, ax, &value2);
1639       gen_usual_unary (ax, &value2);
1640       gen_usual_arithmetic (ax, &value1, &value2);
1641       gen_sub (ax, value, &value1, &value2);
1642       break;
1643
1644     case UNOP_LOGICAL_NOT:
1645       (*pc)++;
1646       gen_expr (pc, ax, value);
1647       gen_logical_not (ax, value);
1648       break;
1649
1650     case UNOP_COMPLEMENT:
1651       (*pc)++;
1652       gen_expr (pc, ax, value);
1653       gen_complement (ax, value);
1654       break;
1655
1656     case UNOP_IND:
1657       (*pc)++;
1658       gen_expr (pc, ax, value);
1659       gen_usual_unary (ax, value);
1660       if (TYPE_CODE (value->type) != TYPE_CODE_PTR)
1661         error ("Argument of unary `*' is not a pointer.");
1662       gen_deref (ax, value);
1663       break;
1664
1665     case UNOP_ADDR:
1666       (*pc)++;
1667       gen_expr (pc, ax, value);
1668       gen_address_of (ax, value);
1669       break;
1670
1671     case UNOP_SIZEOF:
1672       (*pc)++;
1673       /* Notice that gen_sizeof handles its own operand, unlike most
1674          of the other unary operator functions.  This is because we
1675          have to throw away the code we generate.  */
1676       gen_sizeof (pc, ax, value);
1677       break;
1678
1679     case STRUCTOP_STRUCT:
1680     case STRUCTOP_PTR:
1681       {
1682         int length = (*pc)[1].longconst;
1683         char *name = &(*pc)[2].string;
1684
1685         (*pc) += 4 + BYTES_TO_EXP_ELEM (length + 1);
1686         gen_expr (pc, ax, value);
1687         if (op == STRUCTOP_STRUCT)
1688           gen_struct_ref (ax, value, name, ".", "structure or union");
1689         else if (op == STRUCTOP_PTR)
1690           gen_struct_ref (ax, value, name, "->",
1691                           "pointer to a structure or union");
1692         else
1693           /* If this `if' chain doesn't handle it, then the case list
1694              shouldn't mention it, and we shouldn't be here.  */
1695           internal_error (__FILE__, __LINE__,
1696                           "gen_expr: unhandled struct case");
1697       }
1698       break;
1699
1700     case OP_TYPE:
1701       error ("Attempt to use a type name as an expression.");
1702
1703     default:
1704       error ("Unsupported operator in expression.");
1705     }
1706 }
1707 \f
1708
1709
1710 /* Generating bytecode from GDB expressions: driver */
1711
1712 /* Given a GDB expression EXPR, produce a string of agent bytecode
1713    which computes its value.  Return the agent expression, and set
1714    *VALUE to describe its type, and whether it's an lvalue or rvalue.  */
1715 struct agent_expr *
1716 expr_to_agent (struct expression *expr, struct axs_value *value)
1717 {
1718   struct cleanup *old_chain = 0;
1719   struct agent_expr *ax = new_agent_expr (0);
1720   union exp_element *pc;
1721
1722   old_chain = make_cleanup_free_agent_expr (ax);
1723
1724   pc = expr->elts;
1725   trace_kludge = 0;
1726   gen_expr (&pc, ax, value);
1727
1728   /* We have successfully built the agent expr, so cancel the cleanup
1729      request.  If we add more cleanups that we always want done, this
1730      will have to get more complicated.  */
1731   discard_cleanups (old_chain);
1732   return ax;
1733 }
1734
1735
1736 #if 0                           /* not used */
1737 /* Given a GDB expression EXPR denoting an lvalue in memory, produce a
1738    string of agent bytecode which will leave its address and size on
1739    the top of stack.  Return the agent expression.
1740
1741    Not sure this function is useful at all.  */
1742 struct agent_expr *
1743 expr_to_address_and_size (struct expression *expr)
1744 {
1745   struct axs_value value;
1746   struct agent_expr *ax = expr_to_agent (expr, &value);
1747
1748   /* Complain if the result is not a memory lvalue.  */
1749   if (value.kind != axs_lvalue_memory)
1750     {
1751       free_agent_expr (ax);
1752       error ("Expression does not denote an object in memory.");
1753     }
1754
1755   /* Push the object's size on the stack.  */
1756   ax_const_l (ax, TYPE_LENGTH (value.type));
1757
1758   return ax;
1759 }
1760 #endif
1761
1762 /* Given a GDB expression EXPR, return bytecode to trace its value.
1763    The result will use the `trace' and `trace_quick' bytecodes to
1764    record the value of all memory touched by the expression.  The
1765    caller can then use the ax_reqs function to discover which
1766    registers it relies upon.  */
1767 struct agent_expr *
1768 gen_trace_for_expr (CORE_ADDR scope, struct expression *expr)
1769 {
1770   struct cleanup *old_chain = 0;
1771   struct agent_expr *ax = new_agent_expr (scope);
1772   union exp_element *pc;
1773   struct axs_value value;
1774
1775   old_chain = make_cleanup_free_agent_expr (ax);
1776
1777   pc = expr->elts;
1778   trace_kludge = 1;
1779   gen_expr (&pc, ax, &value);
1780
1781   /* Make sure we record the final object, and get rid of it.  */
1782   gen_traced_pop (ax, &value);
1783
1784   /* Oh, and terminate.  */
1785   ax_simple (ax, aop_end);
1786
1787   /* We have successfully built the agent expr, so cancel the cleanup
1788      request.  If we add more cleanups that we always want done, this
1789      will have to get more complicated.  */
1790   discard_cleanups (old_chain);
1791   return ax;
1792 }
1793 \f
1794
1795
1796 /* The "agent" command, for testing: compile and disassemble an expression.  */
1797
1798 static void
1799 print_axs_value (struct ui_file *f, struct axs_value *value)
1800 {
1801   switch (value->kind)
1802     {
1803     case axs_rvalue:
1804       fputs_filtered ("rvalue", f);
1805       break;
1806
1807     case axs_lvalue_memory:
1808       fputs_filtered ("memory lvalue", f);
1809       break;
1810
1811     case axs_lvalue_register:
1812       fprintf_filtered (f, "register %d lvalue", value->u.reg);
1813       break;
1814     }
1815
1816   fputs_filtered (" : ", f);
1817   type_print (value->type, "", f, -1);
1818 }
1819
1820
1821 static void
1822 agent_command (char *exp, int from_tty)
1823 {
1824   struct cleanup *old_chain = 0;
1825   struct expression *expr;
1826   struct agent_expr *agent;
1827   struct frame_info *fi = get_current_frame (); /* need current scope */
1828
1829   /* We don't deal with overlay debugging at the moment.  We need to
1830      think more carefully about this.  If you copy this code into
1831      another command, change the error message; the user shouldn't
1832      have to know anything about agent expressions.  */
1833   if (overlay_debugging)
1834     error ("GDB can't do agent expression translation with overlays.");
1835
1836   if (exp == 0)
1837     error_no_arg ("expression to translate");
1838
1839   expr = parse_expression (exp);
1840   old_chain = make_cleanup (free_current_contents, &expr);
1841   agent = gen_trace_for_expr (get_frame_pc (fi), expr);
1842   make_cleanup_free_agent_expr (agent);
1843   ax_print (gdb_stdout, agent);
1844
1845   /* It would be nice to call ax_reqs here to gather some general info
1846      about the expression, and then print out the result.  */
1847
1848   do_cleanups (old_chain);
1849   dont_repeat ();
1850 }
1851 \f
1852
1853 /* Initialization code.  */
1854
1855 void _initialize_ax_gdb (void);
1856 void
1857 _initialize_ax_gdb (void)
1858 {
1859   add_cmd ("agent", class_maintenance, agent_command,
1860            "Translate an expression into remote agent bytecode.",
1861            &maintenancelist);
1862 }