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