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