* config/tc-i960.c (md_convert_frag): Add ATTRIBUTE_UNUSED to args.
[external/binutils.git] / gas / config / tc-i960.c
1 /* tc-i960.c - All the i80960-specific stuff
2    Copyright 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000, 2001, 2002
4    Free Software Foundation, Inc.
5
6    This file is part of GAS.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21    02111-1307, USA.  */
22
23 /* See comment on md_parse_option for 80960-specific invocation options.  */
24
25 /* There are 4 different lengths of (potentially) symbol-based displacements
26    in the 80960 instruction set, each of which could require address fix-ups
27    and (in the case of external symbols) emission of relocation directives:
28
29    32-bit (MEMB)
30         This is a standard length for the base assembler and requires no
31         special action.
32
33    13-bit (COBR)
34         This is a non-standard length, but the base assembler has a
35         hook for bit field address fixups: the fixS structure can
36         point to a descriptor of the field, in which case our
37         md_number_to_field() routine gets called to process it.
38
39         I made the hook a little cleaner by having fix_new() (in the base
40         assembler) return a pointer to the fixS in question.  And I made it a
41         little simpler by storing the field size (in this case 13) instead of
42         of a pointer to another structure:  80960 displacements are ALWAYS
43         stored in the low-order bits of a 4-byte word.
44
45         Since the target of a COBR cannot be external, no relocation
46         directives for this size displacement have to be generated.
47         But the base assembler had to be modified to issue error
48         messages if the symbol did turn out to be external.
49
50    24-bit (CTRL)
51         Fixups are handled as for the 13-bit case (except that 24 is stored
52         in the fixS).
53
54         The relocation directive generated is the same as that for the 32-bit
55         displacement, except that it's PC-relative (the 32-bit displacement
56         never is).   The i80960 version of the linker needs a mod to
57         distinguish and handle the 24-bit case.
58
59    12-bit (MEMA)
60         MEMA formats are always promoted to MEMB (32-bit) if the displacement
61         is based on a symbol, because it could be relocated at link time.
62         The only time we use the 12-bit format is if an absolute value of
63         less than 4096 is specified, in which case we need neither a fixup nor
64         a relocation directive.  */
65
66 #include <stdio.h>
67
68 #include "as.h"
69
70 #include "safe-ctype.h"
71 #include "obstack.h"
72
73 #include "opcode/i960.h"
74
75 #if defined (OBJ_AOUT) || defined (OBJ_BOUT)
76
77 #define TC_S_IS_SYSPROC(s)      ((1<=S_GET_OTHER(s)) && (S_GET_OTHER(s)<=32))
78 #define TC_S_IS_BALNAME(s)      (S_GET_OTHER(s) == N_BALNAME)
79 #define TC_S_IS_CALLNAME(s)     (S_GET_OTHER(s) == N_CALLNAME)
80 #define TC_S_IS_BADPROC(s)      ((S_GET_OTHER(s) != 0) && !TC_S_IS_CALLNAME(s) && !TC_S_IS_BALNAME(s) && !TC_S_IS_SYSPROC(s))
81
82 #define TC_S_SET_SYSPROC(s, p)  (S_SET_OTHER((s), (p)+1))
83 #define TC_S_GET_SYSPROC(s)     (S_GET_OTHER(s)-1)
84
85 #define TC_S_FORCE_TO_BALNAME(s)        (S_SET_OTHER((s), N_BALNAME))
86 #define TC_S_FORCE_TO_CALLNAME(s)       (S_SET_OTHER((s), N_CALLNAME))
87 #define TC_S_FORCE_TO_SYSPROC(s)        {;}
88
89 #else /* ! OBJ_A/BOUT */
90 #ifdef OBJ_COFF
91
92 #define TC_S_IS_SYSPROC(s)      (S_GET_STORAGE_CLASS(s) == C_SCALL)
93 #define TC_S_IS_BALNAME(s)      (SF_GET_BALNAME(s))
94 #define TC_S_IS_CALLNAME(s)     (SF_GET_CALLNAME(s))
95 #define TC_S_IS_BADPROC(s)      (TC_S_IS_SYSPROC(s) && TC_S_GET_SYSPROC(s) < 0 && 31 < TC_S_GET_SYSPROC(s))
96
97 #define TC_S_SET_SYSPROC(s, p)  ((s)->sy_symbol.ost_auxent[1].x_sc.x_stindx = (p))
98 #define TC_S_GET_SYSPROC(s)     ((s)->sy_symbol.ost_auxent[1].x_sc.x_stindx)
99
100 #define TC_S_FORCE_TO_BALNAME(s)        (SF_SET_BALNAME(s))
101 #define TC_S_FORCE_TO_CALLNAME(s)       (SF_SET_CALLNAME(s))
102 #define TC_S_FORCE_TO_SYSPROC(s)        (S_SET_STORAGE_CLASS((s), C_SCALL))
103
104 #else /* ! OBJ_COFF */
105 #ifdef OBJ_ELF
106 #define TC_S_IS_SYSPROC(s)      0
107
108 #define TC_S_IS_BALNAME(s)      0
109 #define TC_S_IS_CALLNAME(s)     0
110 #define TC_S_IS_BADPROC(s)      0
111
112 #define TC_S_SET_SYSPROC(s, p)
113 #define TC_S_GET_SYSPROC(s) 0
114
115 #define TC_S_FORCE_TO_BALNAME(s)
116 #define TC_S_FORCE_TO_CALLNAME(s)
117 #define TC_S_FORCE_TO_SYSPROC(s)
118 #else
119  #error COFF, a.out, b.out, and ELF are the only supported formats.
120 #endif /* ! OBJ_ELF */
121 #endif /* ! OBJ_COFF */
122 #endif /* ! OBJ_A/BOUT */
123
124 extern char *input_line_pointer;
125
126 #if !defined (BFD_ASSEMBLER) && !defined (BFD)
127 #ifdef OBJ_COFF
128 const int md_reloc_size = sizeof (struct reloc);
129 #else /* OBJ_COFF */
130 const int md_reloc_size = sizeof (struct relocation_info);
131 #endif /* OBJ_COFF */
132 #endif
133
134 /* Local i80960 routines.  */
135 struct memS;
136 struct regop;
137
138 /* Emit branch-prediction instrumentation code */
139 static void brcnt_emit PARAMS ((void));
140 /* Return next branch local label */
141 static char *brlab_next PARAMS ((void));
142 /* Generate COBR instruction */
143 static void cobr_fmt PARAMS ((char *[], long, struct i960_opcode *));
144 /* Generate CTRL instruction */
145 static void ctrl_fmt PARAMS ((char *, long, int));
146 /* Emit (internally) binary */
147 static char *emit PARAMS ((long));
148 /* Break arguments out of comma-separated list */
149 static int get_args PARAMS ((char *, char *[]));
150 /* Handle COBR or CTRL displacement */
151 static void get_cdisp PARAMS ((char *, char *, long, int, int, int));
152 /* Find index specification string */
153 static char *get_ispec PARAMS ((char *));
154 /* Translate text to register number */
155 static int get_regnum PARAMS ((char *));
156 /* Lexical scan of instruction source */
157 static int i_scan PARAMS ((char *, char *[]));
158 /* Generate MEMA or MEMB instruction */
159 static void mem_fmt PARAMS ((char *[], struct i960_opcode *, int));
160 /* Convert MEMA instruction to MEMB format */
161 static void mema_to_memb PARAMS ((char *));
162 /* Parse an expression */
163 static void parse_expr PARAMS ((char *, expressionS *));
164 /* Parse and replace a 'ldconst' pseudo-op */
165 static int parse_ldconst PARAMS ((char *[]));
166 /* Parse a memory operand */
167 static void parse_memop PARAMS ((struct memS *, char *, int));
168 /* Parse machine-dependent pseudo-op */
169 static void parse_po PARAMS ((int));
170 /* Parse a register operand */
171 static void parse_regop PARAMS ((struct regop *, char *, char));
172 /* Generate a REG format instruction */
173 static void reg_fmt PARAMS ((char *[], struct i960_opcode *));
174 /* "De-optimize" cobr into compare/branch */
175 static void relax_cobr PARAMS ((fragS *));
176 /* Process '.leafproc' pseudo-op */
177 static void s_leafproc PARAMS ((int, char *[]));
178 /* Process '.sysproc' pseudo-op */
179 static void s_sysproc PARAMS ((int, char *[]));
180 /* Will a 'shlo' substiture for a 'ldconst'? */
181 static int shift_ok PARAMS ((int));
182 /* Give syntax error */
183 static void syntax PARAMS ((void));
184 /* Target chip supports spec-func register? */
185 static int targ_has_sfr PARAMS ((int));
186 /* Target chip supports instruction set? */
187 static int targ_has_iclass PARAMS ((int));
188
189 /* See md_parse_option() for meanings of these options */
190 static char norelax;            /* True if -norelax switch seen */
191 static char instrument_branches;        /* True if -b switch seen */
192
193 /* Characters that always start a comment.
194    If the pre-processor is disabled, these aren't very useful.
195  */
196 const char comment_chars[] = "#";
197
198 /* Characters that only start a comment at the beginning of
199    a line.  If the line seems to have the form '# 123 filename'
200    .line and .file directives will appear in the pre-processed output.
201
202    Note that input_file.c hand checks for '#' at the beginning of the
203    first line of the input file.  This is because the compiler outputs
204    #NO_APP at the beginning of its output.
205  */
206
207 /* Also note that comments started like this one will always work.  */
208
209 const char line_comment_chars[] = "";
210
211 const char line_separator_chars[] = ";";
212
213 /* Chars that can be used to separate mant from exp in floating point nums */
214 const char EXP_CHARS[] = "eE";
215
216 /* Chars that mean this number is a floating point constant,
217    as in 0f12.456 or 0d1.2345e12
218  */
219 const char FLT_CHARS[] = "fFdDtT";
220
221 /* Table used by base assembler to relax addresses based on varying length
222    instructions.  The fields are:
223      1) most positive reach of this state,
224      2) most negative reach of this state,
225      3) how many bytes this mode will add to the size of the current frag
226      4) which index into the table to try if we can't fit into this one.
227
228    For i80960, the only application is the (de-)optimization of cobr
229    instructions into separate compare and branch instructions when a 13-bit
230    displacement won't hack it.
231  */
232 const relax_typeS md_relax_table[] =
233 {
234   {0, 0, 0, 0},                 /* State 0 => no more relaxation possible */
235   {4088, -4096, 0, 2},          /* State 1: conditional branch (cobr) */
236   {0x800000 - 8, -0x800000, 4, 0},      /* State 2: compare (reg) & branch (ctrl) */
237 };
238
239 static void s_endian PARAMS ((int));
240
241 /* These are the machine dependent pseudo-ops.
242
243    This table describes all the machine specific pseudo-ops the assembler
244    has to support.  The fields are:
245         pseudo-op name without dot
246         function to call to execute this pseudo-op
247         integer arg to pass to the function
248  */
249 #define S_LEAFPROC      1
250 #define S_SYSPROC       2
251
252 const pseudo_typeS md_pseudo_table[] =
253 {
254   {"bss", s_lcomm, 1},
255   {"endian", s_endian, 0},
256   {"extended", float_cons, 't'},
257   {"leafproc", parse_po, S_LEAFPROC},
258   {"sysproc", parse_po, S_SYSPROC},
259
260   {"word", cons, 4},
261   {"quad", cons, 16},
262
263   {0, 0, 0}
264 };
265 \f
266 /* Macros to extract info from an 'expressionS' structure 'e' */
267 #define adds(e) e.X_add_symbol
268 #define offs(e) e.X_add_number
269
270 /* Branch-prediction bits for CTRL/COBR format opcodes */
271 #define BP_MASK         0x00000002      /* Mask for branch-prediction bit */
272 #define BP_TAKEN        0x00000000      /* Value to OR in to predict branch */
273 #define BP_NOT_TAKEN    0x00000002      /* Value to OR in to predict no branch */
274
275 /* Some instruction opcodes that we need explicitly */
276 #define BE      0x12000000
277 #define BG      0x11000000
278 #define BGE     0x13000000
279 #define BL      0x14000000
280 #define BLE     0x16000000
281 #define BNE     0x15000000
282 #define BNO     0x10000000
283 #define BO      0x17000000
284 #define CHKBIT  0x5a002700
285 #define CMPI    0x5a002080
286 #define CMPO    0x5a002000
287
288 #define B       0x08000000
289 #define BAL     0x0b000000
290 #define CALL    0x09000000
291 #define CALLS   0x66003800
292 #define RET     0x0a000000
293
294 /* These masks are used to build up a set of MEMB mode bits.  */
295 #define A_BIT           0x0400
296 #define I_BIT           0x0800
297 #define MEMB_BIT        0x1000
298 #define D_BIT           0x2000
299
300 /* Mask for the only mode bit in a MEMA instruction (if set, abase reg is
301    used).  */
302 #define MEMA_ABASE      0x2000
303
304 /* Info from which a MEMA or MEMB format instruction can be generated */
305 typedef struct memS
306   {
307     /* (First) 32 bits of instruction */
308     long opcode;
309     /* 0-(none), 12- or, 32-bit displacement needed */
310     int disp;
311     /* The expression in the source instruction from which the
312        displacement should be determined.  */
313     char *e;
314   }
315 memS;
316
317 /* The two pieces of info we need to generate a register operand */
318 struct regop
319   {
320     int mode;                   /* 0 =>local/global/spec reg; 1=> literal or fp reg */
321     int special;                /* 0 =>not a sfr;  1=> is a sfr (not valid w/mode=0) */
322     int n;                      /* Register number or literal value */
323   };
324
325 /* Number and assembler mnemonic for all registers that can appear in
326    operands.  */
327 static const struct
328   {
329     char *reg_name;
330     int reg_num;
331   }
332 regnames[] =
333 {
334   { "pfp", 0 },
335   { "sp", 1 },
336   { "rip", 2 },
337   { "r3", 3 },
338   { "r4", 4 },
339   { "r5", 5 },
340   { "r6", 6 },
341   { "r7", 7 },
342   { "r8", 8 },
343   { "r9", 9 },
344   { "r10", 10 },
345   { "r11", 11 },
346   { "r12", 12 },
347   { "r13", 13 },
348   { "r14", 14 },
349   { "r15", 15 },
350   { "g0", 16 },
351   { "g1", 17 },
352   { "g2", 18 },
353   { "g3", 19 },
354   { "g4", 20 },
355   { "g5", 21 },
356   { "g6", 22 },
357   { "g7", 23 },
358   { "g8", 24 },
359   { "g9", 25 },
360   { "g10", 26 },
361   { "g11", 27 },
362   { "g12", 28 },
363   { "g13", 29 },
364   { "g14", 30 },
365   { "fp", 31 },
366
367   /* Numbers for special-function registers are for assembler internal
368      use only: they are scaled back to range [0-31] for binary output.  */
369 #define SF0     32
370
371   { "sf0", 32 },
372   { "sf1", 33 },
373   { "sf2", 34 },
374   { "sf3", 35 },
375   { "sf4", 36 },
376   { "sf5", 37 },
377   { "sf6", 38 },
378   { "sf7", 39 },
379   { "sf8", 40 },
380   { "sf9", 41 },
381   { "sf10", 42 },
382   { "sf11", 43 },
383   { "sf12", 44 },
384   { "sf13", 45 },
385   { "sf14", 46 },
386   { "sf15", 47 },
387   { "sf16", 48 },
388   { "sf17", 49 },
389   { "sf18", 50 },
390   { "sf19", 51 },
391   { "sf20", 52 },
392   { "sf21", 53 },
393   { "sf22", 54 },
394   { "sf23", 55 },
395   { "sf24", 56 },
396   { "sf25", 57 },
397   { "sf26", 58 },
398   { "sf27", 59 },
399   { "sf28", 60 },
400   { "sf29", 61 },
401   { "sf30", 62 },
402   { "sf31", 63 },
403
404   /* Numbers for floating point registers are for assembler internal
405      use only: they are scaled back to [0-3] for binary output.  */
406 #define FP0     64
407
408   { "fp0", 64 },
409   { "fp1", 65 },
410   { "fp2", 66 },
411   { "fp3", 67 },
412
413   { NULL, 0 },                          /* END OF LIST */
414 };
415
416 #define IS_RG_REG(n)    ((0 <= (n)) && ((n) < SF0))
417 #define IS_SF_REG(n)    ((SF0 <= (n)) && ((n) < FP0))
418 #define IS_FP_REG(n)    ((n) >= FP0)
419
420 /* Number and assembler mnemonic for all registers that can appear as
421    'abase' (indirect addressing) registers.  */
422 static const struct
423   {
424     char *areg_name;
425     int areg_num;
426   }
427 aregs[] =
428 {
429   { "(pfp)", 0 },
430   { "(sp)", 1 },
431   { "(rip)", 2 },
432   { "(r3)", 3 },
433   { "(r4)", 4 },
434   { "(r5)", 5 },
435   { "(r6)", 6 },
436   { "(r7)", 7 },
437   { "(r8)", 8 },
438   { "(r9)", 9 },
439   { "(r10)", 10 },
440   { "(r11)", 11 },
441   { "(r12)", 12 },
442   { "(r13)", 13 },
443   { "(r14)", 14 },
444   { "(r15)", 15 },
445   { "(g0)", 16 },
446   { "(g1)", 17 },
447   { "(g2)", 18 },
448   { "(g3)", 19 },
449   { "(g4)", 20 },
450   { "(g5)", 21 },
451   { "(g6)", 22 },
452   { "(g7)", 23 },
453   { "(g8)", 24 },
454   { "(g9)", 25 },
455   { "(g10)", 26 },
456   { "(g11)", 27 },
457   { "(g12)", 28 },
458   { "(g13)", 29 },
459   { "(g14)", 30 },
460   { "(fp)", 31 },
461
462 #define IPREL   32
463   /* For assembler internal use only: this number never appears in binary
464      output.  */
465   { "(ip)", IPREL },
466
467   { NULL, 0 },                          /* END OF LIST */
468 };
469
470 /* Hash tables */
471 static struct hash_control *op_hash;    /* Opcode mnemonics */
472 static struct hash_control *reg_hash;   /* Register name hash table */
473 static struct hash_control *areg_hash;  /* Abase register hash table */
474
475 /* Architecture for which we are assembling */
476 #define ARCH_ANY        0       /* Default: no architecture checking done */
477 #define ARCH_KA         1
478 #define ARCH_KB         2
479 #define ARCH_MC         3
480 #define ARCH_CA         4
481 #define ARCH_JX         5
482 #define ARCH_HX         6
483 int architecture = ARCH_ANY;    /* Architecture requested on invocation line */
484 int iclasses_seen;              /* OR of instruction classes (I_* constants)
485                                  *    for which we've actually assembled
486                                  *      instructions.
487                                  */
488
489 /* BRANCH-PREDICTION INSTRUMENTATION
490
491         The following supports generation of branch-prediction instrumentation
492         (turned on by -b switch).  The instrumentation collects counts
493         of branches taken/not-taken for later input to a utility that will
494         set the branch prediction bits of the instructions in accordance with
495         the behavior observed.  (Note that the KX series does not have
496         brach-prediction.)
497
498         The instrumentation consists of:
499
500         (1) before and after each conditional branch, a call to an external
501             routine that increments and steps over an inline counter.  The
502             counter itself, initialized to 0, immediately follows the call
503             instruction.  For each branch, the counter following the branch
504             is the number of times the branch was not taken, and the difference
505             between the counters is the number of times it was taken.  An
506             example of an instrumented conditional branch:
507
508                                 call    BR_CNT_FUNC
509                                 .word   0
510                 LBRANCH23:      be      label
511                                 call    BR_CNT_FUNC
512                                 .word   0
513
514         (2) a table of pointers to the instrumented branches, so that an
515             external postprocessing routine can locate all of the counters.
516             the table begins with a 2-word header: a pointer to the next in
517             a linked list of such tables (initialized to 0);  and a count
518             of the number of entries in the table (exclusive of the header.
519
520             Note that input source code is expected to already contain calls
521             an external routine that will link the branch local table into a
522             list of such tables.
523  */
524
525 /* Number of branches instrumented so far.  Also used to generate
526    unique local labels for each instrumented branch.  */
527 static int br_cnt;
528
529 #define BR_LABEL_BASE   "LBRANCH"
530 /* Basename of local labels on instrumented branches, to avoid
531    conflict with compiler- generated local labels.  */
532
533 #define BR_CNT_FUNC     "__inc_branch"
534 /* Name of the external routine that will increment (and step over) an
535    inline counter.  */
536
537 #define BR_TAB_NAME     "__BRANCH_TABLE__"
538 /* Name of the table of pointers to branches.  A local (i.e.,
539    non-external) symbol.  */
540 \f
541 /*****************************************************************************
542    md_begin:  One-time initialization.
543
544         Set up hash tables.
545
546   *************************************************************************** */
547 void
548 md_begin ()
549 {
550   int i;                        /* Loop counter */
551   const struct i960_opcode *oP; /* Pointer into opcode table */
552   const char *retval;           /* Value returned by hash functions */
553
554   op_hash = hash_new ();
555   reg_hash = hash_new ();
556   areg_hash = hash_new ();
557
558   /* For some reason, the base assembler uses an empty string for "no
559      error message", instead of a NULL pointer.  */
560   retval = 0;
561
562   for (oP = i960_opcodes; oP->name && !retval; oP++)
563     retval = hash_insert (op_hash, oP->name, (PTR) oP);
564
565   for (i = 0; regnames[i].reg_name && !retval; i++)
566     retval = hash_insert (reg_hash, regnames[i].reg_name,
567                           (char *) &regnames[i].reg_num);
568
569   for (i = 0; aregs[i].areg_name && !retval; i++)
570     retval = hash_insert (areg_hash, aregs[i].areg_name,
571                           (char *) &aregs[i].areg_num);
572
573   if (retval)
574     as_fatal (_("Hashing returned \"%s\"."), retval);
575 }
576
577 /*****************************************************************************
578    md_assemble:  Assemble an instruction
579
580    Assumptions about the passed-in text:
581         - all comments, labels removed
582         - text is an instruction
583         - all white space compressed to single blanks
584         - all character constants have been replaced with decimal
585
586   *************************************************************************** */
587 void
588 md_assemble (textP)
589      char *textP;               /* Source text of instruction */
590 {
591   /* Parsed instruction text, containing NO whitespace: arg[0]->opcode
592      mnemonic arg[1-3]->operands, with char constants replaced by
593      decimal numbers.  */
594   char *args[4];
595
596   int n_ops;                    /* Number of instruction operands */
597   /* Pointer to instruction description */
598   struct i960_opcode *oP;
599   /* TRUE iff opcode mnemonic included branch-prediction suffix (".f"
600      or ".t").  */
601   int branch_predict;
602   /* Setting of branch-prediction bit(s) to be OR'd into instruction
603      opcode of CTRL/COBR format instructions.  */
604   long bp_bits;
605
606   int n;                        /* Offset of last character in opcode mnemonic */
607
608   const char *bp_error_msg = _("branch prediction invalid on this opcode");
609
610   /* Parse instruction into opcode and operands */
611   memset (args, '\0', sizeof (args));
612   n_ops = i_scan (textP, args);
613   if (n_ops == -1)
614     {
615       return;                   /* Error message already issued */
616     }
617
618   /* Do "macro substitution" (sort of) on 'ldconst' pseudo-instruction */
619   if (!strcmp (args[0], "ldconst"))
620     {
621       n_ops = parse_ldconst (args);
622       if (n_ops == -1)
623         {
624           return;
625         }
626     }
627
628   /* Check for branch-prediction suffix on opcode mnemonic, strip it off */
629   n = strlen (args[0]) - 1;
630   branch_predict = 0;
631   bp_bits = 0;
632   if (args[0][n - 1] == '.' && (args[0][n] == 't' || args[0][n] == 'f'))
633     {
634       /* We could check here to see if the target architecture
635          supports branch prediction, but why bother?  The bit will
636          just be ignored by processors that don't use it.  */
637       branch_predict = 1;
638       bp_bits = (args[0][n] == 't') ? BP_TAKEN : BP_NOT_TAKEN;
639       args[0][n - 1] = '\0';    /* Strip suffix from opcode mnemonic */
640     }
641
642   /* Look up opcode mnemonic in table and check number of operands.
643      Check that opcode is legal for the target architecture.  If all
644      looks good, assemble instruction.  */
645   oP = (struct i960_opcode *) hash_find (op_hash, args[0]);
646   if (!oP || !targ_has_iclass (oP->iclass))
647     {
648       as_bad (_("invalid opcode, \"%s\"."), args[0]);
649
650     }
651   else if (n_ops != oP->num_ops)
652     {
653       as_bad (_("improper number of operands.  expecting %d, got %d"),
654               oP->num_ops, n_ops);
655     }
656   else
657     {
658       switch (oP->format)
659         {
660         case FBRA:
661         case CTRL:
662           ctrl_fmt (args[1], oP->opcode | bp_bits, oP->num_ops);
663           if (oP->format == FBRA)
664             {
665               /* Now generate a 'bno' to same arg */
666               ctrl_fmt (args[1], BNO | bp_bits, 1);
667             }
668           break;
669         case COBR:
670         case COJ:
671           cobr_fmt (args, oP->opcode | bp_bits, oP);
672           break;
673         case REG:
674           if (branch_predict)
675             {
676               as_warn (bp_error_msg);
677             }
678           reg_fmt (args, oP);
679           break;
680         case MEM1:
681           if (args[0][0] == 'c' && args[0][1] == 'a')
682             {
683               if (branch_predict)
684                 {
685                   as_warn (bp_error_msg);
686                 }
687               mem_fmt (args, oP, 1);
688               break;
689             }
690         case MEM2:
691         case MEM4:
692         case MEM8:
693         case MEM12:
694         case MEM16:
695           if (branch_predict)
696             {
697               as_warn (bp_error_msg);
698             }
699           mem_fmt (args, oP, 0);
700           break;
701         case CALLJ:
702           if (branch_predict)
703             {
704               as_warn (bp_error_msg);
705             }
706           /* Output opcode & set up "fixup" (relocation); flag
707              relocation as 'callj' type.  */
708           know (oP->num_ops == 1);
709           get_cdisp (args[1], "CTRL", oP->opcode, 24, 0, 1);
710           break;
711         default:
712           BAD_CASE (oP->format);
713           break;
714         }
715     }
716 }                               /* md_assemble() */
717
718 /*****************************************************************************
719    md_number_to_chars:  convert a number to target byte order
720
721   *************************************************************************** */
722 void
723 md_number_to_chars (buf, value, n)
724      char *buf;
725      valueT value;
726      int n;
727 {
728   number_to_chars_littleendian (buf, value, n);
729 }
730
731 /*****************************************************************************
732    md_chars_to_number:  convert from target byte order to host byte order.
733
734   *************************************************************************** */
735 static int md_chars_to_number PARAMS ((unsigned char *, int));
736
737 static int
738 md_chars_to_number (val, n)
739      unsigned char *val;        /* Value in target byte order */
740      int n;                     /* Number of bytes in the input */
741 {
742   int retval;
743
744   for (retval = 0; n--;)
745     {
746       retval <<= 8;
747       retval |= val[n];
748     }
749   return retval;
750 }
751
752 #define MAX_LITTLENUMS  6
753 #define LNUM_SIZE       sizeof (LITTLENUM_TYPE)
754
755 /*****************************************************************************
756    md_atof:     convert ascii to floating point
757
758    Turn a string at input_line_pointer into a floating point constant of type
759    'type', and store the appropriate bytes at *litP.  The number of LITTLENUMS
760    emitted is returned at 'sizeP'.  An error message is returned, or a pointer
761    to an empty message if OK.
762
763    Note we call the i386 floating point routine, rather than complicating
764    things with more files or symbolic links.
765
766   *************************************************************************** */
767 char *
768 md_atof (type, litP, sizeP)
769      int type;
770      char *litP;
771      int *sizeP;
772 {
773   LITTLENUM_TYPE words[MAX_LITTLENUMS];
774   LITTLENUM_TYPE *wordP;
775   int prec;
776   char *t;
777
778   switch (type)
779     {
780     case 'f':
781     case 'F':
782       prec = 2;
783       break;
784
785     case 'd':
786     case 'D':
787       prec = 4;
788       break;
789
790     case 't':
791     case 'T':
792       prec = 5;
793       type = 'x';               /* That's what atof_ieee() understands */
794       break;
795
796     default:
797       *sizeP = 0;
798       return _("Bad call to md_atof()");
799     }
800
801   t = atof_ieee (input_line_pointer, type, words);
802   if (t)
803     {
804       input_line_pointer = t;
805     }
806
807   *sizeP = prec * LNUM_SIZE;
808
809   /* Output the LITTLENUMs in REVERSE order in accord with i80960
810      word-order.  (Dunno why atof_ieee doesn't do it in the right
811      order in the first place -- probably because it's a hack of
812      atof_m68k.)  */
813
814   for (wordP = words + prec - 1; prec--;)
815     {
816       md_number_to_chars (litP, (long) (*wordP--), LNUM_SIZE);
817       litP += sizeof (LITTLENUM_TYPE);
818     }
819
820   return 0;
821 }
822
823 /*****************************************************************************
824    md_number_to_imm
825
826   *************************************************************************** */
827 static void md_number_to_imm PARAMS ((char *, long, int));
828
829 static void
830 md_number_to_imm (buf, val, n)
831      char *buf;
832      long val;
833      int n;
834 {
835   md_number_to_chars (buf, val, n);
836 }
837
838 /*****************************************************************************
839    md_number_to_field:
840
841         Stick a value (an address fixup) into a bit field of
842         previously-generated instruction.
843
844   *************************************************************************** */
845 static void md_number_to_field PARAMS ((char *, long, bit_fixS *));
846
847 static void
848 md_number_to_field (instrP, val, bfixP)
849      char *instrP;              /* Pointer to instruction to be fixed */
850      long val;                  /* Address fixup value */
851      bit_fixS *bfixP;           /* Description of bit field to be fixed up */
852 {
853   int numbits;                  /* Length of bit field to be fixed */
854   long instr;                   /* 32-bit instruction to be fixed-up */
855   long sign;                    /* 0 or -1, according to sign bit of 'val' */
856
857   /* Convert instruction back to host byte order.  */
858   instr = md_chars_to_number (instrP, 4);
859
860   /* Surprise! -- we stored the number of bits to be modified rather
861      than a pointer to a structure.  */
862   numbits = (int) bfixP;
863   if (numbits == 1)
864     {
865       /* This is a no-op, stuck here by reloc_callj() */
866       return;
867     }
868
869   know ((numbits == 13) || (numbits == 24));
870
871   /* Propagate sign bit of 'val' for the given number of bits.  Result
872      should be all 0 or all 1.  */
873   sign = val >> ((int) numbits - 1);
874   if (((val < 0) && (sign != -1))
875       || ((val > 0) && (sign != 0)))
876     {
877       as_bad (_("Fixup of %ld too large for field width of %d"),
878               val, numbits);
879     }
880   else
881     {
882       /* Put bit field into instruction and write back in target
883          * byte order.
884        */
885       val &= ~(-1 << (int) numbits);    /* Clear unused sign bits */
886       instr |= val;
887       md_number_to_chars (instrP, instr, 4);
888     }
889 }                               /* md_number_to_field() */
890 \f
891
892 /*****************************************************************************
893    md_parse_option
894         Invocation line includes a switch not recognized by the base assembler.
895         See if it's a processor-specific option.  For the 960, these are:
896
897         -norelax:
898                 Conditional branch instructions that require displacements
899                 greater than 13 bits (or that have external targets) should
900                 generate errors.  The default is to replace each such
901                 instruction with the corresponding compare (or chkbit) and
902                 branch instructions.  Note that the Intel "j" cobr directives
903                 are ALWAYS "de-optimized" in this way when necessary,
904                 regardless of the setting of this option.
905
906         -b:
907                 Add code to collect information about branches taken, for
908                 later optimization of branch prediction bits by a separate
909                 tool.  COBR and CNTL format instructions have branch
910                 prediction bits (in the CX architecture);  if "BR" represents
911                 an instruction in one of these classes, the following rep-
912                 resents the code generated by the assembler:
913
914                         call    <increment routine>
915                         .word   0       # pre-counter
916                 Label:  BR
917                         call    <increment routine>
918                         .word   0       # post-counter
919
920                 A table of all such "Labels" is also generated.
921
922         -AKA, -AKB, -AKC, -ASA, -ASB, -AMC, -ACA:
923                 Select the 80960 architecture.  Instructions or features not
924                 supported by the selected architecture cause fatal errors.
925                 The default is to generate code for any instruction or feature
926                 that is supported by SOME version of the 960 (even if this
927                 means mixing architectures!).
928
929   ****************************************************************************/
930
931 const char *md_shortopts = "A:b";
932 struct option md_longopts[] =
933 {
934 #define OPTION_LINKRELAX (OPTION_MD_BASE)
935   {"linkrelax", no_argument, NULL, OPTION_LINKRELAX},
936   {"link-relax", no_argument, NULL, OPTION_LINKRELAX},
937 #define OPTION_NORELAX (OPTION_MD_BASE + 1)
938   {"norelax", no_argument, NULL, OPTION_NORELAX},
939   {"no-relax", no_argument, NULL, OPTION_NORELAX},
940   {NULL, no_argument, NULL, 0}
941 };
942 size_t md_longopts_size = sizeof (md_longopts);
943
944 struct tabentry
945   {
946     char *flag;
947     int arch;
948   };
949 static const struct tabentry arch_tab[] =
950 {
951   {"KA", ARCH_KA},
952   {"KB", ARCH_KB},
953   {"SA", ARCH_KA},              /* Synonym for KA */
954   {"SB", ARCH_KB},              /* Synonym for KB */
955   {"KC", ARCH_MC},              /* Synonym for MC */
956   {"MC", ARCH_MC},
957   {"CA", ARCH_CA},
958   {"JX", ARCH_JX},
959   {"HX", ARCH_HX},
960   {NULL, 0}
961 };
962
963 int
964 md_parse_option (c, arg)
965      int c;
966      char *arg;
967 {
968   switch (c)
969     {
970     case OPTION_LINKRELAX:
971       linkrelax = 1;
972       flag_keep_locals = 1;
973       break;
974
975     case OPTION_NORELAX:
976       norelax = 1;
977       break;
978
979     case 'b':
980       instrument_branches = 1;
981       break;
982
983     case 'A':
984       {
985         const struct tabentry *tp;
986         char *p = arg;
987
988         for (tp = arch_tab; tp->flag != NULL; tp++)
989           if (!strcmp (p, tp->flag))
990             break;
991
992         if (tp->flag == NULL)
993           {
994             as_bad (_("invalid architecture %s"), p);
995             return 0;
996           }
997         else
998           architecture = tp->arch;
999       }
1000       break;
1001
1002     default:
1003       return 0;
1004     }
1005
1006   return 1;
1007 }
1008
1009 void
1010 md_show_usage (stream)
1011      FILE *stream;
1012 {
1013   int i;
1014   fprintf (stream, _("I960 options:\n"));
1015   for (i = 0; arch_tab[i].flag; i++)
1016     fprintf (stream, "%s-A%s", i ? " | " : "", arch_tab[i].flag);
1017   fprintf (stream, _("\n\
1018                         specify variant of 960 architecture\n\
1019 -b                      add code to collect statistics about branches taken\n\
1020 -link-relax             preserve individual alignment directives so linker\n\
1021                         can do relaxing (b.out format only)\n\
1022 -no-relax               don't alter compare-and-branch instructions for\n\
1023                         long displacements\n"));
1024 }
1025 \f
1026
1027 /*****************************************************************************
1028    md_convert_frag:
1029         Called by base assembler after address relaxation is finished:  modify
1030         variable fragments according to how much relaxation was done.
1031
1032         If the fragment substate is still 1, a 13-bit displacement was enough
1033         to reach the symbol in question.  Set up an address fixup, but otherwise
1034         leave the cobr instruction alone.
1035
1036         If the fragment substate is 2, a 13-bit displacement was not enough.
1037         Replace the cobr with a two instructions (a compare and a branch).
1038
1039   *************************************************************************** */
1040 #ifndef BFD_ASSEMBLER
1041 void
1042 md_convert_frag (headers, seg, fragP)
1043      object_headers *headers ATTRIBUTE_UNUSED;
1044      segT seg ATTRIBUTE_UNUSED;
1045      fragS *fragP;
1046 #else
1047 void
1048 md_convert_frag (abfd, sec, fragP)
1049      bfd *abfd ATTRIBUTE_UNUSED;
1050      segT sec ATTRIBUTE_UNUSED;
1051      fragS *fragP;
1052 #endif
1053 {
1054   fixS *fixP;                   /* Structure describing needed address fix */
1055
1056   switch (fragP->fr_subtype)
1057     {
1058     case 1:
1059       /* LEAVE SINGLE COBR INSTRUCTION */
1060       fixP = fix_new (fragP,
1061                       fragP->fr_opcode - fragP->fr_literal,
1062                       4,
1063                       fragP->fr_symbol,
1064                       fragP->fr_offset,
1065                       1,
1066                       NO_RELOC);
1067
1068       fixP->fx_bit_fixP = (bit_fixS *) 13;      /* size of bit field */
1069       break;
1070     case 2:
1071       /* REPLACE COBR WITH COMPARE/BRANCH INSTRUCTIONS */
1072       relax_cobr (fragP);
1073       break;
1074     default:
1075       BAD_CASE (fragP->fr_subtype);
1076       break;
1077     }
1078 }
1079
1080 /*****************************************************************************
1081    md_estimate_size_before_relax:  How much does it look like *fragP will grow?
1082
1083         Called by base assembler just before address relaxation.
1084         Return the amount by which the fragment will grow.
1085
1086         Any symbol that is now undefined will not become defined; cobr's
1087         based on undefined symbols will have to be replaced with a compare
1088         instruction and a branch instruction, and the code fragment will grow
1089         by 4 bytes.
1090
1091   *************************************************************************** */
1092 int
1093 md_estimate_size_before_relax (fragP, segment_type)
1094      register fragS *fragP;
1095      register segT segment_type;
1096 {
1097   /* If symbol is undefined in this segment, go to "relaxed" state
1098      (compare and branch instructions instead of cobr) right now.  */
1099   if (S_GET_SEGMENT (fragP->fr_symbol) != segment_type)
1100     {
1101       relax_cobr (fragP);
1102       return 4;
1103     }
1104
1105   return md_relax_table[fragP->fr_subtype].rlx_length;
1106 }                               /* md_estimate_size_before_relax() */
1107
1108 #if defined(OBJ_AOUT) | defined(OBJ_BOUT)
1109
1110 /*****************************************************************************
1111    md_ri_to_chars:
1112         This routine exists in order to overcome machine byte-order problems
1113         when dealing with bit-field entries in the relocation_info struct.
1114
1115         But relocation info will be used on the host machine only (only
1116         executable code is actually downloaded to the i80960).  Therefore,
1117         we leave it in host byte order.
1118
1119         The above comment is no longer true.  This routine now really
1120         does do the reordering (Ian Taylor 28 Aug 92).
1121
1122   *************************************************************************** */
1123
1124 static void
1125 md_ri_to_chars (where, ri)
1126      char *where;
1127      struct relocation_info *ri;
1128 {
1129   md_number_to_chars (where, ri->r_address,
1130                       sizeof (ri->r_address));
1131   where[4] = ri->r_index & 0x0ff;
1132   where[5] = (ri->r_index >> 8) & 0x0ff;
1133   where[6] = (ri->r_index >> 16) & 0x0ff;
1134   where[7] = ((ri->r_pcrel << 0)
1135               | (ri->r_length << 1)
1136               | (ri->r_extern << 3)
1137               | (ri->r_bsr << 4)
1138               | (ri->r_disp << 5)
1139               | (ri->r_callj << 6));
1140 }
1141
1142 #endif /* defined(OBJ_AOUT) | defined(OBJ_BOUT) */
1143
1144 \f
1145 /* FOLLOWING ARE THE LOCAL ROUTINES, IN ALPHABETICAL ORDER  */
1146
1147 /*****************************************************************************
1148    brcnt_emit:  Emit code to increment inline branch counter.
1149
1150         See the comments above the declaration of 'br_cnt' for details on
1151         branch-prediction instrumentation.
1152   *************************************************************************** */
1153 static void
1154 brcnt_emit ()
1155 {
1156   ctrl_fmt (BR_CNT_FUNC, CALL, 1);      /* Emit call to "increment" routine */
1157   emit (0);                     /* Emit inline counter to be incremented */
1158 }
1159
1160 /*****************************************************************************
1161    brlab_next:  generate the next branch local label
1162
1163         See the comments above the declaration of 'br_cnt' for details on
1164         branch-prediction instrumentation.
1165   *************************************************************************** */
1166 static char *
1167 brlab_next ()
1168 {
1169   static char buf[20];
1170
1171   sprintf (buf, "%s%d", BR_LABEL_BASE, br_cnt++);
1172   return buf;
1173 }
1174
1175 /*****************************************************************************
1176    brtab_emit:  generate the fetch-prediction branch table.
1177
1178         See the comments above the declaration of 'br_cnt' for details on
1179         branch-prediction instrumentation.
1180
1181         The code emitted here would be functionally equivalent to the following
1182         example assembler source.
1183
1184                         .data
1185                         .align  2
1186            BR_TAB_NAME:
1187                         .word   0               # link to next table
1188                         .word   3               # length of table
1189                         .word   LBRANCH0        # 1st entry in table proper
1190                         .word   LBRANCH1
1191                         .word   LBRANCH2
1192   **************************************************************************** */
1193 void
1194 brtab_emit ()
1195 {
1196   int i;
1197   char buf[20];
1198   char *p;                      /* Where the binary was output to */
1199   /* Pointer to description of deferred address fixup.  */
1200   fixS *fixP;
1201
1202   if (!instrument_branches)
1203     {
1204       return;
1205     }
1206
1207   subseg_set (data_section, 0); /*      .data */
1208   frag_align (2, 0, 0);         /*      .align 2 */
1209   record_alignment (now_seg, 2);
1210   colon (BR_TAB_NAME);          /* BR_TAB_NAME: */
1211   emit (0);                     /*      .word 0 #link to next table */
1212   emit (br_cnt);                /*      .word n #length of table */
1213
1214   for (i = 0; i < br_cnt; i++)
1215     {
1216       sprintf (buf, "%s%d", BR_LABEL_BASE, i);
1217       p = emit (0);
1218       fixP = fix_new (frag_now,
1219                       p - frag_now->fr_literal,
1220                       4,
1221                       symbol_find (buf),
1222                       0,
1223                       0,
1224                       NO_RELOC);
1225     }
1226 }
1227
1228 /*****************************************************************************
1229    cobr_fmt:    generate a COBR-format instruction
1230
1231   *************************************************************************** */
1232 static void
1233 cobr_fmt (arg, opcode, oP)
1234      /* arg[0]->opcode mnemonic, arg[1-3]->operands (ascii) */
1235      char *arg[];
1236      /* Opcode, with branch-prediction bits already set if necessary.  */
1237      long opcode;
1238      /* Pointer to description of instruction.  */
1239      struct i960_opcode *oP;
1240 {
1241   long instr;                   /* 32-bit instruction */
1242   struct regop regop;           /* Description of register operand */
1243   int n;                        /* Number of operands */
1244   int var_frag;                 /* 1 if varying length code fragment should
1245                                  *    be emitted;  0 if an address fix
1246                                  *      should be emitted.
1247                                  */
1248
1249   instr = opcode;
1250   n = oP->num_ops;
1251
1252   if (n >= 1)
1253     {
1254       /* First operand (if any) of a COBR is always a register
1255          operand.  Parse it.  */
1256       parse_regop (&regop, arg[1], oP->operand[0]);
1257       instr |= (regop.n << 19) | (regop.mode << 13);
1258     }
1259   if (n >= 2)
1260     {
1261       /* Second operand (if any) of a COBR is always a register
1262          operand.  Parse it.  */
1263     parse_regop (&regop, arg[2], oP->operand[1]);
1264       instr |= (regop.n << 14) | regop.special;
1265     }
1266
1267   if (n < 3)
1268     {
1269       emit (instr);
1270
1271     }
1272   else
1273     {
1274       if (instrument_branches)
1275         {
1276           brcnt_emit ();
1277           colon (brlab_next ());
1278         }
1279
1280       /* A third operand to a COBR is always a displacement.  Parse
1281          it; if it's relaxable (a cobr "j" directive, or any cobr
1282          other than bbs/bbc when the "-norelax" option is not in use)
1283          set up a variable code fragment; otherwise set up an address
1284          fix.  */
1285       var_frag = !norelax || (oP->format == COJ);       /* TRUE or FALSE */
1286       get_cdisp (arg[3], "COBR", instr, 13, var_frag, 0);
1287
1288       if (instrument_branches)
1289         {
1290           brcnt_emit ();
1291         }
1292     }
1293 }                               /* cobr_fmt() */
1294
1295 /*****************************************************************************
1296    ctrl_fmt:    generate a CTRL-format instruction
1297
1298   *************************************************************************** */
1299 static void
1300 ctrl_fmt (targP, opcode, num_ops)
1301      char *targP;               /* Pointer to text of lone operand (if any) */
1302      long opcode;               /* Template of instruction */
1303      int num_ops;               /* Number of operands */
1304 {
1305   int instrument;               /* TRUE iff we should add instrumentation to track
1306                                    * how often the branch is taken
1307                                  */
1308
1309   if (num_ops == 0)
1310     {
1311       emit (opcode);            /* Output opcode */
1312     }
1313   else
1314     {
1315
1316       instrument = instrument_branches && (opcode != CALL)
1317         && (opcode != B) && (opcode != RET) && (opcode != BAL);
1318
1319       if (instrument)
1320         {
1321           brcnt_emit ();
1322           colon (brlab_next ());
1323         }
1324
1325       /* The operand MUST be an ip-relative displacment. Parse it
1326          * and set up address fix for the instruction we just output.
1327        */
1328       get_cdisp (targP, "CTRL", opcode, 24, 0, 0);
1329
1330       if (instrument)
1331         {
1332           brcnt_emit ();
1333         }
1334     }
1335
1336 }
1337
1338 /*****************************************************************************
1339    emit:        output instruction binary
1340
1341         Output instruction binary, in target byte order, 4 bytes at a time.
1342         Return pointer to where it was placed.
1343
1344   *************************************************************************** */
1345 static char *
1346 emit (instr)
1347      long instr;                /* Word to be output, host byte order */
1348 {
1349   char *toP;                    /* Where to output it */
1350
1351   toP = frag_more (4);          /* Allocate storage */
1352   md_number_to_chars (toP, instr, 4);   /* Convert to target byte order */
1353   return toP;
1354 }
1355
1356 /*****************************************************************************
1357    get_args:    break individual arguments out of comma-separated list
1358
1359    Input assumptions:
1360         - all comments and labels have been removed
1361         - all strings of whitespace have been collapsed to a single blank.
1362         - all character constants ('x') have been replaced with decimal
1363
1364    Output:
1365         args[0] is untouched. args[1] points to first operand, etc. All args:
1366         - are NULL-terminated
1367         - contain no whitespace
1368
1369    Return value:
1370         Number of operands (0,1,2, or 3) or -1 on error.
1371
1372   *************************************************************************** */
1373 static int
1374 get_args (p, args)
1375      /* Pointer to comma-separated operands; MUCKED BY US */
1376      register char *p;
1377      /* Output arg: pointers to operands placed in args[1-3].  MUST
1378         ACCOMMODATE 4 ENTRIES (args[0-3]).  */
1379      char *args[];
1380 {
1381   register int n;               /* Number of operands */
1382   register char *to;
1383
1384   /* Skip lead white space */
1385   while (*p == ' ')
1386     {
1387       p++;
1388     }
1389
1390   if (*p == '\0')
1391     {
1392       return 0;
1393     }
1394
1395   n = 1;
1396   args[1] = p;
1397
1398   /* Squeze blanks out by moving non-blanks toward start of string.
1399      * Isolate operands, whenever comma is found.
1400    */
1401   to = p;
1402   while (*p != '\0')
1403     {
1404
1405       if (*p == ' '
1406           && (! ISALNUM (p[1])
1407               || ! ISALNUM (p[-1])))
1408         {
1409           p++;
1410
1411         }
1412       else if (*p == ',')
1413         {
1414
1415           /* Start of operand */
1416           if (n == 3)
1417             {
1418               as_bad (_("too many operands"));
1419               return -1;
1420             }
1421           *to++ = '\0';         /* Terminate argument */
1422           args[++n] = to;       /* Start next argument */
1423           p++;
1424
1425         }
1426       else
1427         {
1428           *to++ = *p++;
1429         }
1430     }
1431   *to = '\0';
1432   return n;
1433 }
1434
1435 /*****************************************************************************
1436    get_cdisp:   handle displacement for a COBR or CTRL instruction.
1437
1438         Parse displacement for a COBR or CTRL instruction.
1439
1440         If successful, output the instruction opcode and set up for it,
1441         depending on the arg 'var_frag', either:
1442             o an address fixup to be done when all symbol values are known, or
1443             o a varying length code fragment, with address fixup info.  This
1444                 will be done for cobr instructions that may have to be relaxed
1445                 in to compare/branch instructions (8 bytes) if the final
1446                 address displacement is greater than 13 bits.
1447
1448   ****************************************************************************/
1449 static void
1450 get_cdisp (dispP, ifmtP, instr, numbits, var_frag, callj)
1451      /* displacement as specified in source instruction */
1452      char *dispP;
1453      /* "COBR" or "CTRL" (for use in error message) */
1454      char *ifmtP;
1455      /* Instruction needing the displacement */
1456      long instr;
1457      /* # bits of displacement (13 for COBR, 24 for CTRL) */
1458      int numbits;
1459      /* 1 if varying length code fragment should be emitted;
1460       *       0 if an address fix should be emitted.
1461       */
1462      int var_frag;
1463      /* 1 if callj relocation should be done; else 0 */
1464      int callj;
1465 {
1466   expressionS e;                /* Parsed expression */
1467   fixS *fixP;                   /* Structure describing needed address fix */
1468   char *outP;                   /* Where instruction binary is output to */
1469
1470   fixP = NULL;
1471
1472   parse_expr (dispP, &e);
1473   switch (e.X_op)
1474     {
1475     case O_illegal:
1476       as_bad (_("expression syntax error"));
1477
1478     case O_symbol:
1479       if (S_GET_SEGMENT (e.X_add_symbol) == now_seg
1480           || S_GET_SEGMENT (e.X_add_symbol) == undefined_section)
1481         {
1482           if (var_frag)
1483             {
1484               outP = frag_more (8);     /* Allocate worst-case storage */
1485               md_number_to_chars (outP, instr, 4);
1486               frag_variant (rs_machine_dependent, 4, 4, 1,
1487                             adds (e), offs (e), outP);
1488             }
1489           else
1490             {
1491               /* Set up a new fix structure, so address can be updated
1492                * when all symbol values are known.
1493                */
1494               outP = emit (instr);
1495               fixP = fix_new (frag_now,
1496                               outP - frag_now->fr_literal,
1497                               4,
1498                               adds (e),
1499                               offs (e),
1500                               1,
1501                               NO_RELOC);
1502
1503               fixP->fx_tcbit = callj;
1504
1505               /* We want to modify a bit field when the address is
1506                * known.  But we don't need all the garbage in the
1507                * bit_fix structure.  So we're going to lie and store
1508                * the number of bits affected instead of a pointer.
1509                */
1510               fixP->fx_bit_fixP = (bit_fixS *) numbits;
1511             }
1512         }
1513       else
1514         as_bad (_("attempt to branch into different segment"));
1515       break;
1516
1517     default:
1518       as_bad (_("target of %s instruction must be a label"), ifmtP);
1519       break;
1520     }
1521 }
1522
1523 /*****************************************************************************
1524    get_ispec:   parse a memory operand for an index specification
1525
1526         Here, an "index specification" is taken to be anything surrounded
1527         by square brackets and NOT followed by anything else.
1528
1529         If it's found, detach it from the input string, remove the surrounding
1530         square brackets, and return a pointer to it.  Otherwise, return NULL.
1531
1532   *************************************************************************** */
1533 static char *
1534 get_ispec (textP)
1535      /* Pointer to memory operand from source instruction, no white space.  */
1536      char *textP;
1537 {
1538   /* Points to start of index specification.  */
1539   char *start;
1540   /* Points to end of index specification.  */
1541   char *end;
1542
1543   /* Find opening square bracket, if any.  */
1544   start = strchr (textP, '[');
1545
1546   if (start != NULL)
1547     {
1548
1549       /* Eliminate '[', detach from rest of operand */
1550       *start++ = '\0';
1551
1552       end = strchr (start, ']');
1553
1554       if (end == NULL)
1555         {
1556           as_bad (_("unmatched '['"));
1557
1558         }
1559       else
1560         {
1561           /* Eliminate ']' and make sure it was the last thing
1562              * in the string.
1563            */
1564           *end = '\0';
1565           if (*(end + 1) != '\0')
1566             {
1567               as_bad (_("garbage after index spec ignored"));
1568             }
1569         }
1570     }
1571   return start;
1572 }
1573
1574 /*****************************************************************************
1575    get_regnum:
1576
1577         Look up a (suspected) register name in the register table and return the
1578         associated register number (or -1 if not found).
1579
1580   *************************************************************************** */
1581 static int
1582 get_regnum (regname)
1583      char *regname;             /* Suspected register name */
1584 {
1585   int *rP;
1586
1587   rP = (int *) hash_find (reg_hash, regname);
1588   return (rP == NULL) ? -1 : *rP;
1589 }
1590
1591 /*****************************************************************************
1592    i_scan:      perform lexical scan of ascii assembler instruction.
1593
1594    Input assumptions:
1595         - input string is an i80960 instruction (not a pseudo-op)
1596         - all comments and labels have been removed
1597         - all strings of whitespace have been collapsed to a single blank.
1598
1599    Output:
1600         args[0] points to opcode, other entries point to operands. All strings:
1601         - are NULL-terminated
1602         - contain no whitespace
1603         - have character constants ('x') replaced with a decimal number
1604
1605    Return value:
1606         Number of operands (0,1,2, or 3) or -1 on error.
1607
1608   *************************************************************************** */
1609 static int
1610 i_scan (iP, args)
1611      /* Pointer to ascii instruction;  MUCKED BY US.  */
1612      register char *iP;
1613      /* Output arg: pointers to opcode and operands placed here.  MUST
1614         ACCOMMODATE 4 ENTRIES.  */
1615      char *args[];
1616 {
1617
1618   /* Isolate opcode */
1619   if (*(iP) == ' ')
1620     {
1621       iP++;
1622     }                           /* Skip lead space, if any */
1623   args[0] = iP;
1624   for (; *iP != ' '; iP++)
1625     {
1626       if (*iP == '\0')
1627         {
1628           /* There are no operands */
1629           if (args[0] == iP)
1630             {
1631               /* We never moved: there was no opcode either! */
1632               as_bad (_("missing opcode"));
1633               return -1;
1634             }
1635           return 0;
1636         }
1637     }
1638   *iP++ = '\0';                 /* Terminate opcode */
1639   return (get_args (iP, args));
1640 }                               /* i_scan() */
1641
1642 /*****************************************************************************
1643    mem_fmt:     generate a MEMA- or MEMB-format instruction
1644
1645   *************************************************************************** */
1646 static void
1647 mem_fmt (args, oP, callx)
1648      char *args[];              /* args[0]->opcode mnemonic, args[1-3]->operands */
1649      struct i960_opcode *oP;    /* Pointer to description of instruction */
1650      int callx;                 /* Is this a callx opcode */
1651 {
1652   int i;                        /* Loop counter */
1653   struct regop regop;           /* Description of register operand */
1654   char opdesc;                  /* Operand descriptor byte */
1655   memS instr;                   /* Description of binary to be output */
1656   char *outP;                   /* Where the binary was output to */
1657   expressionS expr;             /* Parsed expression */
1658   /* ->description of deferred address fixup */
1659   fixS *fixP;
1660
1661 #ifdef OBJ_COFF
1662   /* COFF support isn't in place yet for callx relaxing.  */
1663   callx = 0;
1664 #endif
1665
1666   memset (&instr, '\0', sizeof (memS));
1667   instr.opcode = oP->opcode;
1668
1669   /* Process operands.  */
1670   for (i = 1; i <= oP->num_ops; i++)
1671     {
1672       opdesc = oP->operand[i - 1];
1673
1674       if (MEMOP (opdesc))
1675         {
1676           parse_memop (&instr, args[i], oP->format);
1677         }
1678       else
1679         {
1680           parse_regop (&regop, args[i], opdesc);
1681           instr.opcode |= regop.n << 19;
1682         }
1683     }
1684
1685   /* Parse the displacement; this must be done before emitting the
1686      opcode, in case it is an expression using `.'.  */
1687   parse_expr (instr.e, &expr);
1688
1689   /* Output opcode */
1690   outP = emit (instr.opcode);
1691
1692   if (instr.disp == 0)
1693     {
1694       return;
1695     }
1696
1697   /* Process the displacement */
1698   switch (expr.X_op)
1699     {
1700     case O_illegal:
1701       as_bad (_("expression syntax error"));
1702       break;
1703
1704     case O_constant:
1705       if (instr.disp == 32)
1706         {
1707           (void) emit (offs (expr));    /* Output displacement */
1708         }
1709       else
1710         {
1711           /* 12-bit displacement */
1712           if (offs (expr) & ~0xfff)
1713             {
1714               /* Won't fit in 12 bits: convert already-output
1715                * instruction to MEMB format, output
1716                * displacement.
1717                */
1718               mema_to_memb (outP);
1719               (void) emit (offs (expr));
1720             }
1721           else
1722             {
1723               /* WILL fit in 12 bits:  OR into opcode and
1724                * overwrite the binary we already put out
1725                */
1726               instr.opcode |= offs (expr);
1727               md_number_to_chars (outP, instr.opcode, 4);
1728             }
1729         }
1730       break;
1731
1732     default:
1733       if (instr.disp == 12)
1734         {
1735           /* Displacement is dependent on a symbol, whose value
1736            * may change at link time.  We HAVE to reserve 32 bits.
1737            * Convert already-output opcode to MEMB format.
1738            */
1739           mema_to_memb (outP);
1740         }
1741
1742       /* Output 0 displacement and set up address fixup for when
1743        * this symbol's value becomes known.
1744        */
1745       outP = emit ((long) 0);
1746       fixP = fix_new_exp (frag_now,
1747                           outP - frag_now->fr_literal,
1748                           4,
1749                           &expr,
1750                           0,
1751                           NO_RELOC);
1752       /* Steve's linker relaxing hack.  Mark this 32-bit relocation as
1753          being in the instruction stream, specifically as part of a callx
1754          instruction.  */
1755       fixP->fx_bsr = callx;
1756       break;
1757     }
1758 }                               /* memfmt() */
1759
1760 /*****************************************************************************
1761    mema_to_memb:        convert a MEMA-format opcode to a MEMB-format opcode.
1762
1763    There are 2 possible MEMA formats:
1764         - displacement only
1765         - displacement + abase
1766
1767    They are distinguished by the setting of the MEMA_ABASE bit.
1768
1769   *************************************************************************** */
1770 static void
1771 mema_to_memb (opcodeP)
1772      char *opcodeP;             /* Where to find the opcode, in target byte order */
1773 {
1774   long opcode;                  /* Opcode in host byte order */
1775   long mode;                    /* Mode bits for MEMB instruction */
1776
1777   opcode = md_chars_to_number (opcodeP, 4);
1778   know (!(opcode & MEMB_BIT));
1779
1780   mode = MEMB_BIT | D_BIT;
1781   if (opcode & MEMA_ABASE)
1782     {
1783       mode |= A_BIT;
1784     }
1785
1786   opcode &= 0xffffc000;         /* Clear MEMA offset and mode bits */
1787   opcode |= mode;               /* Set MEMB mode bits */
1788
1789   md_number_to_chars (opcodeP, opcode, 4);
1790 }                               /* mema_to_memb() */
1791
1792 /*****************************************************************************
1793    parse_expr:          parse an expression
1794
1795         Use base assembler's expression parser to parse an expression.
1796         It, unfortunately, runs off a global which we have to save/restore
1797         in order to make it work for us.
1798
1799         An empty expression string is treated as an absolute 0.
1800
1801         Sets O_illegal regardless of expression evaluation if entire input
1802         string is not consumed in the evaluation -- tolerate no dangling junk!
1803
1804   *************************************************************************** */
1805 static void
1806 parse_expr (textP, expP)
1807      char *textP;               /* Text of expression to be parsed */
1808      expressionS *expP;         /* Where to put the results of parsing */
1809 {
1810   char *save_in;                /* Save global here */
1811   symbolS *symP;
1812
1813   know (textP);
1814
1815   if (*textP == '\0')
1816     {
1817       /* Treat empty string as absolute 0 */
1818       expP->X_add_symbol = expP->X_op_symbol = NULL;
1819       expP->X_add_number = 0;
1820       expP->X_op = O_constant;
1821     }
1822   else
1823     {
1824       save_in = input_line_pointer;     /* Save global */
1825       input_line_pointer = textP;       /* Make parser work for us */
1826
1827       (void) expression (expP);
1828       if ((size_t) (input_line_pointer - textP) != strlen (textP))
1829         {
1830           /* Did not consume all of the input */
1831           expP->X_op = O_illegal;
1832         }
1833       symP = expP->X_add_symbol;
1834       if (symP && (hash_find (reg_hash, S_GET_NAME (symP))))
1835         {
1836           /* Register name in an expression */
1837           /* FIXME: this isn't much of a check any more.  */
1838           expP->X_op = O_illegal;
1839         }
1840
1841       input_line_pointer = save_in;     /* Restore global */
1842     }
1843 }
1844
1845 /*****************************************************************************
1846    parse_ldcont:
1847         Parse and replace a 'ldconst' pseudo-instruction with an appropriate
1848         i80960 instruction.
1849
1850         Assumes the input consists of:
1851                 arg[0]  opcode mnemonic ('ldconst')
1852                 arg[1]  first operand (constant)
1853                 arg[2]  name of register to be loaded
1854
1855         Replaces opcode and/or operands as appropriate.
1856
1857         Returns the new number of arguments, or -1 on failure.
1858
1859   *************************************************************************** */
1860 static int
1861 parse_ldconst (arg)
1862      char *arg[];               /* See above */
1863 {
1864   int n;                        /* Constant to be loaded */
1865   int shift;                    /* Shift count for "shlo" instruction */
1866   static char buf[5];           /* Literal for first operand */
1867   static char buf2[5];          /* Literal for second operand */
1868   expressionS e;                /* Parsed expression */
1869
1870   arg[3] = NULL;                /* So we can tell at the end if it got used or not */
1871
1872   parse_expr (arg[1], &e);
1873   switch (e.X_op)
1874     {
1875     default:
1876       /* We're dependent on one or more symbols -- use "lda" */
1877       arg[0] = "lda";
1878       break;
1879
1880     case O_constant:
1881       /* Try the following mappings:
1882        *      ldconst 0,<reg>  ->mov  0,<reg>
1883        *        ldconst 31,<reg> ->mov  31,<reg>
1884        *        ldconst 32,<reg> ->addo 1,31,<reg>
1885        *        ldconst 62,<reg> ->addo 31,31,<reg>
1886        *        ldconst 64,<reg> ->shlo 8,3,<reg>
1887        *        ldconst -1,<reg> ->subo 1,0,<reg>
1888        *        ldconst -31,<reg>->subo 31,0,<reg>
1889        *
1890        * anthing else becomes:
1891        *        lda xxx,<reg>
1892        */
1893       n = offs (e);
1894       if ((0 <= n) && (n <= 31))
1895         {
1896           arg[0] = "mov";
1897
1898         }
1899       else if ((-31 <= n) && (n <= -1))
1900         {
1901           arg[0] = "subo";
1902           arg[3] = arg[2];
1903           sprintf (buf, "%d", -n);
1904           arg[1] = buf;
1905           arg[2] = "0";
1906
1907         }
1908       else if ((32 <= n) && (n <= 62))
1909         {
1910           arg[0] = "addo";
1911           arg[3] = arg[2];
1912           arg[1] = "31";
1913           sprintf (buf, "%d", n - 31);
1914           arg[2] = buf;
1915
1916         }
1917       else if ((shift = shift_ok (n)) != 0)
1918         {
1919           arg[0] = "shlo";
1920           arg[3] = arg[2];
1921           sprintf (buf, "%d", shift);
1922           arg[1] = buf;
1923           sprintf (buf2, "%d", n >> shift);
1924           arg[2] = buf2;
1925
1926         }
1927       else
1928         {
1929           arg[0] = "lda";
1930         }
1931       break;
1932
1933     case O_illegal:
1934       as_bad (_("invalid constant"));
1935       return -1;
1936       break;
1937     }
1938   return (arg[3] == 0) ? 2 : 3;
1939 }
1940
1941 /*****************************************************************************
1942    parse_memop: parse a memory operand
1943
1944         This routine is based on the observation that the 4 mode bits of the
1945         MEMB format, taken individually, have fairly consistent meaning:
1946
1947                  M3 (bit 13): 1 if displacement is present (D_BIT)
1948                  M2 (bit 12): 1 for MEMB instructions (MEMB_BIT)
1949                  M1 (bit 11): 1 if index is present (I_BIT)
1950                  M0 (bit 10): 1 if abase is present (A_BIT)
1951
1952         So we parse the memory operand and set bits in the mode as we find
1953         things.  Then at the end, if we go to MEMB format, we need only set
1954         the MEMB bit (M2) and our mode is built for us.
1955
1956         Unfortunately, I said "fairly consistent".  The exceptions:
1957
1958                  DBIA
1959                  0100   Would seem illegal, but means "abase-only".
1960
1961                  0101   Would seem to mean "abase-only" -- it means IP-relative.
1962                         Must be converted to 0100.
1963
1964                  0110   Would seem to mean "index-only", but is reserved.
1965                         We turn on the D bit and provide a 0 displacement.
1966
1967         The other thing to observe is that we parse from the right, peeling
1968         things * off as we go:  first any index spec, then any abase, then
1969         the displacement.
1970
1971   *************************************************************************** */
1972 static void
1973 parse_memop (memP, argP, optype)
1974      memS *memP;                /* Where to put the results */
1975      char *argP;                /* Text of the operand to be parsed */
1976      int optype;                /* MEM1, MEM2, MEM4, MEM8, MEM12, or MEM16 */
1977 {
1978   char *indexP;                 /* Pointer to index specification with "[]" removed */
1979   char *p;                      /* Temp char pointer */
1980   char iprel_flag;              /* True if this is an IP-relative operand */
1981   int regnum;                   /* Register number */
1982   /* Scale factor: 1,2,4,8, or 16.  Later converted to internal format
1983      (0,1,2,3,4 respectively).  */
1984   int scale;
1985   int mode;                     /* MEMB mode bits */
1986   int *intP;                    /* Pointer to register number */
1987
1988   /* The following table contains the default scale factors for each
1989      type of memory instruction.  It is accessed using (optype-MEM1)
1990      as an index -- thus it assumes the 'optype' constants are
1991      assigned consecutive values, in the order they appear in this
1992      table.  */
1993   static const int def_scale[] =
1994   {
1995     1,                          /* MEM1 */
1996     2,                          /* MEM2 */
1997     4,                          /* MEM4 */
1998     8,                          /* MEM8 */
1999     -1,                         /* MEM12 -- no valid default */
2000     16                          /* MEM16 */
2001   };
2002
2003   iprel_flag = mode = 0;
2004
2005   /* Any index present? */
2006   indexP = get_ispec (argP);
2007   if (indexP)
2008     {
2009       p = strchr (indexP, '*');
2010       if (p == NULL)
2011         {
2012           /* No explicit scale -- use default for this instruction
2013              type and assembler mode.  */
2014           if (flag_mri)
2015             scale = 1;
2016           else
2017             /* GNU960 compatibility */
2018             scale = def_scale[optype - MEM1];
2019         }
2020       else
2021         {
2022           *p++ = '\0';          /* Eliminate '*' */
2023
2024           /* Now indexP->a '\0'-terminated register name,
2025              * and p->a scale factor.
2026            */
2027
2028           if (!strcmp (p, "16"))
2029             {
2030               scale = 16;
2031             }
2032           else if (strchr ("1248", *p) && (p[1] == '\0'))
2033             {
2034               scale = *p - '0';
2035             }
2036           else
2037             {
2038               scale = -1;
2039             }
2040         }
2041
2042       regnum = get_regnum (indexP);     /* Get index reg. # */
2043       if (!IS_RG_REG (regnum))
2044         {
2045           as_bad (_("invalid index register"));
2046           return;
2047         }
2048
2049       /* Convert scale to its binary encoding */
2050       switch (scale)
2051         {
2052         case 1:
2053           scale = 0 << 7;
2054           break;
2055         case 2:
2056           scale = 1 << 7;
2057           break;
2058         case 4:
2059           scale = 2 << 7;
2060           break;
2061         case 8:
2062           scale = 3 << 7;
2063           break;
2064         case 16:
2065           scale = 4 << 7;
2066           break;
2067         default:
2068           as_bad (_("invalid scale factor"));
2069           return;
2070         };
2071
2072       memP->opcode |= scale | regnum;   /* Set index bits in opcode */
2073       mode |= I_BIT;            /* Found a valid index spec */
2074     }
2075
2076   /* Any abase (Register Indirect) specification present? */
2077   if ((p = strrchr (argP, '(')) != NULL)
2078     {
2079       /* "(" is there -- does it start a legal abase spec?  If not, it
2080          could be part of a displacement expression.  */
2081       intP = (int *) hash_find (areg_hash, p);
2082       if (intP != NULL)
2083         {
2084           /* Got an abase here */
2085           regnum = *intP;
2086           *p = '\0';            /* discard register spec */
2087           if (regnum == IPREL)
2088             {
2089               /* We have to specialcase ip-rel mode */
2090               iprel_flag = 1;
2091             }
2092           else
2093             {
2094               memP->opcode |= regnum << 14;
2095               mode |= A_BIT;
2096             }
2097         }
2098     }
2099
2100   /* Any expression present? */
2101   memP->e = argP;
2102   if (*argP != '\0')
2103     {
2104       mode |= D_BIT;
2105     }
2106
2107   /* Special-case ip-relative addressing */
2108   if (iprel_flag)
2109     {
2110       if (mode & I_BIT)
2111         {
2112           syntax ();
2113         }
2114       else
2115         {
2116           memP->opcode |= 5 << 10;      /* IP-relative mode */
2117           memP->disp = 32;
2118         }
2119       return;
2120     }
2121
2122   /* Handle all other modes */
2123   switch (mode)
2124     {
2125     case D_BIT | A_BIT:
2126       /* Go with MEMA instruction format for now (grow to MEMB later
2127          if 12 bits is not enough for the displacement).  MEMA format
2128          has a single mode bit: set it to indicate that abase is
2129          present.  */
2130       memP->opcode |= MEMA_ABASE;
2131       memP->disp = 12;
2132       break;
2133
2134     case D_BIT:
2135       /* Go with MEMA instruction format for now (grow to MEMB later
2136          if 12 bits is not enough for the displacement).  */
2137       memP->disp = 12;
2138       break;
2139
2140     case A_BIT:
2141       /* For some reason, the bit string for this mode is not
2142          consistent: it should be 0 (exclusive of the MEMB bit), so we
2143          set it "by hand" here.  */
2144       memP->opcode |= MEMB_BIT;
2145       break;
2146
2147     case A_BIT | I_BIT:
2148       /* set MEMB bit in mode, and OR in mode bits */
2149       memP->opcode |= mode | MEMB_BIT;
2150       break;
2151
2152     case I_BIT:
2153       /* Treat missing displacement as displacement of 0.  */
2154       mode |= D_BIT;
2155       /* Fall into next case.  */
2156     case D_BIT | A_BIT | I_BIT:
2157     case D_BIT | I_BIT:
2158       /* set MEMB bit in mode, and OR in mode bits */
2159       memP->opcode |= mode | MEMB_BIT;
2160       memP->disp = 32;
2161       break;
2162
2163     default:
2164       syntax ();
2165       break;
2166     }
2167 }
2168
2169 /*****************************************************************************
2170    parse_po:    parse machine-dependent pseudo-op
2171
2172         This is a top-level routine for machine-dependent pseudo-ops.  It slurps
2173         up the rest of the input line, breaks out the individual arguments,
2174         and dispatches them to the correct handler.
2175   *************************************************************************** */
2176 static void
2177 parse_po (po_num)
2178      int po_num;                /* Pseudo-op number:  currently S_LEAFPROC or S_SYSPROC */
2179 {
2180   /* Pointers operands, with no embedded whitespace.
2181      arg[0] unused, arg[1-3]->operands */
2182   char *args[4];
2183   int n_ops;                    /* Number of operands */
2184   char *p;                      /* Pointer to beginning of unparsed argument string */
2185   char eol;                     /* Character that indicated end of line */
2186
2187   extern char is_end_of_line[];
2188
2189   /* Advance input pointer to end of line.  */
2190   p = input_line_pointer;
2191   while (!is_end_of_line[(unsigned char) *input_line_pointer])
2192     {
2193       input_line_pointer++;
2194     }
2195   eol = *input_line_pointer;    /* Save end-of-line char */
2196   *input_line_pointer = '\0';   /* Terminate argument list */
2197
2198   /* Parse out operands */
2199   n_ops = get_args (p, args);
2200   if (n_ops == -1)
2201     {
2202       return;
2203     }
2204
2205   /* Dispatch to correct handler */
2206   switch (po_num)
2207     {
2208     case S_SYSPROC:
2209       s_sysproc (n_ops, args);
2210       break;
2211     case S_LEAFPROC:
2212       s_leafproc (n_ops, args);
2213       break;
2214     default:
2215       BAD_CASE (po_num);
2216       break;
2217     }
2218
2219   /* Restore eol, so line numbers get updated correctly.  Base
2220      assembler assumes we leave input pointer pointing at char
2221      following the eol.  */
2222   *input_line_pointer++ = eol;
2223 }
2224
2225 /*****************************************************************************
2226    parse_regop: parse a register operand.
2227
2228         In case of illegal operand, issue a message and return some valid
2229         information so instruction processing can continue.
2230   *************************************************************************** */
2231 static void
2232 parse_regop (regopP, optext, opdesc)
2233      struct regop *regopP;      /* Where to put description of register operand */
2234      char *optext;              /* Text of operand */
2235      char opdesc;               /* Descriptor byte:  what's legal for this operand */
2236 {
2237   int n;                        /* Register number */
2238   expressionS e;                /* Parsed expression */
2239
2240   /* See if operand is a register */
2241   n = get_regnum (optext);
2242   if (n >= 0)
2243     {
2244       if (IS_RG_REG (n))
2245         {
2246           /* global or local register */
2247           if (!REG_ALIGN (opdesc, n))
2248             {
2249               as_bad (_("unaligned register"));
2250             }
2251           regopP->n = n;
2252           regopP->mode = 0;
2253           regopP->special = 0;
2254           return;
2255         }
2256       else if (IS_FP_REG (n) && FP_OK (opdesc))
2257         {
2258           /* Floating point register, and it's allowed */
2259           regopP->n = n - FP0;
2260           regopP->mode = 1;
2261           regopP->special = 0;
2262           return;
2263         }
2264       else if (IS_SF_REG (n) && SFR_OK (opdesc))
2265         {
2266           /* Special-function register, and it's allowed */
2267           regopP->n = n - SF0;
2268           regopP->mode = 0;
2269           regopP->special = 1;
2270           if (!targ_has_sfr (regopP->n))
2271             {
2272               as_bad (_("no such sfr in this architecture"));
2273             }
2274           return;
2275         }
2276     }
2277   else if (LIT_OK (opdesc))
2278     {
2279       /* How about a literal?  */
2280       regopP->mode = 1;
2281       regopP->special = 0;
2282       if (FP_OK (opdesc))
2283         {                       /* floating point literal acceptable */
2284           /* Skip over 0f, 0d, or 0e prefix */
2285           if ((optext[0] == '0')
2286               && (optext[1] >= 'd')
2287               && (optext[1] <= 'f'))
2288             {
2289               optext += 2;
2290             }
2291
2292           if (!strcmp (optext, "0.0") || !strcmp (optext, "0"))
2293             {
2294               regopP->n = 0x10;
2295               return;
2296             }
2297           if (!strcmp (optext, "1.0") || !strcmp (optext, "1"))
2298             {
2299               regopP->n = 0x16;
2300               return;
2301             }
2302
2303         }
2304       else
2305         {                       /* fixed point literal acceptable */
2306           parse_expr (optext, &e);
2307           if (e.X_op != O_constant
2308               || (offs (e) < 0) || (offs (e) > 31))
2309             {
2310               as_bad (_("illegal literal"));
2311               offs (e) = 0;
2312             }
2313           regopP->n = offs (e);
2314           return;
2315         }
2316     }
2317
2318   /* Nothing worked */
2319   syntax ();
2320   regopP->mode = 0;             /* Register r0 is always a good one */
2321   regopP->n = 0;
2322   regopP->special = 0;
2323 }                               /* parse_regop() */
2324
2325 /*****************************************************************************
2326    reg_fmt:     generate a REG-format instruction
2327
2328   *************************************************************************** */
2329 static void
2330 reg_fmt (args, oP)
2331      char *args[];              /* args[0]->opcode mnemonic, args[1-3]->operands */
2332      struct i960_opcode *oP;    /* Pointer to description of instruction */
2333 {
2334   long instr;                   /* Binary to be output */
2335   struct regop regop;           /* Description of register operand */
2336   int n_ops;                    /* Number of operands */
2337
2338   instr = oP->opcode;
2339   n_ops = oP->num_ops;
2340
2341   if (n_ops >= 1)
2342     {
2343       parse_regop (&regop, args[1], oP->operand[0]);
2344
2345       if ((n_ops == 1) && !(instr & M3))
2346         {
2347           /* 1-operand instruction in which the dst field should
2348              * be used (instead of src1).
2349            */
2350           regop.n <<= 19;
2351           if (regop.special)
2352             {
2353               regop.mode = regop.special;
2354             }
2355           regop.mode <<= 13;
2356           regop.special = 0;
2357         }
2358       else
2359         {
2360           /* regop.n goes in bit 0, needs no shifting */
2361           regop.mode <<= 11;
2362           regop.special <<= 5;
2363         }
2364       instr |= regop.n | regop.mode | regop.special;
2365     }
2366
2367   if (n_ops >= 2)
2368     {
2369       parse_regop (&regop, args[2], oP->operand[1]);
2370
2371       if ((n_ops == 2) && !(instr & M3))
2372         {
2373           /* 2-operand instruction in which the dst field should
2374              * be used instead of src2).
2375            */
2376           regop.n <<= 19;
2377           if (regop.special)
2378             {
2379               regop.mode = regop.special;
2380             }
2381           regop.mode <<= 13;
2382           regop.special = 0;
2383         }
2384       else
2385         {
2386           regop.n <<= 14;
2387           regop.mode <<= 12;
2388           regop.special <<= 6;
2389         }
2390       instr |= regop.n | regop.mode | regop.special;
2391     }
2392   if (n_ops == 3)
2393     {
2394       parse_regop (&regop, args[3], oP->operand[2]);
2395       if (regop.special)
2396         {
2397           regop.mode = regop.special;
2398         }
2399       instr |= (regop.n <<= 19) | (regop.mode <<= 13);
2400     }
2401   emit (instr);
2402 }
2403
2404 /*****************************************************************************
2405    relax_cobr:
2406         Replace cobr instruction in a code fragment with equivalent branch and
2407         compare instructions, so it can reach beyond a 13-bit displacement.
2408         Set up an address fix/relocation for the new branch instruction.
2409
2410   *************************************************************************** */
2411
2412 /* This "conditional jump" table maps cobr instructions into
2413    equivalent compare and branch opcodes.  */
2414 static const
2415 struct
2416 {
2417   long compare;
2418   long branch;
2419 }
2420
2421 coj[] =
2422 {                               /* COBR OPCODE: */
2423   { CHKBIT, BNO },              /*      0x30 - bbc */
2424   { CMPO, BG },                 /*      0x31 - cmpobg */
2425   { CMPO, BE },                 /*      0x32 - cmpobe */
2426   { CMPO, BGE },                /*      0x33 - cmpobge */
2427   { CMPO, BL },                 /*      0x34 - cmpobl */
2428   { CMPO, BNE },                /*      0x35 - cmpobne */
2429   { CMPO, BLE },                /*      0x36 - cmpoble */
2430   { CHKBIT, BO },               /*      0x37 - bbs */
2431   { CMPI, BNO },                /*      0x38 - cmpibno */
2432   { CMPI, BG },                 /*      0x39 - cmpibg */
2433   { CMPI, BE },                 /*      0x3a - cmpibe */
2434   { CMPI, BGE },                /*      0x3b - cmpibge */
2435   { CMPI, BL },                 /*      0x3c - cmpibl */
2436   { CMPI, BNE },                /*      0x3d - cmpibne */
2437   { CMPI, BLE },                /*      0x3e - cmpible */
2438   { CMPI, BO },                 /*      0x3f - cmpibo */
2439 };
2440
2441 static void
2442 relax_cobr (fragP)
2443      register fragS *fragP;     /* fragP->fr_opcode is assumed to point to
2444                                  * the cobr instruction, which comes at the
2445                                  * end of the code fragment.
2446                                  */
2447 {
2448   int opcode, src1, src2, m1, s2;
2449   /* Bit fields from cobr instruction */
2450   long bp_bits;                 /* Branch prediction bits from cobr instruction */
2451   long instr;                   /* A single i960 instruction */
2452   /* ->instruction to be replaced */
2453   char *iP;
2454   fixS *fixP;                   /* Relocation that can be done at assembly time */
2455
2456   /* PICK UP & PARSE COBR INSTRUCTION */
2457   iP = fragP->fr_opcode;
2458   instr = md_chars_to_number (iP, 4);
2459   opcode = ((instr >> 24) & 0xff) - 0x30;       /* "-0x30" for table index */
2460   src1 = (instr >> 19) & 0x1f;
2461   m1 = (instr >> 13) & 1;
2462   s2 = instr & 1;
2463   src2 = (instr >> 14) & 0x1f;
2464   bp_bits = instr & BP_MASK;
2465
2466   /* GENERATE AND OUTPUT COMPARE INSTRUCTION */
2467   instr = coj[opcode].compare
2468     | src1 | (m1 << 11) | (s2 << 6) | (src2 << 14);
2469   md_number_to_chars (iP, instr, 4);
2470
2471   /* OUTPUT BRANCH INSTRUCTION */
2472   md_number_to_chars (iP + 4, coj[opcode].branch | bp_bits, 4);
2473
2474   /* SET UP ADDRESS FIXUP/RELOCATION */
2475   fixP = fix_new (fragP,
2476                   iP + 4 - fragP->fr_literal,
2477                   4,
2478                   fragP->fr_symbol,
2479                   fragP->fr_offset,
2480                   1,
2481                   NO_RELOC);
2482
2483   fixP->fx_bit_fixP = (bit_fixS *) 24;  /* Store size of bit field */
2484
2485   fragP->fr_fix += 4;
2486   frag_wane (fragP);
2487 }
2488
2489 /*****************************************************************************
2490    reloc_callj: Relocate a 'callj' instruction
2491
2492         This is a "non-(GNU)-standard" machine-dependent hook.  The base
2493         assembler calls it when it decides it can relocate an address at
2494         assembly time instead of emitting a relocation directive.
2495
2496         Check to see if the relocation involves a 'callj' instruction to a:
2497             sysproc:    Replace the default 'call' instruction with a 'calls'
2498             leafproc:   Replace the default 'call' instruction with a 'bal'.
2499             other proc: Do nothing.
2500
2501         See b.out.h for details on the 'n_other' field in a symbol structure.
2502
2503    IMPORTANT!:
2504         Assumes the caller has already figured out, in the case of a leafproc,
2505         to use the 'bal' entry point, and has substituted that symbol into the
2506         passed fixup structure.
2507
2508   *************************************************************************** */
2509 int
2510 reloc_callj (fixP)
2511      /* Relocation that can be done at assembly time */
2512      fixS *fixP;
2513 {
2514   /* Points to the binary for the instruction being relocated.  */
2515   char *where;
2516
2517   if (!fixP->fx_tcbit)
2518     {
2519       /* This wasn't a callj instruction in the first place */
2520       return 0;
2521     }
2522
2523   where = fixP->fx_frag->fr_literal + fixP->fx_where;
2524
2525   if (TC_S_IS_SYSPROC (fixP->fx_addsy))
2526     {
2527       /* Symbol is a .sysproc: replace 'call' with 'calls'.  System
2528          procedure number is (other-1).  */
2529       md_number_to_chars (where, CALLS | TC_S_GET_SYSPROC (fixP->fx_addsy), 4);
2530
2531       /* Nothing else needs to be done for this instruction.  Make
2532          sure 'md_number_to_field()' will perform a no-op.  */
2533       fixP->fx_bit_fixP = (bit_fixS *) 1;
2534     }
2535   else if (TC_S_IS_CALLNAME (fixP->fx_addsy))
2536     {
2537       /* Should not happen: see block comment above */
2538       as_fatal (_("Trying to 'bal' to %s"), S_GET_NAME (fixP->fx_addsy));
2539     }
2540   else if (TC_S_IS_BALNAME (fixP->fx_addsy))
2541     {
2542       /* Replace 'call' with 'bal'; both instructions have the same
2543          format, so calling code should complete relocation as if
2544          nothing happened here.  */
2545       md_number_to_chars (where, BAL, 4);
2546     }
2547   else if (TC_S_IS_BADPROC (fixP->fx_addsy))
2548     {
2549       as_bad (_("Looks like a proc, but can't tell what kind.\n"));
2550     }                           /* switch on proc type */
2551
2552   /* else Symbol is neither a sysproc nor a leafproc */
2553   return 0;
2554 }
2555
2556 /*****************************************************************************
2557    s_leafproc:  process .leafproc pseudo-op
2558
2559         .leafproc takes two arguments, the second one is optional:
2560                 arg[1]: name of 'call' entry point to leaf procedure
2561                 arg[2]: name of 'bal' entry point to leaf procedure
2562
2563         If the two arguments are identical, or if the second one is missing,
2564         the first argument is taken to be the 'bal' entry point.
2565
2566         If there are 2 distinct arguments, we must make sure that the 'bal'
2567         entry point immediately follows the 'call' entry point in the linked
2568         list of symbols.
2569
2570   *************************************************************************** */
2571 static void
2572 s_leafproc (n_ops, args)
2573      int n_ops;                 /* Number of operands */
2574      char *args[];              /* args[1]->1st operand, args[2]->2nd operand */
2575 {
2576   symbolS *callP;               /* Pointer to leafproc 'call' entry point symbol */
2577   symbolS *balP;                /* Pointer to leafproc 'bal' entry point symbol */
2578
2579   if ((n_ops != 1) && (n_ops != 2))
2580     {
2581       as_bad (_("should have 1 or 2 operands"));
2582       return;
2583     }                           /* Check number of arguments */
2584
2585   /* Find or create symbol for 'call' entry point.  */
2586   callP = symbol_find_or_make (args[1]);
2587
2588   if (TC_S_IS_CALLNAME (callP))
2589     {
2590       as_warn (_("Redefining leafproc %s"), S_GET_NAME (callP));
2591     }                           /* is leafproc */
2592
2593   /* If that was the only argument, use it as the 'bal' entry point.
2594      * Otherwise, mark it as the 'call' entry point and find or create
2595      * another symbol for the 'bal' entry point.
2596    */
2597   if ((n_ops == 1) || !strcmp (args[1], args[2]))
2598     {
2599       TC_S_FORCE_TO_BALNAME (callP);
2600
2601     }
2602   else
2603     {
2604       TC_S_FORCE_TO_CALLNAME (callP);
2605
2606       balP = symbol_find_or_make (args[2]);
2607       if (TC_S_IS_CALLNAME (balP))
2608         {
2609           as_warn (_("Redefining leafproc %s"), S_GET_NAME (balP));
2610         }
2611       TC_S_FORCE_TO_BALNAME (balP);
2612
2613 #ifndef OBJ_ELF
2614       tc_set_bal_of_call (callP, balP);
2615 #endif
2616     }                           /* if only one arg, or the args are the same */
2617 }
2618
2619 /*
2620    s_sysproc: process .sysproc pseudo-op
2621
2622         .sysproc takes two arguments:
2623                 arg[1]: name of entry point to system procedure
2624                 arg[2]: 'entry_num' (index) of system procedure in the range
2625                         [0,31] inclusive.
2626
2627         For [ab].out, we store the 'entrynum' in the 'n_other' field of
2628         the symbol.  Since that entry is normally 0, we bias 'entrynum'
2629         by adding 1 to it.  It must be unbiased before it is used.  */
2630 static void
2631 s_sysproc (n_ops, args)
2632      int n_ops;                 /* Number of operands */
2633      char *args[];              /* args[1]->1st operand, args[2]->2nd operand */
2634 {
2635   expressionS exp;
2636   symbolS *symP;
2637
2638   if (n_ops != 2)
2639     {
2640       as_bad (_("should have two operands"));
2641       return;
2642     }                           /* bad arg count */
2643
2644   /* Parse "entry_num" argument and check it for validity.  */
2645   parse_expr (args[2], &exp);
2646   if (exp.X_op != O_constant
2647       || (offs (exp) < 0)
2648       || (offs (exp) > 31))
2649     {
2650       as_bad (_("'entry_num' must be absolute number in [0,31]"));
2651       return;
2652     }
2653
2654   /* Find/make symbol and stick entry number (biased by +1) into it */
2655   symP = symbol_find_or_make (args[1]);
2656
2657   if (TC_S_IS_SYSPROC (symP))
2658     {
2659       as_warn (_("Redefining entrynum for sysproc %s"), S_GET_NAME (symP));
2660     }                           /* redefining */
2661
2662   TC_S_SET_SYSPROC (symP, offs (exp));  /* encode entry number */
2663   TC_S_FORCE_TO_SYSPROC (symP);
2664 }
2665
2666 /*****************************************************************************
2667    shift_ok:
2668         Determine if a "shlo" instruction can be used to implement a "ldconst".
2669         This means that some number X < 32 can be shifted left to produce the
2670         constant of interest.
2671
2672         Return the shift count, or 0 if we can't do it.
2673         Caller calculates X by shifting original constant right 'shift' places.
2674
2675   *************************************************************************** */
2676 static int
2677 shift_ok (n)
2678      int n;                     /* The constant of interest */
2679 {
2680   int shift;                    /* The shift count */
2681
2682   if (n <= 0)
2683     {
2684       /* Can't do it for negative numbers */
2685       return 0;
2686     }
2687
2688   /* Shift 'n' right until a 1 is about to be lost */
2689   for (shift = 0; (n & 1) == 0; shift++)
2690     {
2691       n >>= 1;
2692     }
2693
2694   if (n >= 32)
2695     {
2696       return 0;
2697     }
2698   return shift;
2699 }
2700
2701 /* syntax: issue syntax error */
2702
2703 static void
2704 syntax ()
2705 {
2706   as_bad (_("syntax error"));
2707 }                               /* syntax() */
2708
2709 /* targ_has_sfr:
2710
2711    Return TRUE iff the target architecture supports the specified
2712    special-function register (sfr).  */
2713
2714 static int
2715 targ_has_sfr (n)
2716      int n;                     /* Number (0-31) of sfr */
2717 {
2718   switch (architecture)
2719     {
2720     case ARCH_KA:
2721     case ARCH_KB:
2722     case ARCH_MC:
2723     case ARCH_JX:
2724       return 0;
2725     case ARCH_HX:
2726       return ((0 <= n) && (n <= 4));
2727     case ARCH_CA:
2728     default:
2729       return ((0 <= n) && (n <= 2));
2730     }
2731 }
2732
2733 /* targ_has_iclass:
2734
2735    Return TRUE iff the target architecture supports the indicated
2736    class of instructions.  */
2737 static int
2738 targ_has_iclass (ic)
2739      /* Instruction class;  one of:
2740         I_BASE, I_CX, I_DEC, I_KX, I_FP, I_MIL, I_CASIM, I_CX2, I_HX, I_HX2
2741       */
2742      int ic;
2743 {
2744   iclasses_seen |= ic;
2745   switch (architecture)
2746     {
2747     case ARCH_KA:
2748       return ic & (I_BASE | I_KX);
2749     case ARCH_KB:
2750       return ic & (I_BASE | I_KX | I_FP | I_DEC);
2751     case ARCH_MC:
2752       return ic & (I_BASE | I_KX | I_FP | I_DEC | I_MIL);
2753     case ARCH_CA:
2754       return ic & (I_BASE | I_CX | I_CX2 | I_CASIM);
2755     case ARCH_JX:
2756       return ic & (I_BASE | I_CX2 | I_JX);
2757     case ARCH_HX:
2758       return ic & (I_BASE | I_CX2 | I_JX | I_HX);
2759     default:
2760       if ((iclasses_seen & (I_KX | I_FP | I_DEC | I_MIL))
2761           && (iclasses_seen & (I_CX | I_CX2)))
2762         {
2763           as_warn (_("architecture of opcode conflicts with that of earlier instruction(s)"));
2764           iclasses_seen &= ~ic;
2765         }
2766       return 1;
2767     }
2768 }
2769
2770 /* Handle the MRI .endian pseudo-op.  */
2771
2772 static void
2773 s_endian (ignore)
2774      int ignore ATTRIBUTE_UNUSED;
2775 {
2776   char *name;
2777   char c;
2778
2779   name = input_line_pointer;
2780   c = get_symbol_end ();
2781   if (strcasecmp (name, "little") == 0)
2782     ;
2783   else if (strcasecmp (name, "big") == 0)
2784     as_bad (_("big endian mode is not supported"));
2785   else
2786     as_warn (_("ignoring unrecognized .endian type `%s'"), name);
2787
2788   *input_line_pointer = c;
2789
2790   demand_empty_rest_of_line ();
2791 }
2792
2793 /* We have no need to default values of symbols.  */
2794
2795 symbolS *
2796 md_undefined_symbol (name)
2797      char *name ATTRIBUTE_UNUSED;
2798 {
2799   return 0;
2800 }
2801
2802 /* Exactly what point is a PC-relative offset relative TO?
2803    On the i960, they're relative to the address of the instruction,
2804    which we have set up as the address of the fixup too.  */
2805 long
2806 md_pcrel_from (fixP)
2807      fixS *fixP;
2808 {
2809   return fixP->fx_where + fixP->fx_frag->fr_address;
2810 }
2811
2812 void
2813 md_apply_fix3 (fixP, valP, seg)
2814      fixS *fixP;
2815      valueT *valP;
2816      segT seg ATTRIBUTE_UNUSED;
2817 {
2818   long val = *valP;
2819   char *place = fixP->fx_where + fixP->fx_frag->fr_literal;
2820
2821   if (!fixP->fx_bit_fixP)
2822     {
2823 #ifndef BFD_ASSEMBLER
2824       /* For callx, we always want to write out zero, and emit a
2825          symbolic relocation.  */
2826       if (fixP->fx_bsr)
2827         val = 0;
2828
2829       fixP->fx_addnumber = val;
2830 #endif
2831
2832       md_number_to_imm (place, val, fixP->fx_size);
2833     }
2834   else if ((int) fixP->fx_bit_fixP == 13
2835            && fixP->fx_addsy != NULL
2836            && S_GET_SEGMENT (fixP->fx_addsy) == undefined_section)
2837     {
2838       /* This is a COBR instruction.  They have only a
2839          13-bit displacement and are only to be used
2840          for local branches: flag as error, don't generate
2841          relocation.  */
2842       as_bad_where (fixP->fx_file, fixP->fx_line,
2843                     _("can't use COBR format with external label"));
2844       fixP->fx_addsy = NULL;
2845     }
2846   else
2847     md_number_to_field (place, val, fixP->fx_bit_fixP);
2848
2849   if (fixP->fx_addsy == NULL)
2850     fixP->fx_done = 1;
2851 }
2852
2853 #if defined(OBJ_AOUT) | defined(OBJ_BOUT)
2854 void
2855 tc_bout_fix_to_chars (where, fixP, segment_address_in_file)
2856      char *where;
2857      fixS *fixP;
2858      relax_addressT segment_address_in_file;
2859 {
2860   static const unsigned char nbytes_r_length[] = {42, 0, 1, 42, 2};
2861   struct relocation_info ri;
2862   symbolS *symbolP;
2863
2864   memset ((char *) &ri, '\0', sizeof (ri));
2865   symbolP = fixP->fx_addsy;
2866   know (symbolP != 0 || fixP->fx_r_type != NO_RELOC);
2867   ri.r_bsr = fixP->fx_bsr;      /*SAC LD RELAX HACK */
2868   /* These two 'cuz of NS32K */
2869   ri.r_callj = fixP->fx_tcbit;
2870   if (fixP->fx_bit_fixP)
2871     ri.r_length = 2;
2872   else
2873     ri.r_length = nbytes_r_length[fixP->fx_size];
2874   ri.r_pcrel = fixP->fx_pcrel;
2875   ri.r_address = fixP->fx_frag->fr_address + fixP->fx_where - segment_address_in_file;
2876
2877   if (fixP->fx_r_type != NO_RELOC)
2878     {
2879       switch (fixP->fx_r_type)
2880         {
2881         case rs_align:
2882           ri.r_index = -2;
2883           ri.r_pcrel = 1;
2884           ri.r_length = fixP->fx_size - 1;
2885           break;
2886         case rs_org:
2887           ri.r_index = -2;
2888           ri.r_pcrel = 0;
2889           break;
2890         case rs_fill:
2891           ri.r_index = -1;
2892           break;
2893         default:
2894           abort ();
2895         }
2896       ri.r_extern = 0;
2897     }
2898   else if (linkrelax || !S_IS_DEFINED (symbolP) || fixP->fx_bsr)
2899     {
2900       ri.r_extern = 1;
2901       ri.r_index = symbolP->sy_number;
2902     }
2903   else
2904     {
2905       ri.r_extern = 0;
2906       ri.r_index = S_GET_TYPE (symbolP);
2907     }
2908
2909   /* Output the relocation information in machine-dependent form.  */
2910   md_ri_to_chars (where, &ri);
2911 }
2912
2913 #endif /* OBJ_AOUT or OBJ_BOUT */
2914
2915 #if defined (OBJ_COFF) && defined (BFD)
2916 short
2917 tc_coff_fix2rtype (fixP)
2918      fixS *fixP;
2919 {
2920   if (fixP->fx_bsr)
2921     abort ();
2922
2923   if (fixP->fx_pcrel == 0 && fixP->fx_size == 4)
2924     return R_RELLONG;
2925
2926   if (fixP->fx_pcrel != 0 && fixP->fx_size == 4)
2927     return R_IPRMED;
2928
2929   abort ();
2930   return 0;
2931 }
2932
2933 int
2934 tc_coff_sizemachdep (frag)
2935      fragS *frag;
2936 {
2937   if (frag->fr_next)
2938     return frag->fr_next->fr_address - frag->fr_address;
2939   else
2940     return 0;
2941 }
2942 #endif
2943
2944 /* Align an address by rounding it up to the specified boundary.  */
2945 valueT
2946 md_section_align (seg, addr)
2947      segT seg;
2948      valueT addr;               /* Address to be rounded up */
2949 {
2950   int align;
2951 #ifdef BFD_ASSEMBLER
2952   align = bfd_get_section_alignment (stdoutput, seg);
2953 #else
2954   align = section_alignment[(int) seg];
2955 #endif
2956   return (addr + (1 << align) - 1) & (-1 << align);
2957 }
2958
2959 extern int coff_flags;
2960
2961 #ifdef OBJ_COFF
2962 void
2963 tc_headers_hook (headers)
2964      object_headers *headers;
2965 {
2966   switch (architecture)
2967     {
2968     case ARCH_KA:
2969       coff_flags |= F_I960KA;
2970       break;
2971
2972     case ARCH_KB:
2973       coff_flags |= F_I960KB;
2974       break;
2975
2976     case ARCH_MC:
2977       coff_flags |= F_I960MC;
2978       break;
2979
2980     case ARCH_CA:
2981       coff_flags |= F_I960CA;
2982       break;
2983
2984     case ARCH_JX:
2985       coff_flags |= F_I960JX;
2986       break;
2987
2988     case ARCH_HX:
2989       coff_flags |= F_I960HX;
2990       break;
2991
2992     default:
2993       if (iclasses_seen == I_BASE)
2994         coff_flags |= F_I960CORE;
2995       else if (iclasses_seen & I_CX)
2996         coff_flags |= F_I960CA;
2997       else if (iclasses_seen & I_HX)
2998         coff_flags |= F_I960HX;
2999       else if (iclasses_seen & I_JX)
3000         coff_flags |= F_I960JX;
3001       else if (iclasses_seen & I_CX2)
3002         coff_flags |= F_I960CA;
3003       else if (iclasses_seen & I_MIL)
3004         coff_flags |= F_I960MC;
3005       else if (iclasses_seen & (I_DEC | I_FP))
3006         coff_flags |= F_I960KB;
3007       else
3008         coff_flags |= F_I960KA;
3009       break;
3010     }
3011
3012   if (flag_readonly_data_in_text)
3013     {
3014       headers->filehdr.f_magic = I960RWMAGIC;
3015       headers->aouthdr.magic = OMAGIC;
3016     }
3017   else
3018     {
3019       headers->filehdr.f_magic = I960ROMAGIC;
3020       headers->aouthdr.magic = NMAGIC;
3021     }                           /* set magic numbers */
3022 }
3023
3024 #endif /* OBJ_COFF */
3025
3026 #ifndef BFD_ASSEMBLER
3027
3028 /* Things going on here:
3029
3030    For bout, We need to assure a couple of simplifying
3031    assumptions about leafprocs for the linker: the leafproc
3032    entry symbols will be defined in the same assembly in
3033    which they're declared with the '.leafproc' directive;
3034    and if a leafproc has both 'call' and 'bal' entry points
3035    they are both global or both local.
3036
3037    For coff, the call symbol has a second aux entry that
3038    contains the bal entry point.  The bal symbol becomes a
3039    label.
3040
3041    For coff representation, the call symbol has a second aux entry that
3042    contains the bal entry point.  The bal symbol becomes a label.  */
3043
3044 void
3045 tc_crawl_symbol_chain (headers)
3046      object_headers *headers ATTRIBUTE_UNUSED;
3047 {
3048   symbolS *symbolP;
3049
3050   for (symbolP = symbol_rootP; symbolP; symbolP = symbol_next (symbolP))
3051     {
3052 #ifdef OBJ_COFF
3053       if (TC_S_IS_SYSPROC (symbolP))
3054         {
3055           /* second aux entry already contains the sysproc number */
3056           S_SET_NUMBER_AUXILIARY (symbolP, 2);
3057           S_SET_STORAGE_CLASS (symbolP, C_SCALL);
3058           S_SET_DATA_TYPE (symbolP, S_GET_DATA_TYPE (symbolP) | (DT_FCN << N_BTSHFT));
3059           continue;
3060         }                       /* rewrite sysproc */
3061 #endif /* OBJ_COFF */
3062
3063       if (!TC_S_IS_BALNAME (symbolP) && !TC_S_IS_CALLNAME (symbolP))
3064         {
3065           continue;
3066         }                       /* Not a leafproc symbol */
3067
3068       if (!S_IS_DEFINED (symbolP))
3069         {
3070           as_bad (_("leafproc symbol '%s' undefined"), S_GET_NAME (symbolP));
3071         }                       /* undefined leaf */
3072
3073       if (TC_S_IS_CALLNAME (symbolP))
3074         {
3075           symbolS *balP = tc_get_bal_of_call (symbolP);
3076           if (S_IS_EXTERNAL (symbolP) != S_IS_EXTERNAL (balP))
3077             {
3078               S_SET_EXTERNAL (symbolP);
3079               S_SET_EXTERNAL (balP);
3080               as_warn (_("Warning: making leafproc entries %s and %s both global\n"),
3081                        S_GET_NAME (symbolP), S_GET_NAME (balP));
3082             }                   /* externality mismatch */
3083         }                       /* if callname */
3084     }                           /* walk the symbol chain */
3085 }
3086
3087 #endif /* ! BFD_ASSEMBLER */
3088
3089 /* For aout or bout, the bal immediately follows the call.
3090
3091    For coff, we cheat and store a pointer to the bal symbol in the
3092    second aux entry of the call.  */
3093
3094 #undef OBJ_ABOUT
3095 #ifdef OBJ_AOUT
3096 #define OBJ_ABOUT
3097 #endif
3098 #ifdef OBJ_BOUT
3099 #define OBJ_ABOUT
3100 #endif
3101
3102 void
3103 tc_set_bal_of_call (callP, balP)
3104      symbolS *callP ATTRIBUTE_UNUSED;
3105      symbolS *balP ATTRIBUTE_UNUSED;
3106 {
3107   know (TC_S_IS_CALLNAME (callP));
3108   know (TC_S_IS_BALNAME (balP));
3109
3110 #ifdef OBJ_COFF
3111
3112   callP->sy_tc = balP;
3113   S_SET_NUMBER_AUXILIARY (callP, 2);
3114
3115 #else /* ! OBJ_COFF */
3116 #ifdef OBJ_ABOUT
3117
3118   /* If the 'bal' entry doesn't immediately follow the 'call'
3119      * symbol, unlink it from the symbol list and re-insert it.
3120    */
3121   if (symbol_next (callP) != balP)
3122     {
3123       symbol_remove (balP, &symbol_rootP, &symbol_lastP);
3124       symbol_append (balP, callP, &symbol_rootP, &symbol_lastP);
3125     }                           /* if not in order */
3126
3127 #else /* ! OBJ_ABOUT */
3128   as_fatal ("Only supported for a.out, b.out, or COFF");
3129 #endif /* ! OBJ_ABOUT */
3130 #endif /* ! OBJ_COFF */
3131 }
3132
3133 symbolS *
3134 tc_get_bal_of_call (callP)
3135      symbolS *callP ATTRIBUTE_UNUSED;
3136 {
3137   symbolS *retval;
3138
3139   know (TC_S_IS_CALLNAME (callP));
3140
3141 #ifdef OBJ_COFF
3142   retval = callP->sy_tc;
3143 #else
3144 #ifdef OBJ_ABOUT
3145   retval = symbol_next (callP);
3146 #else
3147   as_fatal ("Only supported for a.out, b.out, or COFF");
3148 #endif /* ! OBJ_ABOUT */
3149 #endif /* ! OBJ_COFF */
3150
3151   know (TC_S_IS_BALNAME (retval));
3152   return retval;
3153 }                               /* _tc_get_bal_of_call() */
3154
3155 #ifdef OBJ_COFF
3156 void
3157 tc_coff_symbol_emit_hook (symbolP)
3158      symbolS *symbolP ATTRIBUTE_UNUSED;
3159 {
3160   if (TC_S_IS_CALLNAME (symbolP))
3161     {
3162       symbolS *balP = tc_get_bal_of_call (symbolP);
3163
3164 #if 0
3165       /* second aux entry contains the bal entry point */
3166       S_SET_NUMBER_AUXILIARY (symbolP, 2);
3167 #endif
3168       symbolP->sy_symbol.ost_auxent[1].x_bal.x_balntry = S_GET_VALUE (balP);
3169       if (S_GET_STORAGE_CLASS (symbolP) == C_EXT)
3170         S_SET_STORAGE_CLASS (symbolP, C_LEAFEXT);
3171       else
3172         S_SET_STORAGE_CLASS (symbolP, C_LEAFSTAT);
3173       S_SET_DATA_TYPE (symbolP, S_GET_DATA_TYPE (symbolP) | (DT_FCN << N_BTSHFT));
3174       /* fix up the bal symbol */
3175       S_SET_STORAGE_CLASS (balP, C_LABEL);
3176     }                           /* only on calls */
3177 }
3178 #endif /* OBJ_COFF */
3179
3180 void
3181 i960_handle_align (fragp)
3182      fragS *fragp ATTRIBUTE_UNUSED;
3183 {
3184   if (!linkrelax)
3185     return;
3186
3187 #ifndef OBJ_BOUT
3188
3189   as_bad (_("option --link-relax is only supported in b.out format"));
3190   linkrelax = 0;
3191   return;
3192
3193 #else
3194
3195   /* The text section "ends" with another alignment reloc, to which we
3196      aren't adding padding.  */
3197   if (fragp->fr_next == text_last_frag
3198       || fragp->fr_next == data_last_frag)
3199     return;
3200
3201   /* alignment directive */
3202   fix_new (fragp, fragp->fr_fix, fragp->fr_offset, 0, 0, 0,
3203            (int) fragp->fr_type);
3204 #endif /* OBJ_BOUT */
3205 }
3206
3207 int
3208 i960_validate_fix (fixP, this_segment_type)
3209      fixS *fixP;
3210      segT this_segment_type ATTRIBUTE_UNUSED;
3211 {
3212   if (fixP->fx_tcbit && TC_S_IS_CALLNAME (fixP->fx_addsy))
3213     {
3214       /* Relocation should be done via the associated 'bal'
3215          entry point symbol.  */
3216
3217       if (!TC_S_IS_BALNAME (tc_get_bal_of_call (fixP->fx_addsy)))
3218         {
3219           as_bad_where (fixP->fx_file, fixP->fx_line,
3220                         _("No 'bal' entry point for leafproc %s"),
3221                         S_GET_NAME (fixP->fx_addsy));
3222           return 0;
3223         }
3224       fixP->fx_addsy = tc_get_bal_of_call (fixP->fx_addsy);
3225     }
3226
3227   return 1;
3228 }
3229
3230 #ifdef BFD_ASSEMBLER
3231
3232 /* From cgen.c:  */
3233
3234 static short tc_bfd_fix2rtype PARAMS ((fixS *));
3235
3236 static short
3237 tc_bfd_fix2rtype (fixP)
3238      fixS *fixP;
3239 {
3240 #if 0
3241   if (fixP->fx_bsr)
3242     abort ();
3243 #endif
3244
3245   if (fixP->fx_pcrel == 0 && fixP->fx_size == 4)
3246     return BFD_RELOC_32;
3247
3248   if (fixP->fx_pcrel != 0 && fixP->fx_size == 4)
3249     return BFD_RELOC_24_PCREL;
3250
3251   abort ();
3252   return 0;
3253 }
3254
3255 /* Translate internal representation of relocation info to BFD target
3256    format.
3257
3258    FIXME: To what extent can we get all relevant targets to use this?  */
3259
3260 arelent *
3261 tc_gen_reloc (section, fixP)
3262      asection *section ATTRIBUTE_UNUSED;
3263      fixS *fixP;
3264 {
3265   arelent * reloc;
3266
3267   reloc = (arelent *) xmalloc (sizeof (arelent));
3268
3269   /* HACK: Is this right? */
3270   fixP->fx_r_type = tc_bfd_fix2rtype (fixP);
3271
3272   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
3273   if (reloc->howto == (reloc_howto_type *) NULL)
3274     {
3275       as_bad_where (fixP->fx_file, fixP->fx_line,
3276                     "internal error: can't export reloc type %d (`%s')",
3277                     fixP->fx_r_type,
3278                     bfd_get_reloc_code_name (fixP->fx_r_type));
3279       return NULL;
3280     }
3281
3282   assert (!fixP->fx_pcrel == !reloc->howto->pc_relative);
3283
3284   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
3285   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
3286   reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
3287   reloc->addend = fixP->fx_addnumber;
3288
3289   return reloc;
3290 }
3291
3292 /* end from cgen.c */
3293
3294 #endif /* BFD_ASSEMBLER */
3295
3296 /* end of tc-i960.c */