x86: correct "-Q" option handling
[external/binutils.git] / gas / config / tc-tic6x.c
1 /* TI C6X assembler.
2    Copyright (C) 2010-2019 Free Software Foundation, Inc.
3    Contributed by Joseph Myers <joseph@codesourcery.com>
4                   Bernd Schmidt  <bernds@codesourcery.com>
5
6    This file is part of GAS, the GNU Assembler.
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 3, 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, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 #include "as.h"
24 #include "dwarf2dbg.h"
25 #include "dw2gencfi.h"
26 #include "safe-ctype.h"
27 #include "subsegs.h"
28 #include "opcode/tic6x.h"
29 #include "elf/tic6x.h"
30 #include "elf32-tic6x.h"
31
32 /* Truncate and sign-extend at 32 bits, so that building on a 64-bit
33    host gives identical results to a 32-bit host.  */
34 #define TRUNC(X)        ((valueT) (X) & 0xffffffffU)
35 #define SEXT(X)         ((TRUNC (X) ^ 0x80000000U) - 0x80000000U)
36
37 #define streq(a, b)           (strcmp (a, b) == 0)
38
39 /* Stuff for .scomm symbols.  */
40 static segT sbss_section;
41 static asection scom_section;
42 static asymbol scom_symbol;
43
44 const char comment_chars[] = ";";
45 const char line_comment_chars[] = "#*;";
46 const char line_separator_chars[] = "@";
47
48 const char EXP_CHARS[] = "eE";
49 const char FLT_CHARS[] = "dDfF";
50
51 const char *md_shortopts = "";
52
53 enum
54   {
55     OPTION_MARCH = OPTION_MD_BASE,
56     OPTION_MBIG_ENDIAN,
57     OPTION_MLITTLE_ENDIAN,
58     OPTION_MDSBT,
59     OPTION_MNO_DSBT,
60     OPTION_MPID,
61     OPTION_MPIC,
62     OPTION_MNO_PIC,
63     OPTION_MGENERATE_REL
64   };
65
66 struct option md_longopts[] =
67   {
68     { "march", required_argument, NULL, OPTION_MARCH },
69     { "mbig-endian", no_argument, NULL, OPTION_MBIG_ENDIAN },
70     { "mlittle-endian", no_argument, NULL, OPTION_MLITTLE_ENDIAN },
71     { "mdsbt", no_argument, NULL, OPTION_MDSBT },
72     { "mno-dsbt", no_argument, NULL, OPTION_MNO_DSBT },
73     { "mpid", required_argument, NULL, OPTION_MPID },
74     { "mpic", no_argument, NULL, OPTION_MPIC },
75     { "mno-pic", no_argument, NULL, OPTION_MNO_PIC },
76     { "mgenerate-rel", no_argument, NULL, OPTION_MGENERATE_REL },
77     { NULL, no_argument, NULL, 0 }
78   };
79 size_t md_longopts_size = sizeof (md_longopts);
80
81 /* The instructions enabled based only on the selected architecture
82    (all instructions, if no architecture specified).  */
83 static unsigned short tic6x_arch_enable = (TIC6X_INSN_C62X
84                                            | TIC6X_INSN_C64X
85                                            | TIC6X_INSN_C64XP
86                                            | TIC6X_INSN_C67X
87                                            | TIC6X_INSN_C67XP
88                                            | TIC6X_INSN_C674X);
89
90 /* The instructions enabled based on the current set of features
91    (architecture, as modified by other options).  */
92 static unsigned short tic6x_features;
93
94 /* The architecture attribute value, or C6XABI_Tag_ISA_none if
95    not yet set.  */
96 static int tic6x_arch_attribute = C6XABI_Tag_ISA_none;
97
98 /* Whether any instructions at all have been seen.  Once any
99    instructions have been seen, architecture attributes merge into the
100    previous attribute value rather than replacing it.  */
101 static bfd_boolean tic6x_seen_insns = FALSE;
102
103 /* The number of registers in each register file supported by the
104    current architecture.  */
105 static unsigned int tic6x_num_registers;
106
107 /* Whether predication on A0 is possible.  */
108 static bfd_boolean tic6x_predicate_a0;
109
110 /* Whether execute packets can cross fetch packet boundaries.  */
111 static bfd_boolean tic6x_can_cross_fp_boundary;
112
113 /* Whether there are constraints on simultaneous reads and writes of
114    40-bit data.  */
115 static bfd_boolean tic6x_long_data_constraints;
116
117 /* Whether compact instructions are available.  */
118 static bfd_boolean tic6x_compact_insns;
119
120 /* Whether to generate RELA relocations.  */
121 static bfd_boolean tic6x_generate_rela = TRUE;
122
123 /* Whether the code uses DSBT addressing.  */
124 static bfd_boolean tic6x_dsbt;
125
126 /* Types of position-independent data (attribute values for
127    Tag_ABI_PID).  */
128 typedef enum
129   {
130     tic6x_pid_no = 0,
131     tic6x_pid_near = 1,
132     tic6x_pid_far = 2
133   } tic6x_pid_type;
134
135 /* The type of data addressing used in this code.  */
136 static tic6x_pid_type tic6x_pid;
137
138 /* Whether the code uses position-independent code.  */
139 static bfd_boolean tic6x_pic;
140
141 /* Table of supported architecture variants.  */
142 typedef struct
143 {
144   const char *arch;
145   int attr;
146   unsigned short features;
147 } tic6x_arch_table;
148 static const tic6x_arch_table tic6x_arches[] =
149   {
150     { "c62x", C6XABI_Tag_ISA_C62X, TIC6X_INSN_C62X },
151     { "c64x", C6XABI_Tag_ISA_C64X, TIC6X_INSN_C62X | TIC6X_INSN_C64X },
152     { "c64x+", C6XABI_Tag_ISA_C64XP, (TIC6X_INSN_C62X
153                                       | TIC6X_INSN_C64X
154                                       | TIC6X_INSN_C64XP) },
155     { "c67x", C6XABI_Tag_ISA_C67X, TIC6X_INSN_C62X | TIC6X_INSN_C67X },
156     { "c67x+", C6XABI_Tag_ISA_C67XP, (TIC6X_INSN_C62X
157                                       | TIC6X_INSN_C67X
158                                       | TIC6X_INSN_C67XP) },
159     { "c674x", C6XABI_Tag_ISA_C674X, (TIC6X_INSN_C62X
160                                       | TIC6X_INSN_C64X
161                                       | TIC6X_INSN_C64XP
162                                       | TIC6X_INSN_C67X
163                                       | TIC6X_INSN_C67XP
164                                       | TIC6X_INSN_C674X) }
165   };
166
167 /* Caller saved register encodings.  The standard frame layout uses this
168    order, starting from the highest address.  There must be
169    TIC6X_NUM_UNWIND_REGS values.  */
170 enum
171 {
172   UNWIND_A15,
173   UNWIND_B15,
174   UNWIND_B14,
175   UNWIND_B13,
176   UNWIND_B12,
177   UNWIND_B11,
178   UNWIND_B10,
179   UNWIND_B3,
180   UNWIND_A14,
181   UNWIND_A13,
182   UNWIND_A12,
183   UNWIND_A11,
184   UNWIND_A10
185 };
186
187 static void tic6x_output_unwinding (bfd_boolean need_extab);
188
189 /* Return the frame unwind state for the current function, allocating
190    as necessary.  */
191
192 static tic6x_unwind_info *tic6x_get_unwind (void)
193 {
194   tic6x_unwind_info *unwind;
195
196   unwind = seg_info (now_seg)->tc_segment_info_data.unwind;
197   if (unwind)
198     return unwind;
199
200   unwind = seg_info (now_seg)->tc_segment_info_data.text_unwind;
201   if (unwind)
202     return unwind;
203
204   unwind =XNEW (tic6x_unwind_info);
205   seg_info (now_seg)->tc_segment_info_data.unwind = unwind;
206   memset (unwind, 0, sizeof (*unwind));
207   return unwind;
208 }
209
210 /* Update the selected architecture based on ARCH, giving an error if
211    ARCH is an invalid value.  Does not call tic6x_update_features; the
212    caller must do that if necessary.  */
213
214 static void
215 tic6x_use_arch (const char *arch)
216 {
217   unsigned int i;
218
219   for (i = 0; i < ARRAY_SIZE (tic6x_arches); i++)
220     if (strcmp (arch, tic6x_arches[i].arch) == 0)
221       {
222         tic6x_arch_enable = tic6x_arches[i].features;
223         if (tic6x_seen_insns)
224           tic6x_arch_attribute
225             = elf32_tic6x_merge_arch_attributes (tic6x_arch_attribute,
226                                                  tic6x_arches[i].attr);
227         else
228           tic6x_arch_attribute = tic6x_arches[i].attr;
229         return;
230       }
231
232   as_bad (_("unknown architecture '%s'"), arch);
233 }
234
235 /* Table of supported -mpid arguments.  */
236 typedef struct
237 {
238   const char *arg;
239   tic6x_pid_type attr;
240 } tic6x_pid_type_table;
241 static const tic6x_pid_type_table tic6x_pid_types[] =
242   {
243     { "no", tic6x_pid_no },
244     { "near", tic6x_pid_near },
245     { "far", tic6x_pid_far }
246   };
247
248 /* Handle -mpid=ARG.  */
249
250 static void
251 tic6x_use_pid (const char *arg)
252 {
253   unsigned int i;
254
255   for (i = 0; i < ARRAY_SIZE (tic6x_pid_types); i++)
256     if (strcmp (arg, tic6x_pid_types[i].arg) == 0)
257       {
258         tic6x_pid = tic6x_pid_types[i].attr;
259         return;
260       }
261
262   as_bad (_("unknown -mpid= argument '%s'"), arg);
263 }
264
265 /* Parse a target-specific option.  */
266
267 int
268 md_parse_option (int c, const char *arg)
269 {
270   switch (c)
271     {
272     case OPTION_MARCH:
273       tic6x_use_arch (arg);
274       break;
275
276     case OPTION_MBIG_ENDIAN:
277       target_big_endian = 1;
278       break;
279
280     case OPTION_MLITTLE_ENDIAN:
281       target_big_endian = 0;
282       break;
283
284     case OPTION_MDSBT:
285       tic6x_dsbt = 1;
286       break;
287
288     case OPTION_MNO_DSBT:
289       tic6x_dsbt = 0;
290       break;
291
292     case OPTION_MPID:
293       tic6x_use_pid (arg);
294       break;
295
296     case OPTION_MPIC:
297       tic6x_pic = 1;
298       break;
299
300     case OPTION_MNO_PIC:
301       tic6x_pic = 0;
302       break;
303
304     case OPTION_MGENERATE_REL:
305       tic6x_generate_rela = FALSE;
306       break;
307
308     default:
309       return 0;
310     }
311   return 1;
312 }
313
314 void
315 md_show_usage (FILE *stream ATTRIBUTE_UNUSED)
316 {
317   unsigned int i;
318
319   fputc ('\n', stream);
320   fprintf (stream, _("TMS320C6000 options:\n"));
321   fprintf (stream, _("  -march=ARCH             enable instructions from architecture ARCH\n"));
322   fprintf (stream, _("  -mbig-endian            generate big-endian code\n"));
323   fprintf (stream, _("  -mlittle-endian         generate little-endian code\n"));
324   fprintf (stream, _("  -mdsbt                  code uses DSBT addressing\n"));
325   fprintf (stream, _("  -mno-dsbt               code does not use DSBT addressing\n"));
326   fprintf (stream, _("  -mpid=no                code uses position-dependent data addressing\n"));
327   fprintf (stream, _("  -mpid=near              code uses position-independent data addressing,\n"
328                      "                            GOT accesses use near DP addressing\n"));
329   fprintf (stream, _("  -mpid=far               code uses position-independent data addressing,\n"
330                      "                            GOT accesses use far DP addressing\n"));
331   fprintf (stream, _("  -mpic                   code addressing is position-independent\n"));
332   fprintf (stream, _("  -mno-pic                code addressing is position-dependent\n"));
333   /* -mgenerate-rel is only for testsuite use and is deliberately
334       undocumented.  */
335
336   fputc ('\n', stream);
337   fprintf (stream, _("Supported ARCH values are:"));
338   for (i = 0; i < ARRAY_SIZE (tic6x_arches); i++)
339     fprintf (stream, " %s", tic6x_arches[i].arch);
340   fputc ('\n', stream);
341 }
342
343 /* Update enabled features based on the current architecture and
344    related settings.  */
345 static void
346 tic6x_update_features (void)
347 {
348   tic6x_features = tic6x_arch_enable;
349
350   tic6x_num_registers
351     = (tic6x_arch_enable & (TIC6X_INSN_C64X | TIC6X_INSN_C67XP)) ? 32 : 16;
352
353   tic6x_predicate_a0 = (tic6x_arch_enable & TIC6X_INSN_C64X) ? TRUE : FALSE;
354
355   tic6x_can_cross_fp_boundary
356     = (tic6x_arch_enable
357        & (TIC6X_INSN_C64X | TIC6X_INSN_C67XP)) ? TRUE : FALSE;
358
359   tic6x_long_data_constraints
360     = (tic6x_arch_enable & TIC6X_INSN_C64X) ? FALSE : TRUE;
361
362   tic6x_compact_insns = (tic6x_arch_enable & TIC6X_INSN_C64XP) ? TRUE : FALSE;
363 }
364
365 /* Do configuration after all options have been parsed.  */
366
367 void
368 tic6x_after_parse_args (void)
369 {
370   tic6x_update_features ();
371 }
372
373 /* Parse a .cantunwind directive.  */
374 static void
375 s_tic6x_cantunwind (int ignored ATTRIBUTE_UNUSED)
376 {
377   tic6x_unwind_info *unwind = tic6x_get_unwind ();
378
379   /* GCC sometimes spits out superfluous .cantunwind directives, so ignore
380      them.  */
381   if (unwind->data_bytes == 0)
382     return;
383
384   if (unwind->data_bytes != -1)
385     {
386       as_bad (_("unexpected .cantunwind directive"));
387       return;
388     }
389
390   demand_empty_rest_of_line ();
391
392   if (unwind->personality_routine || unwind->personality_index != -1)
393     as_bad (_("personality routine specified for cantunwind frame"));
394
395   unwind->personality_index = -2;
396 }
397
398 /* Parse a .handlerdata directive.  */
399 static void
400 s_tic6x_handlerdata (int ignored ATTRIBUTE_UNUSED)
401 {
402   tic6x_unwind_info *unwind = tic6x_get_unwind ();
403
404   if (!unwind->saved_seg)
405     {
406       as_bad (_("unexpected .handlerdata directive"));
407       return;
408     }
409
410   if (unwind->table_entry || unwind->personality_index == -2)
411     {
412       as_bad (_("duplicate .handlerdata directive"));
413       return;
414     }
415
416   if (unwind->personality_index == -1 && unwind->personality_routine == NULL)
417     {
418       as_bad (_("personality routine required before .handlerdata directive"));
419       return;
420     }
421
422   tic6x_output_unwinding (TRUE);
423 }
424
425 /* Parse a .endp directive.  */
426 static void
427 s_tic6x_endp (int ignored ATTRIBUTE_UNUSED)
428 {
429   tic6x_unwind_info *unwind = tic6x_get_unwind ();
430
431   if (unwind->data_bytes != 0)
432     {
433       /* Output a .exidx entry if we have not already done so.
434          Then switch back to the text section.  */
435       if (!unwind->table_entry)
436         tic6x_output_unwinding (FALSE);
437
438       subseg_set (unwind->saved_seg, unwind->saved_subseg);
439     }
440
441   unwind->saved_seg = NULL;
442   unwind->table_entry = NULL;
443   unwind->data_bytes = 0;
444 }
445
446 /* Parse a .personalityindex directive.  */
447 static void
448 s_tic6x_personalityindex (int ignored ATTRIBUTE_UNUSED)
449 {
450   tic6x_unwind_info *unwind = tic6x_get_unwind ();
451   expressionS exp;
452
453   if (unwind->personality_routine || unwind->personality_index != -1)
454     as_bad (_("duplicate .personalityindex directive"));
455
456   expression (&exp);
457
458   if (exp.X_op != O_constant
459       || exp.X_add_number < 0 || exp.X_add_number > 15)
460     {
461       as_bad (_("bad personality routine number"));
462       ignore_rest_of_line ();
463       return;
464     }
465
466   unwind->personality_index = exp.X_add_number;
467
468   demand_empty_rest_of_line ();
469 }
470
471 static void
472 s_tic6x_personality (int ignored ATTRIBUTE_UNUSED)
473 {
474   char *name, c;
475   tic6x_unwind_info *unwind = tic6x_get_unwind ();
476
477   if (unwind->personality_routine || unwind->personality_index != -1)
478     as_bad (_("duplicate .personality directive"));
479
480   c = get_symbol_name (&name);
481   unwind->personality_routine = symbol_find_or_make (name);
482   (void) restore_line_pointer (c);
483   demand_empty_rest_of_line ();
484 }
485
486 /* Parse a .arch directive.  */
487 static void
488 s_tic6x_arch (int ignored ATTRIBUTE_UNUSED)
489 {
490   char c;
491   char *arch;
492
493   arch = input_line_pointer;
494   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
495     input_line_pointer++;
496   c = *input_line_pointer;
497   *input_line_pointer = 0;
498
499   tic6x_use_arch (arch);
500   tic6x_update_features ();
501   *input_line_pointer = c;
502   demand_empty_rest_of_line ();
503 }
504
505 /* Parse a .ehtype directive.  */
506
507 static void
508 s_tic6x_ehtype (int ignored ATTRIBUTE_UNUSED)
509 {
510   expressionS exp;
511   char *p;
512
513 #ifdef md_flush_pending_output
514   md_flush_pending_output ();
515 #endif
516
517   if (is_it_end_of_statement ())
518     {
519       demand_empty_rest_of_line ();
520       return;
521     }
522
523 #ifdef md_cons_align
524   md_cons_align (4);
525 #endif
526
527
528   expression (&exp);
529
530   if (exp.X_op != O_symbol)
531     {
532       as_bad (_("expected symbol"));
533       return;
534     }
535
536   p = frag_more (4);
537   memset (p, 0, 4);
538   fix_new_exp (frag_now, p - frag_now->fr_literal, 4,
539                &exp, 0, BFD_RELOC_C6000_EHTYPE);
540
541   demand_empty_rest_of_line ();
542 }
543
544 /* Parse a .nocmp directive.  */
545
546 static void
547 s_tic6x_nocmp (int ignored ATTRIBUTE_UNUSED)
548 {
549   seg_info (now_seg)->tc_segment_info_data.nocmp = TRUE;
550   demand_empty_rest_of_line ();
551 }
552
553 /* .scomm pseudo-op handler.
554
555    This is a new pseudo-op to handle putting objects in .scommon.
556    By doing this the linker won't need to do any work,
557    and more importantly it removes the implicit -G arg necessary to
558    correctly link the object file.  */
559
560 static void
561 s_tic6x_scomm (int ignore ATTRIBUTE_UNUSED)
562 {
563   char *name;
564   char c;
565   char *p;
566   offsetT size;
567   symbolS *symbolP;
568   offsetT align;
569   int align2;
570
571   c = get_symbol_name (&name);
572
573   /* Just after name is now '\0'.  */
574   p = input_line_pointer;
575   (void) restore_line_pointer (c);
576   SKIP_WHITESPACE ();
577   if (*input_line_pointer != ',')
578     {
579       as_bad (_("expected comma after symbol name"));
580       ignore_rest_of_line ();
581       return;
582     }
583
584   /* Skip ','.  */
585   input_line_pointer++;
586   if ((size = get_absolute_expression ()) < 0)
587     {
588       /* xgettext:c-format  */
589       as_warn (_("invalid length for .scomm directive"));
590       ignore_rest_of_line ();
591       return;
592     }
593
594   /* The third argument to .scomm is the alignment.  */
595   if (*input_line_pointer != ',')
596     align = 8;
597   else
598     {
599       ++input_line_pointer;
600       align = get_absolute_expression ();
601       if (align <= 0)
602         {
603           as_warn (_("alignment is not a positive number"));
604           align = 8;
605         }
606     }
607
608   /* Convert to a power of 2 alignment.  */
609   if (align)
610     {
611       for (align2 = 0; (align & 1) == 0; align >>= 1, ++align2)
612         continue;
613       if (align != 1)
614         {
615           as_bad (_("alignment is not a power of 2"));
616           ignore_rest_of_line ();
617           return;
618         }
619     }
620   else
621     align2 = 0;
622
623   *p = 0;
624   symbolP = symbol_find_or_make (name);
625   *p = c;
626
627   if (S_IS_DEFINED (symbolP))
628     {
629       /* xgettext:c-format  */
630       as_bad (_("attempt to re-define symbol `%s'"),
631               S_GET_NAME (symbolP));
632       ignore_rest_of_line ();
633       return;
634     }
635
636   if (S_GET_VALUE (symbolP) && S_GET_VALUE (symbolP) != (valueT) size)
637     {
638       /* xgettext:c-format  */
639       as_bad (_("attempt to redefine `%s' with a different length"),
640               S_GET_NAME (symbolP));
641
642       ignore_rest_of_line ();
643       return;
644     }
645
646   if (symbol_get_obj (symbolP)->local)
647     {
648       segT old_sec = now_seg;
649       int old_subsec = now_subseg;
650       char *pfrag;
651
652       record_alignment (sbss_section, align2);
653       subseg_set (sbss_section, 0);
654
655       if (align2)
656         frag_align (align2, 0, 0);
657
658       if (S_GET_SEGMENT (symbolP) == sbss_section)
659         symbol_get_frag (symbolP)->fr_symbol = 0;
660
661       symbol_set_frag (symbolP, frag_now);
662
663       pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP, size,
664                         (char *) 0);
665       *pfrag = 0;
666       S_SET_SIZE (symbolP, size);
667       S_SET_SEGMENT (symbolP, sbss_section);
668       S_CLEAR_EXTERNAL (symbolP);
669       subseg_set (old_sec, old_subsec);
670     }
671   else
672     {
673       S_SET_VALUE (symbolP, (valueT) size);
674       S_SET_ALIGN (symbolP, 1 << align2);
675       S_SET_EXTERNAL (symbolP);
676       S_SET_SEGMENT (symbolP, &scom_section);
677     }
678
679   symbol_get_bfdsym (symbolP)->flags |= BSF_OBJECT;
680
681   demand_empty_rest_of_line ();
682 }
683
684 /* Track for each attribute whether it has been set explicitly (and so
685    should not have a default value set by the assembler).  */
686 static bfd_boolean tic6x_attributes_set_explicitly[NUM_KNOWN_OBJ_ATTRIBUTES];
687
688 /* Parse a .c6xabi_attribute directive.  */
689
690 static void
691 s_tic6x_c6xabi_attribute (int ignored ATTRIBUTE_UNUSED)
692 {
693   int tag = obj_elf_vendor_attribute (OBJ_ATTR_PROC);
694
695   if (tag < NUM_KNOWN_OBJ_ATTRIBUTES)
696     tic6x_attributes_set_explicitly[tag] = TRUE;
697 }
698
699 typedef struct
700 {
701   const char *name;
702   int tag;
703 } tic6x_attribute_table;
704
705 static const tic6x_attribute_table tic6x_attributes[] =
706   {
707 #define TAG(tag, value) { #tag, tag },
708 #include "elf/tic6x-attrs.h"
709 #undef TAG
710   };
711
712 /* Convert an attribute name to a number.  */
713
714 int
715 tic6x_convert_symbolic_attribute (const char *name)
716 {
717   unsigned int i;
718
719   for (i = 0; i < ARRAY_SIZE (tic6x_attributes); i++)
720     if (strcmp (name, tic6x_attributes[i].name) == 0)
721       return tic6x_attributes[i].tag;
722
723   return -1;
724 }
725
726 const pseudo_typeS md_pseudo_table[] =
727   {
728     { "arch", s_tic6x_arch, 0 },
729     { "c6xabi_attribute", s_tic6x_c6xabi_attribute, 0 },
730     { "nocmp", s_tic6x_nocmp, 0 },
731     { "scomm",  s_tic6x_scomm, 0 },
732     { "word", cons, 4 },
733     { "ehtype", s_tic6x_ehtype, 0 },
734     { "endp", s_tic6x_endp, 0 },
735     { "handlerdata", s_tic6x_handlerdata, 0 },
736     { "personalityindex", s_tic6x_personalityindex, 0 },
737     { "personality", s_tic6x_personality, 0 },
738     { "cantunwind", s_tic6x_cantunwind, 0 },
739     { 0, 0, 0 }
740   };
741
742 /* Hash table of opcodes.  For each opcode name, this stores a pointer
743    to a tic6x_opcode_list listing (in an arbitrary order) all opcode
744    table entries with that name.  */
745 static struct hash_control *opcode_hash;
746
747 /* Initialize the assembler (called once at assembler startup).  */
748
749 void
750 md_begin (void)
751 {
752   tic6x_opcode_id id;
753   flagword applicable;
754   segT seg;
755   subsegT subseg;
756
757   bfd_set_arch_mach (stdoutput, TARGET_ARCH, 0);
758
759   /* Insert opcodes into the hash table.  */
760   opcode_hash = hash_new ();
761   for (id = 0; id < tic6x_opcode_max; id++)
762     {
763       const char *errmsg;
764       tic6x_opcode_list *opc = XNEW (tic6x_opcode_list);
765
766       opc->id = id;
767       opc->next = hash_find (opcode_hash, tic6x_opcode_table[id].name);
768       if ((errmsg = hash_jam (opcode_hash, tic6x_opcode_table[id].name, opc))
769           != NULL)
770         as_fatal ("%s", _(errmsg));
771     }
772
773   /* Save the current subseg so we can restore it [it's the default one and
774      we don't want the initial section to be .sbss].  */
775   seg = now_seg;
776   subseg = now_subseg;
777
778   /* The sbss section is for local .scomm symbols.  */
779   sbss_section = subseg_new (".bss", 0);
780   seg_info (sbss_section)->bss = 1;
781
782   /* This is copied from perform_an_assembly_pass.  */
783   applicable = bfd_applicable_section_flags (stdoutput);
784   bfd_set_section_flags (stdoutput, sbss_section, applicable & SEC_ALLOC);
785
786   subseg_set (seg, subseg);
787
788   /* We must construct a fake section similar to bfd_com_section
789      but with the name .scommon.  */
790   scom_section                = *bfd_com_section_ptr;
791   scom_section.name           = ".scommon";
792   scom_section.output_section = & scom_section;
793   scom_section.symbol         = & scom_symbol;
794   scom_section.symbol_ptr_ptr = & scom_section.symbol;
795   scom_symbol                 = * bfd_com_section_ptr->symbol;
796   scom_symbol.name            = ".scommon";
797   scom_symbol.section         = & scom_section;
798 }
799
800 /* Whether the current line being parsed had the "||" parallel bars.  */
801 static bfd_boolean tic6x_line_parallel;
802
803 /* Whether the current line being parsed started "||^" to indicate an
804    SPMASKed parallel instruction.  */
805 static bfd_boolean tic6x_line_spmask;
806
807 /* If the current line being parsed had an instruction predicate, the
808    creg value for that predicate (which must be nonzero); otherwise
809    0.  */
810 static unsigned int tic6x_line_creg;
811
812 /* If the current line being parsed had an instruction predicate, the
813    z value for that predicate; otherwise 0.  */
814 static unsigned int tic6x_line_z;
815
816 /* Return 1 (updating input_line_pointer as appropriate) if the line
817    starting with C (immediately before input_line_pointer) starts with
818    pre-opcode text appropriate for this target, 0 otherwise.  */
819
820 int
821 tic6x_unrecognized_line (int c)
822 {
823   char *p, *endp;
824   unsigned int z;
825   bfd_boolean areg;
826   bfd_boolean bad_predicate;
827
828   switch (c)
829     {
830     case '|':
831       if (input_line_pointer[0] == '|')
832         {
833           if (input_line_pointer[1] == '^')
834             {
835               tic6x_line_spmask = TRUE;
836               input_line_pointer += 2;
837             }
838           else
839             input_line_pointer += 1;
840           if (tic6x_line_parallel)
841             as_bad (_("multiple '||' on same line"));
842           tic6x_line_parallel = TRUE;
843           if (tic6x_line_creg)
844             as_bad (_("'||' after predicate"));
845           return 1;
846         }
847       return 0;
848
849     case '[':
850       /* If it doesn't look like a predicate at all, just return 0.
851          If it looks like one but not a valid one, give a better
852          error.  */
853       p = input_line_pointer;
854       while (*p != ']' && !is_end_of_line[(unsigned char) *p])
855         p++;
856       if (*p != ']')
857         return 0;
858       endp = p + 1;
859       p = input_line_pointer;
860       z = 0;
861       bad_predicate = FALSE;
862       if (*p == '!')
863         {
864           z = 1;
865           p++;
866         }
867       if (*p == 'A' || *p == 'a')
868         areg = TRUE;
869       else if (*p == 'B' || *p == 'b')
870         areg = FALSE;
871       else
872         {
873           areg = TRUE; /* Avoid uninitialized warning.  */
874           bad_predicate = TRUE;
875         }
876       if (!bad_predicate)
877         {
878           p++;
879           if (*p != '0' && *p != '1' && *p != '2')
880             bad_predicate = TRUE;
881           else if (p[1] != ']')
882             bad_predicate = TRUE;
883           else
884             input_line_pointer = p + 2;
885         }
886
887       if (tic6x_line_creg)
888         as_bad (_("multiple predicates on same line"));
889
890       if (bad_predicate)
891         {
892           char ctmp = *endp;
893           *endp = 0;
894           as_bad (_("bad predicate '%s'"), input_line_pointer - 1);
895           *endp = ctmp;
896           input_line_pointer = endp;
897           return 1;
898         }
899
900       switch (*p)
901         {
902         case '0':
903           tic6x_line_creg = (areg ? 6 : 1);
904           if (areg && !tic6x_predicate_a0)
905             as_bad (_("predication on A0 not supported on this architecture"));
906           break;
907
908         case '1':
909           tic6x_line_creg = (areg ? 4 : 2);
910           break;
911
912         case '2':
913           tic6x_line_creg = (areg ? 5 : 3);
914           break;
915
916         default:
917           abort ();
918         }
919
920       tic6x_line_z = z;
921       return 1;
922
923     default:
924       return 0;
925     }
926 }
927
928 /* Do any target-specific handling of a label required.  */
929
930 void
931 tic6x_frob_label (symbolS *sym)
932 {
933   segment_info_type *si;
934   tic6x_label_list *list;
935
936   if (tic6x_line_parallel)
937     {
938       as_bad (_("label after '||'"));
939       tic6x_line_parallel = FALSE;
940       tic6x_line_spmask = FALSE;
941     }
942   if (tic6x_line_creg)
943     {
944       as_bad (_("label after predicate"));
945       tic6x_line_creg = 0;
946       tic6x_line_z = 0;
947     }
948
949   si = seg_info (now_seg);
950   list = si->tc_segment_info_data.label_list;
951   si->tc_segment_info_data.label_list = XNEW (tic6x_label_list);
952   si->tc_segment_info_data.label_list->next = list;
953   si->tc_segment_info_data.label_list->label = sym;
954
955   /* Defining tc_frob_label overrides the ELF definition of
956      obj_frob_label, so we need to apply its effects here.  */
957   dwarf2_emit_label (sym);
958 }
959
960 /* At end-of-line, give errors for start-of-line decorations that
961    needed an instruction but were not followed by one.  */
962
963 static void
964 tic6x_end_of_line (void)
965 {
966   if (tic6x_line_parallel)
967     {
968       as_bad (_("'||' not followed by instruction"));
969       tic6x_line_parallel = FALSE;
970       tic6x_line_spmask = FALSE;
971     }
972   if (tic6x_line_creg)
973     {
974       as_bad (_("predicate not followed by instruction"));
975       tic6x_line_creg = 0;
976       tic6x_line_z = 0;
977     }
978 }
979
980 /* Do any target-specific handling of the start of a logical line.  */
981
982 void
983 tic6x_start_line_hook (void)
984 {
985   tic6x_end_of_line ();
986 }
987
988 /* Do target-specific handling immediately after an input file from
989    the command line, and any other inputs it includes, have been
990    read.  */
991
992 void
993 tic6x_cleanup (void)
994 {
995   tic6x_end_of_line ();
996 }
997
998 /* Do target-specific initialization after arguments have been
999    processed and the output file created.  */
1000
1001 void
1002 tic6x_init_after_args (void)
1003 {
1004   elf32_tic6x_set_use_rela_p (stdoutput, tic6x_generate_rela);
1005 }
1006
1007 /* Free LIST of labels (possibly NULL).  */
1008
1009 static void
1010 tic6x_free_label_list (tic6x_label_list *list)
1011 {
1012   while (list)
1013     {
1014       tic6x_label_list *old = list;
1015
1016       list = list->next;
1017       free (old);
1018     }
1019 }
1020
1021 /* Handle a data alignment of N bytes.  */
1022
1023 void
1024 tic6x_cons_align (int n ATTRIBUTE_UNUSED)
1025 {
1026   segment_info_type *seginfo = seg_info (now_seg);
1027
1028   /* Data means there is no current execute packet, and that any label
1029      applies to that data rather than a subsequent instruction.  */
1030   tic6x_free_label_list (seginfo->tc_segment_info_data.label_list);
1031   seginfo->tc_segment_info_data.label_list = NULL;
1032   seginfo->tc_segment_info_data.execute_packet_frag = NULL;
1033   seginfo->tc_segment_info_data.last_insn_lsb = NULL;
1034   seginfo->tc_segment_info_data.spmask_addr = NULL;
1035   seginfo->tc_segment_info_data.func_units_used = 0;
1036 }
1037
1038 /* Handle an alignment directive.  Return TRUE if the
1039    machine-independent frag generation should be skipped.  */
1040
1041 bfd_boolean
1042 tic6x_do_align (int n, char *fill, int len ATTRIBUTE_UNUSED, int max)
1043 {
1044   /* Given code alignments of 4, 8, 16 or 32 bytes, we try to handle
1045      them in the md_end pass by inserting NOPs in parallel with
1046      previous instructions.  We only do this in sections containing
1047      nothing but instructions.  Code alignments of 1 or 2 bytes have
1048      no effect in such sections (but we record them with
1049      machine-dependent frags anyway so they can be skipped or
1050      converted to machine-independent), while those of more than 64
1051      bytes cannot reliably be handled in this way.  */
1052   if (n > 0
1053       && max >= 0
1054       && max < (1 << n)
1055       && !need_pass_2
1056       && fill == NULL
1057       && subseg_text_p (now_seg))
1058     {
1059       fragS *align_frag;
1060       char *p;
1061
1062       if (n > 5)
1063         return FALSE;
1064
1065       /* Machine-independent code would generate a frag here, but we
1066          wish to handle it in a machine-dependent way.  */
1067       if (frag_now_fix () != 0)
1068         {
1069           if (frag_now->fr_type != rs_machine_dependent)
1070             frag_wane (frag_now);
1071
1072           frag_new (0);
1073         }
1074       frag_grow (32);
1075       align_frag = frag_now;
1076       p = frag_var (rs_machine_dependent, 32, 32, max, NULL, n, NULL);
1077       /* This must be the same as the frag to which a pointer was just
1078          saved.  */
1079       if (p != align_frag->fr_literal)
1080         abort ();
1081       align_frag->tc_frag_data.is_insns = FALSE;
1082       return TRUE;
1083     }
1084   else
1085     return FALSE;
1086 }
1087
1088 /* Types of operand for parsing purposes.  These are used as bit-masks
1089    to tell tic6x_parse_operand what forms of operand are
1090    permitted.  */
1091 #define TIC6X_OP_EXP            0x0001u
1092 #define TIC6X_OP_REG            0x0002u
1093 #define TIC6X_OP_REGPAIR        0x0004u
1094 #define TIC6X_OP_IRP            0x0008u
1095 #define TIC6X_OP_NRP            0x0010u
1096 /* With TIC6X_OP_MEM_NOUNREG, the contents of a () offset are always
1097    interpreted as an expression, which may be a symbol with the same
1098    name as a register that ends up being implicitly DP-relative.  With
1099    TIC6X_OP_MEM_UNREG, the contents of a () offset are interpreted as
1100    a register if they match one, and failing that as an expression,
1101    which must be constant.  */
1102 #define TIC6X_OP_MEM_NOUNREG    0x0020u
1103 #define TIC6X_OP_MEM_UNREG      0x0040u
1104 #define TIC6X_OP_CTRL           0x0080u
1105 #define TIC6X_OP_FUNC_UNIT      0x0100u
1106
1107 /* A register or register pair read by the assembler.  */
1108 typedef struct
1109 {
1110   /* The side the register is on (1 or 2).  */
1111   unsigned int side;
1112   /* The register number (0 to 31).  */
1113   unsigned int num;
1114 } tic6x_register;
1115
1116 /* Types of modification of a base address.  */
1117 typedef enum
1118   {
1119     tic6x_mem_mod_none,
1120     tic6x_mem_mod_plus,
1121     tic6x_mem_mod_minus,
1122     tic6x_mem_mod_preinc,
1123     tic6x_mem_mod_predec,
1124     tic6x_mem_mod_postinc,
1125     tic6x_mem_mod_postdec
1126   } tic6x_mem_mod;
1127
1128 /* Scaled [] or unscaled () nature of an offset.  */
1129 typedef enum
1130   {
1131     tic6x_offset_none,
1132     tic6x_offset_scaled,
1133     tic6x_offset_unscaled
1134   } tic6x_mem_scaling;
1135
1136 /* A memory operand read by the assembler.  */
1137 typedef struct
1138 {
1139   /* The base register.  */
1140   tic6x_register base_reg;
1141   /* How the base register is modified.  */
1142   tic6x_mem_mod mod;
1143   /* Whether there is an offset (required with plain "+" and "-"), and
1144      whether it is scaled or unscaled if so.  */
1145   tic6x_mem_scaling scaled;
1146   /* Whether the offset is a register (TRUE) or an expression
1147      (FALSE).  */
1148   bfd_boolean offset_is_reg;
1149   /* The offset.  */
1150   union
1151   {
1152     expressionS exp;
1153     tic6x_register reg;
1154   } offset;
1155 } tic6x_mem_ref;
1156
1157 /* A functional unit in SPMASK operands read by the assembler.  */
1158 typedef struct
1159 {
1160   /* The basic unit.  */
1161   tic6x_func_unit_base base;
1162   /* The side (1 or 2).  */
1163   unsigned int side;
1164 } tic6x_func_unit_operand;
1165
1166 /* An operand read by the assembler.  */
1167 typedef struct
1168 {
1169   /* The syntactic form of the operand, as one of the bit-masks
1170      above.  */
1171   unsigned int form;
1172   /* The operand value.  */
1173   union
1174   {
1175     /* An expression: TIC6X_OP_EXP.  */
1176     expressionS exp;
1177     /* A register: TIC6X_OP_REG, TIC6X_OP_REGPAIR.  */
1178     tic6x_register reg;
1179     /* A memory reference: TIC6X_OP_MEM_NOUNREG,
1180        TIC6X_OP_MEM_UNREG.  */
1181     tic6x_mem_ref mem;
1182     /* A control register: TIC6X_OP_CTRL.  */
1183     tic6x_ctrl_id ctrl;
1184     /* A functional unit: TIC6X_OP_FUNC_UNIT.  */
1185     tic6x_func_unit_operand func_unit;
1186   } value;
1187 } tic6x_operand;
1188
1189 #define skip_whitespace(str)  do { if (*(str) == ' ') ++(str); } while (0)
1190
1191 /* Parse a register operand, or part of an operand, starting at *P.
1192    If syntactically OK (including that the number is in the range 0 to
1193    31, but not necessarily in range for this architecture), return
1194    TRUE, putting the register side and number in *REG and update *P to
1195    point immediately after the register number; otherwise return FALSE
1196    without changing *P (but possibly changing *REG).  Do not print any
1197    diagnostics.  */
1198
1199 static bfd_boolean
1200 tic6x_parse_register (char **p, tic6x_register *reg)
1201 {
1202   char *r = *p;
1203
1204   switch (*r)
1205     {
1206     case 'a':
1207     case 'A':
1208       reg->side = 1;
1209       break;
1210
1211     case 'b':
1212     case 'B':
1213       reg->side = 2;
1214       break;
1215
1216     default:
1217       return FALSE;
1218     }
1219   r++;
1220
1221   if (*r >= '0' && *r <= '9')
1222     {
1223       reg->num = *r - '0';
1224       r++;
1225     }
1226   else
1227     return FALSE;
1228
1229   if (reg->num > 0 && *r >= '0' && *r <= '9')
1230     {
1231       reg->num = reg->num * 10 + (*r - '0');
1232       r++;
1233     }
1234
1235   if (*r >= '0' && *r <= '9')
1236     return FALSE;
1237
1238   if (reg->num >= 32)
1239     return FALSE;
1240   *p = r;
1241   return TRUE;
1242 }
1243
1244 /* Parse the initial two characters of a functional unit name starting
1245    at *P.  If OK, set *BASE and *SIDE and return TRUE; otherwise,
1246    return FALSE.  */
1247
1248 static bfd_boolean
1249 tic6x_parse_func_unit_base (char *p, tic6x_func_unit_base *base,
1250                             unsigned int *side)
1251 {
1252   bfd_boolean good_func_unit = TRUE;
1253   tic6x_func_unit_base maybe_base = tic6x_func_unit_nfu;
1254   unsigned int maybe_side = 0;
1255
1256   switch (p[0])
1257     {
1258     case 'd':
1259     case 'D':
1260       maybe_base = tic6x_func_unit_d;
1261       break;
1262
1263     case 'l':
1264     case 'L':
1265       maybe_base = tic6x_func_unit_l;
1266       break;
1267
1268     case 'm':
1269     case 'M':
1270       maybe_base = tic6x_func_unit_m;
1271       break;
1272
1273     case 's':
1274     case 'S':
1275       maybe_base = tic6x_func_unit_s;
1276       break;
1277
1278     default:
1279       good_func_unit = FALSE;
1280       break;
1281     }
1282
1283   if (good_func_unit)
1284     switch (p[1])
1285       {
1286       case '1':
1287         maybe_side = 1;
1288         break;
1289
1290       case '2':
1291         maybe_side = 2;
1292         break;
1293
1294       default:
1295         good_func_unit = FALSE;
1296         break;
1297       }
1298
1299   if (good_func_unit)
1300     {
1301       *base = maybe_base;
1302       *side = maybe_side;
1303     }
1304
1305   return good_func_unit;
1306 }
1307
1308 /* Parse an operand starting at *P.  If the operand parses OK, return
1309    TRUE and store the value in *OP; otherwise return FALSE (possibly
1310    changing *OP).  In any case, update *P to point to the following
1311    comma or end of line.  The possible operand forms are given by
1312    OP_FORMS.  For diagnostics, this is operand OPNO of an opcode
1313    starting at STR, length OPC_LEN.  */
1314
1315 static bfd_boolean
1316 tic6x_parse_operand (char **p, tic6x_operand *op, unsigned int op_forms,
1317                      char *str, int opc_len, unsigned int opno)
1318 {
1319   bfd_boolean operand_parsed = FALSE;
1320   char *q = *p;
1321
1322   if ((op_forms & (TIC6X_OP_MEM_NOUNREG | TIC6X_OP_MEM_UNREG))
1323       == (TIC6X_OP_MEM_NOUNREG | TIC6X_OP_MEM_UNREG))
1324     abort ();
1325
1326   /* Check for functional unit names for SPMASK and SPMASKR.  */
1327   if (!operand_parsed && (op_forms & TIC6X_OP_FUNC_UNIT))
1328     {
1329       tic6x_func_unit_base base = tic6x_func_unit_nfu;
1330       unsigned int side = 0;
1331
1332       if (tic6x_parse_func_unit_base (q, &base, &side))
1333         {
1334           char *rq = q + 2;
1335
1336           skip_whitespace (rq);
1337           if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1338             {
1339               op->form = TIC6X_OP_FUNC_UNIT;
1340               op->value.func_unit.base = base;
1341               op->value.func_unit.side = side;
1342               operand_parsed = TRUE;
1343               q = rq;
1344             }
1345         }
1346     }
1347
1348   /* Check for literal "irp".  */
1349   if (!operand_parsed && (op_forms & TIC6X_OP_IRP))
1350     {
1351       if ((q[0] == 'i' || q[0] == 'I')
1352           && (q[1] == 'r' || q[1] == 'R')
1353           && (q[2] == 'p' || q[2] == 'P'))
1354         {
1355           char *rq = q + 3;
1356
1357           skip_whitespace (rq);
1358           if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1359             {
1360               op->form = TIC6X_OP_IRP;
1361               operand_parsed = TRUE;
1362               q = rq;
1363             }
1364         }
1365     }
1366
1367   /* Check for literal "nrp".  */
1368   if (!operand_parsed && (op_forms & TIC6X_OP_NRP))
1369     {
1370       if ((q[0] == 'n' || q[0] == 'N')
1371           && (q[1] == 'r' || q[1] == 'R')
1372           && (q[2] == 'p' || q[2] == 'P'))
1373         {
1374           char *rq = q + 3;
1375
1376           skip_whitespace (rq);
1377           if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1378             {
1379               op->form = TIC6X_OP_NRP;
1380               operand_parsed = TRUE;
1381               q = rq;
1382             }
1383         }
1384     }
1385
1386   /* Check for control register names.  */
1387   if (!operand_parsed && (op_forms & TIC6X_OP_CTRL))
1388     {
1389       tic6x_ctrl_id crid;
1390
1391       for (crid = 0; crid < tic6x_ctrl_max; crid++)
1392         {
1393           size_t len = strlen (tic6x_ctrl_table[crid].name);
1394
1395           if (strncasecmp (tic6x_ctrl_table[crid].name, q, len) == 0)
1396             {
1397               char *rq = q + len;
1398
1399               skip_whitespace (rq);
1400               if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1401                 {
1402                   op->form = TIC6X_OP_CTRL;
1403                   op->value.ctrl = crid;
1404                   operand_parsed = TRUE;
1405                   q = rq;
1406                   if (!(tic6x_ctrl_table[crid].isa_variants & tic6x_features))
1407                     as_bad (_("control register '%s' not supported "
1408                               "on this architecture"),
1409                             tic6x_ctrl_table[crid].name);
1410                 }
1411             }
1412         }
1413     }
1414
1415   /* See if this looks like a memory reference.  */
1416   if (!operand_parsed
1417       && (op_forms & (TIC6X_OP_MEM_NOUNREG | TIC6X_OP_MEM_UNREG)))
1418     {
1419       bfd_boolean mem_ok = TRUE;
1420       char *mq = q;
1421       tic6x_mem_mod mem_mod = tic6x_mem_mod_none;
1422       tic6x_register base_reg;
1423       bfd_boolean require_offset, permit_offset;
1424       tic6x_mem_scaling scaled;
1425       bfd_boolean offset_is_reg;
1426       expressionS offset_exp;
1427       tic6x_register offset_reg;
1428
1429       if (*mq == '*')
1430         mq++;
1431       else
1432         mem_ok = FALSE;
1433
1434       if (mem_ok)
1435         {
1436           skip_whitespace (mq);
1437           switch (*mq)
1438             {
1439             case '+':
1440               if (mq[1] == '+')
1441                 {
1442                   mem_mod = tic6x_mem_mod_preinc;
1443                   mq += 2;
1444                 }
1445               else
1446                 {
1447                   mem_mod = tic6x_mem_mod_plus;
1448                   mq++;
1449                 }
1450               break;
1451
1452             case '-':
1453               if (mq[1] == '-')
1454                 {
1455                   mem_mod = tic6x_mem_mod_predec;
1456                   mq += 2;
1457                 }
1458               else
1459                 {
1460                   mem_mod = tic6x_mem_mod_minus;
1461                   mq++;
1462                 }
1463               break;
1464
1465             default:
1466               break;
1467             }
1468         }
1469
1470       if (mem_ok)
1471         {
1472           skip_whitespace (mq);
1473           mem_ok = tic6x_parse_register (&mq, &base_reg);
1474         }
1475
1476       if (mem_ok && mem_mod == tic6x_mem_mod_none)
1477         {
1478           skip_whitespace (mq);
1479           if (mq[0] == '+' && mq[1] == '+')
1480             {
1481               mem_mod = tic6x_mem_mod_postinc;
1482               mq += 2;
1483             }
1484           else if (mq[0] == '-' && mq[1] == '-')
1485             {
1486               mem_mod = tic6x_mem_mod_postdec;
1487               mq += 2;
1488             }
1489         }
1490
1491       if (mem_mod == tic6x_mem_mod_none)
1492         permit_offset = FALSE;
1493       else
1494         permit_offset = TRUE;
1495       if (mem_mod == tic6x_mem_mod_plus || mem_mod == tic6x_mem_mod_minus)
1496         require_offset = TRUE;
1497       else
1498         require_offset = FALSE;
1499       scaled = tic6x_offset_none;
1500       offset_is_reg = FALSE;
1501
1502       if (mem_ok && permit_offset)
1503         {
1504           char endc = 0;
1505
1506           skip_whitespace (mq);
1507           switch (*mq)
1508             {
1509             case '[':
1510               scaled = tic6x_offset_scaled;
1511               mq++;
1512               endc = ']';
1513               break;
1514
1515             case '(':
1516               scaled = tic6x_offset_unscaled;
1517               mq++;
1518               endc = ')';
1519               break;
1520
1521             default:
1522               break;
1523             }
1524           if (scaled != tic6x_offset_none)
1525             {
1526               skip_whitespace (mq);
1527               if (scaled == tic6x_offset_scaled
1528                   || (op_forms & TIC6X_OP_MEM_UNREG))
1529                 {
1530                   bfd_boolean reg_ok;
1531                   char *rq = mq;
1532
1533                   reg_ok = tic6x_parse_register (&rq, &offset_reg);
1534                   if (reg_ok)
1535                     {
1536                       skip_whitespace (rq);
1537                       if (*rq == endc)
1538                         {
1539                           mq = rq;
1540                           offset_is_reg = TRUE;
1541                         }
1542                     }
1543                 }
1544               if (!offset_is_reg)
1545                 {
1546                   char *save_input_line_pointer;
1547
1548                   save_input_line_pointer = input_line_pointer;
1549                   input_line_pointer = mq;
1550                   expression (&offset_exp);
1551                   mq = input_line_pointer;
1552                   input_line_pointer = save_input_line_pointer;
1553                 }
1554               skip_whitespace (mq);
1555               if (*mq == endc)
1556                 mq++;
1557               else
1558                 mem_ok = FALSE;
1559             }
1560         }
1561
1562       if (mem_ok && require_offset && scaled == tic6x_offset_none)
1563         mem_ok = FALSE;
1564
1565       if (mem_ok)
1566         {
1567           skip_whitespace (mq);
1568           if (!is_end_of_line[(unsigned char) *mq] && *mq != ',')
1569             mem_ok = FALSE;
1570         }
1571
1572       if (mem_ok)
1573         {
1574           op->form = op_forms & (TIC6X_OP_MEM_NOUNREG | TIC6X_OP_MEM_UNREG);
1575           op->value.mem.base_reg = base_reg;
1576           op->value.mem.mod = mem_mod;
1577           op->value.mem.scaled = scaled;
1578           op->value.mem.offset_is_reg = offset_is_reg;
1579           if (offset_is_reg)
1580             op->value.mem.offset.reg = offset_reg;
1581           else
1582             op->value.mem.offset.exp = offset_exp;
1583           operand_parsed = TRUE;
1584           q = mq;
1585           if (base_reg.num >= tic6x_num_registers)
1586             as_bad (_("register number %u not supported on this architecture"),
1587                     base_reg.num);
1588           if (offset_is_reg && offset_reg.num >= tic6x_num_registers)
1589             as_bad (_("register number %u not supported on this architecture"),
1590                     offset_reg.num);
1591         }
1592     }
1593
1594   /* See if this looks like a register or register pair.  */
1595   if (!operand_parsed && (op_forms & (TIC6X_OP_REG | TIC6X_OP_REGPAIR)))
1596     {
1597       tic6x_register first_reg, second_reg;
1598       bfd_boolean reg_ok;
1599       char *rq = q;
1600
1601       reg_ok = tic6x_parse_register (&rq, &first_reg);
1602
1603       if (reg_ok)
1604         {
1605           if (*rq == ':' && (op_forms & TIC6X_OP_REGPAIR))
1606             {
1607               rq++;
1608               reg_ok = tic6x_parse_register (&rq, &second_reg);
1609               if (reg_ok)
1610                 {
1611                   skip_whitespace (rq);
1612                   if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1613                     {
1614                       if ((second_reg.num & 1)
1615                           || (first_reg.num != second_reg.num + 1)
1616                           || (first_reg.side != second_reg.side))
1617                         as_bad (_("register pair for operand %u of '%.*s'"
1618                                   " not a valid even/odd pair"), opno,
1619                                 opc_len, str);
1620                       op->form = TIC6X_OP_REGPAIR;
1621                       op->value.reg = second_reg;
1622                       operand_parsed = TRUE;
1623                       q = rq;
1624                     }
1625                 }
1626             }
1627           else if (op_forms & TIC6X_OP_REG)
1628             {
1629               skip_whitespace (rq);
1630               if (is_end_of_line[(unsigned char) *rq] || *rq == ',')
1631                 {
1632                   op->form = TIC6X_OP_REG;
1633                   op->value.reg = first_reg;
1634                   operand_parsed = TRUE;
1635                   q = rq;
1636                 }
1637             }
1638         }
1639       if (operand_parsed)
1640         {
1641           if (first_reg.num >= tic6x_num_registers)
1642             as_bad (_("register number %u not supported on this architecture"),
1643                     first_reg.num);
1644           if (op->form == TIC6X_OP_REGPAIR
1645               && second_reg.num >= tic6x_num_registers)
1646             as_bad (_("register number %u not supported on this architecture"),
1647                     second_reg.num);
1648         }
1649     }
1650
1651   /* Otherwise, parse it as an expression.  */
1652   if (!operand_parsed && (op_forms & TIC6X_OP_EXP))
1653     {
1654       char *save_input_line_pointer;
1655
1656       save_input_line_pointer = input_line_pointer;
1657       input_line_pointer = q;
1658       op->form = TIC6X_OP_EXP;
1659       expression (&op->value.exp);
1660       q = input_line_pointer;
1661       input_line_pointer = save_input_line_pointer;
1662       operand_parsed = TRUE;
1663     }
1664
1665   if (operand_parsed)
1666     {
1667       /* Now the operand has been parsed, there must be nothing more
1668          before the comma or end of line.  */
1669       skip_whitespace (q);
1670       if (!is_end_of_line[(unsigned char) *q] && *q != ',')
1671         {
1672           operand_parsed = FALSE;
1673           as_bad (_("junk after operand %u of '%.*s'"), opno,
1674                   opc_len, str);
1675           while (!is_end_of_line[(unsigned char) *q] && *q != ',')
1676             q++;
1677         }
1678     }
1679   else
1680     {
1681       /* This could not be parsed as any acceptable form of
1682          operand.  */
1683       switch (op_forms)
1684         {
1685         case TIC6X_OP_REG | TIC6X_OP_REGPAIR:
1686           as_bad (_("bad register or register pair for operand %u of '%.*s'"),
1687                   opno, opc_len, str);
1688           break;
1689
1690         case TIC6X_OP_REG | TIC6X_OP_CTRL:
1691         case TIC6X_OP_REG:
1692           as_bad (_("bad register for operand %u of '%.*s'"),
1693                   opno, opc_len, str);
1694           break;
1695
1696         case TIC6X_OP_REGPAIR:
1697           as_bad (_("bad register pair for operand %u of '%.*s'"),
1698                   opno, opc_len, str);
1699           break;
1700
1701         case TIC6X_OP_FUNC_UNIT:
1702           as_bad (_("bad functional unit for operand %u of '%.*s'"),
1703                   opno, opc_len, str);
1704           break;
1705
1706         default:
1707           as_bad (_("bad operand %u of '%.*s'"),
1708                   opno, opc_len, str);
1709           break;
1710
1711         }
1712       while (!is_end_of_line[(unsigned char) *q] && *q != ',')
1713         q++;
1714     }
1715   *p = q;
1716   return operand_parsed;
1717 }
1718
1719 /* Table of assembler operators and associated O_* values.  */
1720 typedef struct
1721 {
1722   const char *name;
1723   operatorT op;
1724 } tic6x_operator_table;
1725 static const tic6x_operator_table tic6x_operators[] = {
1726 #define O_dsbt_index O_md1
1727   { "dsbt_index", O_dsbt_index },
1728 #define O_got O_md2
1729   { "got", O_got },
1730 #define O_dpr_got O_md3
1731   { "dpr_got", O_dpr_got },
1732 #define O_dpr_byte O_md4
1733   { "dpr_byte", O_dpr_byte },
1734 #define O_dpr_hword O_md5
1735   { "dpr_hword", O_dpr_hword },
1736 #define O_dpr_word O_md6
1737   { "dpr_word", O_dpr_word },
1738 #define O_pcr_offset O_md7
1739   { "pcr_offset", O_pcr_offset }
1740 };
1741
1742 /* Parse a name in some machine-specific way.  Used on C6X to handle
1743    assembler operators.  */
1744
1745 int
1746 tic6x_parse_name (const char *name, expressionS *exprP,
1747                   enum expr_mode mode ATTRIBUTE_UNUSED, char *nextchar)
1748 {
1749   char *p = input_line_pointer;
1750   char c, *name_start, *name_end;
1751   const char *inner_name;
1752   unsigned int i;
1753   operatorT op = O_illegal;
1754   symbolS *sym, *op_sym = NULL;
1755
1756   if (*name != '$')
1757     return 0;
1758
1759   for (i = 0; i < ARRAY_SIZE (tic6x_operators); i++)
1760     if (strcasecmp (name + 1, tic6x_operators[i].name) == 0)
1761       {
1762         op = tic6x_operators[i].op;
1763         break;
1764       }
1765
1766   if (op == O_illegal)
1767     return 0;
1768
1769   *input_line_pointer = *nextchar;
1770   skip_whitespace (p);
1771
1772   if (*p != '(')
1773     {
1774       *input_line_pointer = 0;
1775       return 0;
1776     }
1777   p++;
1778   skip_whitespace (p);
1779
1780   if (!is_name_beginner (*p))
1781     {
1782       *input_line_pointer = 0;
1783       return 0;
1784     }
1785
1786   name_start = p;
1787   p++;
1788   while (is_part_of_name (*p))
1789     p++;
1790   name_end = p;
1791   skip_whitespace (p);
1792
1793   if (op == O_pcr_offset)
1794     {
1795       char *op_name_start, *op_name_end;
1796
1797       if (*p != ',')
1798         {
1799           *input_line_pointer = 0;
1800           return 0;
1801         }
1802       p++;
1803       skip_whitespace (p);
1804
1805       if (!is_name_beginner (*p))
1806         {
1807           *input_line_pointer = 0;
1808           return 0;
1809         }
1810
1811       op_name_start = p;
1812       p++;
1813       while (is_part_of_name (*p))
1814         p++;
1815       op_name_end = p;
1816       skip_whitespace (p);
1817
1818       c = *op_name_end;
1819       *op_name_end = 0;
1820       op_sym = symbol_find_or_make (op_name_start);
1821       *op_name_end = c;
1822     }
1823
1824   if (*p != ')')
1825     {
1826       *input_line_pointer = 0;
1827       return 0;
1828     }
1829
1830   input_line_pointer = p + 1;
1831   *nextchar = *input_line_pointer;
1832   *input_line_pointer = 0;
1833
1834   c = *name_end;
1835   *name_end = 0;
1836   inner_name = name_start;
1837   if (op == O_dsbt_index && strcmp (inner_name, "__c6xabi_DSBT_BASE") != 0)
1838     {
1839       as_bad (_("$DSBT_INDEX must be used with __c6xabi_DSBT_BASE"));
1840       inner_name = "__c6xabi_DSBT_BASE";
1841     }
1842   sym = symbol_find_or_make (inner_name);
1843   *name_end = c;
1844
1845   exprP->X_op = op;
1846   exprP->X_add_symbol = sym;
1847   exprP->X_add_number = 0;
1848   exprP->X_op_symbol = op_sym;
1849   exprP->X_md = 0;
1850
1851   return 1;
1852 }
1853
1854 /* Create a fixup for an expression.  Same arguments as fix_new_exp,
1855    plus FIX_ADDA which is TRUE for ADDA instructions (to indicate that
1856    fixes resolving to constants should have those constants implicitly
1857    shifted) and FALSE otherwise, but look for C6X-specific expression
1858    types and adjust the relocations or give errors accordingly.  */
1859
1860 static void
1861 tic6x_fix_new_exp (fragS *frag, int where, int size, expressionS *exp,
1862                    int pcrel, bfd_reloc_code_real_type r_type,
1863                    bfd_boolean fix_adda)
1864 {
1865   bfd_reloc_code_real_type new_reloc = BFD_RELOC_UNUSED;
1866   symbolS *subsy = NULL;
1867   fixS *fix;
1868
1869   switch (exp->X_op)
1870     {
1871     case O_dsbt_index:
1872       switch (r_type)
1873         {
1874         case BFD_RELOC_C6000_SBR_U15_W:
1875           new_reloc = BFD_RELOC_C6000_DSBT_INDEX;
1876           break;
1877
1878         default:
1879           as_bad (_("$DSBT_INDEX not supported in this context"));
1880           return;
1881         }
1882       break;
1883
1884     case O_got:
1885       switch (r_type)
1886         {
1887         case BFD_RELOC_C6000_SBR_U15_W:
1888           new_reloc = BFD_RELOC_C6000_SBR_GOT_U15_W;
1889           break;
1890
1891         default:
1892           as_bad (_("$GOT not supported in this context"));
1893           return;
1894         }
1895       break;
1896
1897     case O_dpr_got:
1898       switch (r_type)
1899         {
1900         case BFD_RELOC_C6000_ABS_L16:
1901           new_reloc = BFD_RELOC_C6000_SBR_GOT_L16_W;
1902           break;
1903
1904         case BFD_RELOC_C6000_ABS_H16:
1905           new_reloc = BFD_RELOC_C6000_SBR_GOT_H16_W;
1906           break;
1907
1908         default:
1909           as_bad (_("$DPR_GOT not supported in this context"));
1910           return;
1911         }
1912       break;
1913
1914     case O_dpr_byte:
1915       switch (r_type)
1916         {
1917         case BFD_RELOC_C6000_ABS_S16:
1918           new_reloc = BFD_RELOC_C6000_SBR_S16;
1919           break;
1920
1921         case BFD_RELOC_C6000_ABS_L16:
1922           new_reloc = BFD_RELOC_C6000_SBR_L16_B;
1923           break;
1924
1925         case BFD_RELOC_C6000_ABS_H16:
1926           new_reloc = BFD_RELOC_C6000_SBR_H16_B;
1927           break;
1928
1929         default:
1930           as_bad (_("$DPR_BYTE not supported in this context"));
1931           return;
1932         }
1933       break;
1934
1935     case O_dpr_hword:
1936       switch (r_type)
1937         {
1938         case BFD_RELOC_C6000_ABS_L16:
1939           new_reloc = BFD_RELOC_C6000_SBR_L16_H;
1940           break;
1941
1942         case BFD_RELOC_C6000_ABS_H16:
1943           new_reloc = BFD_RELOC_C6000_SBR_H16_H;
1944           break;
1945
1946         default:
1947           as_bad (_("$DPR_HWORD not supported in this context"));
1948           return;
1949         }
1950       break;
1951
1952     case O_dpr_word:
1953       switch (r_type)
1954         {
1955         case BFD_RELOC_C6000_ABS_L16:
1956           new_reloc = BFD_RELOC_C6000_SBR_L16_W;
1957           break;
1958
1959         case BFD_RELOC_C6000_ABS_H16:
1960           new_reloc = BFD_RELOC_C6000_SBR_H16_W;
1961           break;
1962
1963         default:
1964           as_bad (_("$DPR_WORD not supported in this context"));
1965           return;
1966         }
1967       break;
1968
1969     case O_pcr_offset:
1970       subsy = exp->X_op_symbol;
1971       switch (r_type)
1972         {
1973         case BFD_RELOC_C6000_ABS_S16:
1974         case BFD_RELOC_C6000_ABS_L16:
1975           new_reloc = BFD_RELOC_C6000_PCR_L16;
1976           break;
1977
1978         case BFD_RELOC_C6000_ABS_H16:
1979           new_reloc = BFD_RELOC_C6000_PCR_H16;
1980           break;
1981
1982         default:
1983           as_bad (_("$PCR_OFFSET not supported in this context"));
1984           return;
1985         }
1986       break;
1987
1988     case O_symbol:
1989       break;
1990
1991     default:
1992       if (pcrel)
1993         {
1994           as_bad (_("invalid PC-relative operand"));
1995           return;
1996         }
1997       break;
1998     }
1999
2000   if (new_reloc == BFD_RELOC_UNUSED)
2001     fix = fix_new_exp (frag, where, size, exp, pcrel, r_type);
2002   else
2003     fix = fix_new (frag, where, size, exp->X_add_symbol, exp->X_add_number,
2004                    pcrel, new_reloc);
2005   fix->tc_fix_data.fix_subsy = subsy;
2006   fix->tc_fix_data.fix_adda = fix_adda;
2007 }
2008
2009 /* Generate a fix for a constant (.word etc.).  Needed to ensure these
2010    go through the error checking in tic6x_fix_new_exp.  */
2011
2012 void
2013 tic6x_cons_fix_new (fragS *frag, int where, int size, expressionS *exp,
2014                     bfd_reloc_code_real_type r_type)
2015 {
2016   switch (size)
2017     {
2018     case 1:
2019       r_type = BFD_RELOC_8;
2020       break;
2021
2022     case 2:
2023       r_type = BFD_RELOC_16;
2024       break;
2025
2026     case 4:
2027       r_type = BFD_RELOC_32;
2028       break;
2029
2030     default:
2031       as_bad (_("no %d-byte relocations available"), size);
2032       return;
2033     }
2034
2035   tic6x_fix_new_exp (frag, where, size, exp, 0, r_type, FALSE);
2036 }
2037
2038 /* Initialize target-specific fix data.  */
2039
2040 void
2041 tic6x_init_fix_data (fixS *fixP)
2042 {
2043   fixP->tc_fix_data.fix_adda = FALSE;
2044   fixP->tc_fix_data.fix_subsy = NULL;
2045 }
2046
2047 /* Return true if the fix can be handled by GAS, false if it must
2048    be passed through to the linker.  */
2049
2050 bfd_boolean
2051 tic6x_fix_adjustable (fixS *fixP)
2052 {
2053   switch (fixP->fx_r_type)
2054     {
2055       /* Adjust_reloc_syms doesn't know about the GOT.  */
2056     case BFD_RELOC_C6000_SBR_GOT_U15_W:
2057     case BFD_RELOC_C6000_SBR_GOT_H16_W:
2058     case BFD_RELOC_C6000_SBR_GOT_L16_W:
2059     case BFD_RELOC_C6000_EHTYPE:
2060       return 0;
2061
2062     case BFD_RELOC_C6000_PREL31:
2063       return 0;
2064
2065     case BFD_RELOC_C6000_PCR_H16:
2066     case BFD_RELOC_C6000_PCR_L16:
2067       return 0;
2068
2069     default:
2070       return 1;
2071     }
2072 }
2073
2074 /* Given the fine-grained form of an operand, return the coarse
2075    (bit-mask) form.  */
2076
2077 static unsigned int
2078 tic6x_coarse_operand_form (tic6x_operand_form form)
2079 {
2080   switch (form)
2081     {
2082     case tic6x_operand_asm_const:
2083     case tic6x_operand_link_const:
2084       return TIC6X_OP_EXP;
2085
2086     case tic6x_operand_reg:
2087     case tic6x_operand_xreg:
2088     case tic6x_operand_dreg:
2089     case tic6x_operand_areg:
2090     case tic6x_operand_retreg:
2091       return TIC6X_OP_REG;
2092
2093     case tic6x_operand_regpair:
2094     case tic6x_operand_xregpair:
2095     case tic6x_operand_dregpair:
2096       return TIC6X_OP_REGPAIR;
2097
2098     case tic6x_operand_irp:
2099       return TIC6X_OP_IRP;
2100
2101     case tic6x_operand_nrp:
2102       return TIC6X_OP_NRP;
2103
2104     case tic6x_operand_ctrl:
2105       return TIC6X_OP_CTRL;
2106
2107     case tic6x_operand_mem_short:
2108     case tic6x_operand_mem_long:
2109     case tic6x_operand_mem_deref:
2110       return TIC6X_OP_MEM_NOUNREG;
2111
2112     case tic6x_operand_mem_ndw:
2113       return TIC6X_OP_MEM_UNREG;
2114
2115     case tic6x_operand_func_unit:
2116       return TIC6X_OP_FUNC_UNIT;
2117
2118     default:
2119       abort ();
2120     }
2121 }
2122
2123 /* How an operand may match or not match a desired form.  If different
2124    instruction alternatives fail in different ways, the first failure
2125    in this list determines the diagnostic.  */
2126 typedef enum
2127   {
2128     /* Matches.  */
2129     tic6x_match_matches,
2130     /* Bad coarse form.  */
2131     tic6x_match_coarse,
2132     /* Not constant.  */
2133     tic6x_match_non_const,
2134     /* Register on wrong side.  */
2135     tic6x_match_wrong_side,
2136     /* Not a valid address register.  */
2137     tic6x_match_bad_address,
2138     /* Not a valid return address register.  */
2139     tic6x_match_bad_return,
2140     /* Control register not readable.  */
2141     tic6x_match_ctrl_write_only,
2142     /* Control register not writable.  */
2143     tic6x_match_ctrl_read_only,
2144     /* Not a valid memory reference for this instruction.  */
2145     tic6x_match_bad_mem
2146   } tic6x_operand_match;
2147
2148 /* Return whether an operand matches the given fine-grained form and
2149    read/write usage, and, if it does not match, how it fails to match.
2150    The main functional unit side is SIDE; the cross-path side is CROSS
2151    (the same as SIDE if a cross path not used); the data side is
2152    DATA_SIDE.  */
2153 static tic6x_operand_match
2154 tic6x_operand_matches_form (const tic6x_operand *op, tic6x_operand_form form,
2155                             tic6x_rw rw, unsigned int side, unsigned int cross,
2156                             unsigned int data_side)
2157 {
2158   unsigned int coarse = tic6x_coarse_operand_form (form);
2159
2160   if (coarse != op->form)
2161     return tic6x_match_coarse;
2162
2163   switch (form)
2164     {
2165     case tic6x_operand_asm_const:
2166       if (op->value.exp.X_op == O_constant)
2167         return tic6x_match_matches;
2168       else
2169         return tic6x_match_non_const;
2170
2171     case tic6x_operand_link_const:
2172     case tic6x_operand_irp:
2173     case tic6x_operand_nrp:
2174     case tic6x_operand_func_unit:
2175       /* All expressions are link-time constants, although there may
2176          not be relocations to express them in the output file.  "irp"
2177          and "nrp" are unique operand values.  All parsed functional
2178          unit names are valid.  */
2179       return tic6x_match_matches;
2180
2181     case tic6x_operand_reg:
2182     case tic6x_operand_regpair:
2183       if (op->value.reg.side == side)
2184         return tic6x_match_matches;
2185       else
2186         return tic6x_match_wrong_side;
2187
2188     case tic6x_operand_xreg:
2189     case tic6x_operand_xregpair:
2190       if (op->value.reg.side == cross)
2191         return tic6x_match_matches;
2192       else
2193         return tic6x_match_wrong_side;
2194
2195     case tic6x_operand_dreg:
2196     case tic6x_operand_dregpair:
2197       if (op->value.reg.side == data_side)
2198         return tic6x_match_matches;
2199       else
2200         return tic6x_match_wrong_side;
2201
2202     case tic6x_operand_areg:
2203       if (op->value.reg.side != cross)
2204         return tic6x_match_wrong_side;
2205       else if (op->value.reg.side == 2
2206                && (op->value.reg.num == 14 || op->value.reg.num == 15))
2207         return tic6x_match_matches;
2208       else
2209         return tic6x_match_bad_address;
2210
2211     case tic6x_operand_retreg:
2212       if (op->value.reg.side != side)
2213         return tic6x_match_wrong_side;
2214       else if (op->value.reg.num != 3)
2215         return tic6x_match_bad_return;
2216       else
2217         return tic6x_match_matches;
2218
2219     case tic6x_operand_ctrl:
2220       switch (rw)
2221         {
2222         case tic6x_rw_read:
2223           if (tic6x_ctrl_table[op->value.ctrl].rw == tic6x_rw_read
2224               || tic6x_ctrl_table[op->value.ctrl].rw == tic6x_rw_read_write)
2225             return tic6x_match_matches;
2226           else
2227             return tic6x_match_ctrl_write_only;
2228
2229         case tic6x_rw_write:
2230           if (tic6x_ctrl_table[op->value.ctrl].rw == tic6x_rw_write
2231               || tic6x_ctrl_table[op->value.ctrl].rw == tic6x_rw_read_write)
2232             return tic6x_match_matches;
2233           else
2234             return tic6x_match_ctrl_read_only;
2235
2236         default:
2237           abort ();
2238         }
2239
2240     case tic6x_operand_mem_deref:
2241       if (op->value.mem.mod != tic6x_mem_mod_none)
2242         return tic6x_match_bad_mem;
2243       else if (op->value.mem.scaled != tic6x_offset_none)
2244         abort ();
2245       else if (op->value.mem.base_reg.side != side)
2246         return tic6x_match_bad_mem;
2247       else
2248         return tic6x_match_matches;
2249
2250     case tic6x_operand_mem_short:
2251     case tic6x_operand_mem_ndw:
2252       if (op->value.mem.base_reg.side != side)
2253         return tic6x_match_bad_mem;
2254       if (op->value.mem.mod == tic6x_mem_mod_none)
2255         {
2256           if (op->value.mem.scaled != tic6x_offset_none)
2257             abort ();
2258           return tic6x_match_matches;
2259         }
2260       if (op->value.mem.scaled == tic6x_offset_none)
2261         {
2262           if (op->value.mem.mod == tic6x_mem_mod_plus
2263               || op->value.mem.mod == tic6x_mem_mod_minus)
2264             abort ();
2265           return tic6x_match_matches;
2266         }
2267       if (op->value.mem.offset_is_reg)
2268         {
2269           if (op->value.mem.scaled == tic6x_offset_unscaled
2270               && form != tic6x_operand_mem_ndw)
2271             abort ();
2272           if (op->value.mem.offset.reg.side == side)
2273             return tic6x_match_matches;
2274           else
2275             return tic6x_match_bad_mem;
2276         }
2277       else
2278         {
2279           if (op->value.mem.offset.exp.X_op == O_constant)
2280             return tic6x_match_matches;
2281           else
2282             return tic6x_match_bad_mem;
2283         }
2284
2285     case tic6x_operand_mem_long:
2286       if (op->value.mem.base_reg.side == 2
2287           && (op->value.mem.base_reg.num == 14
2288               || op->value.mem.base_reg.num == 15))
2289         {
2290           switch (op->value.mem.mod)
2291             {
2292             case tic6x_mem_mod_none:
2293               if (op->value.mem.scaled != tic6x_offset_none)
2294                 abort ();
2295               return tic6x_match_matches;
2296
2297             case tic6x_mem_mod_plus:
2298               if (op->value.mem.scaled == tic6x_offset_none)
2299                 abort ();
2300               if (op->value.mem.offset_is_reg)
2301                 return tic6x_match_bad_mem;
2302               else if (op->value.mem.scaled == tic6x_offset_scaled
2303                        && op->value.mem.offset.exp.X_op != O_constant)
2304                 return tic6x_match_bad_mem;
2305               else
2306                 return tic6x_match_matches;
2307
2308             case tic6x_mem_mod_minus:
2309             case tic6x_mem_mod_preinc:
2310             case tic6x_mem_mod_predec:
2311             case tic6x_mem_mod_postinc:
2312             case tic6x_mem_mod_postdec:
2313               return tic6x_match_bad_mem;
2314
2315             default:
2316               abort ();
2317             }
2318
2319         }
2320       else
2321         return tic6x_match_bad_mem;
2322
2323     default:
2324       abort ();
2325     }
2326 }
2327
2328 /* Return the number of bits shift used with DP-relative coding method
2329    CODING.  */
2330
2331 static unsigned int
2332 tic6x_dpr_shift (tic6x_coding_method coding)
2333 {
2334   switch (coding)
2335     {
2336     case tic6x_coding_ulcst_dpr_byte:
2337       return 0;
2338
2339     case tic6x_coding_ulcst_dpr_half:
2340       return 1;
2341
2342     case tic6x_coding_ulcst_dpr_word:
2343       return 2;
2344
2345     default:
2346       abort ();
2347     }
2348 }
2349
2350 /* Return the relocation used with DP-relative coding method
2351    CODING.  */
2352
2353 static bfd_reloc_code_real_type
2354 tic6x_dpr_reloc (tic6x_coding_method coding)
2355 {
2356   switch (coding)
2357     {
2358     case tic6x_coding_ulcst_dpr_byte:
2359       return BFD_RELOC_C6000_SBR_U15_B;
2360
2361     case tic6x_coding_ulcst_dpr_half:
2362       return BFD_RELOC_C6000_SBR_U15_H;
2363
2364     case tic6x_coding_ulcst_dpr_word:
2365       return BFD_RELOC_C6000_SBR_U15_W;
2366
2367     default:
2368       abort ();
2369     }
2370 }
2371
2372 /* Given a memory reference *MEM_REF as originally parsed, fill in
2373    defaults for missing offsets.  */
2374
2375 static void
2376 tic6x_default_mem_ref (tic6x_mem_ref *mem_ref)
2377 {
2378   switch (mem_ref->mod)
2379     {
2380     case tic6x_mem_mod_none:
2381       if (mem_ref->scaled != tic6x_offset_none)
2382         abort ();
2383       mem_ref->mod = tic6x_mem_mod_plus;
2384       mem_ref->scaled = tic6x_offset_unscaled;
2385       mem_ref->offset_is_reg = FALSE;
2386       memset (&mem_ref->offset.exp, 0, sizeof mem_ref->offset.exp);
2387       mem_ref->offset.exp.X_op = O_constant;
2388       mem_ref->offset.exp.X_add_number = 0;
2389       mem_ref->offset.exp.X_unsigned = 0;
2390       break;
2391
2392     case tic6x_mem_mod_plus:
2393     case tic6x_mem_mod_minus:
2394       if (mem_ref->scaled == tic6x_offset_none)
2395         abort ();
2396       break;
2397
2398     case tic6x_mem_mod_preinc:
2399     case tic6x_mem_mod_predec:
2400     case tic6x_mem_mod_postinc:
2401     case tic6x_mem_mod_postdec:
2402       if (mem_ref->scaled != tic6x_offset_none)
2403         break;
2404       mem_ref->scaled = tic6x_offset_scaled;
2405       mem_ref->offset_is_reg = FALSE;
2406       memset (&mem_ref->offset.exp, 0, sizeof mem_ref->offset.exp);
2407       mem_ref->offset.exp.X_op = O_constant;
2408       mem_ref->offset.exp.X_add_number = 1;
2409       mem_ref->offset.exp.X_unsigned = 0;
2410       break;
2411
2412     default:
2413       abort ();
2414     }
2415 }
2416
2417 /* Return the encoding in the 8-bit field of an SPMASK or SPMASKR
2418    instruction of the specified UNIT, side SIDE.  */
2419
2420 static unsigned int
2421 tic6x_encode_spmask (tic6x_func_unit_base unit, unsigned int side)
2422 {
2423   switch (unit)
2424     {
2425     case tic6x_func_unit_l:
2426       return 1 << (side - 1);
2427
2428     case tic6x_func_unit_s:
2429       return 1 << (side + 1);
2430
2431     case tic6x_func_unit_d:
2432       return 1 << (side + 3);
2433
2434     case tic6x_func_unit_m:
2435       return 1 << (side + 5);
2436
2437     default:
2438       abort ();
2439     }
2440 }
2441
2442 /* Try to encode the instruction with opcode number ID and operands
2443    OPERANDS (number NUM_OPERANDS), creg value THIS_LINE_CREG and z
2444    value THIS_LINE_Z; FUNC_UNIT_SIDE, FUNC_UNIT_CROSS and
2445    FUNC_UNIT_DATA_SIDE describe the functional unit specification;
2446    SPLOOP_II is the ii value from the previous SPLOOP-family
2447    instruction, or 0 if not in such a loop; the only possible problems
2448    are operands being out of range (they already match the
2449    fine-grained form), and inappropriate predication.  If this
2450    succeeds, return the encoding and set *OK to TRUE; otherwise return
2451    0 and set *OK to FALSE.  If a fix is needed, set *FIX_NEEDED to
2452    true and fill in *FIX_EXP, *FIX_PCREL, *FX_R_TYPE and *FIX_ADDA.
2453    Print error messages for failure if PRINT_ERRORS is TRUE; the
2454    opcode starts at STR and has length OPC_LEN.  */
2455
2456 static unsigned int
2457 tic6x_try_encode (tic6x_opcode_id id, tic6x_operand *operands,
2458                   unsigned int num_operands, unsigned int this_line_creg,
2459                   unsigned int this_line_z, unsigned int func_unit_side,
2460                   unsigned int func_unit_cross,
2461                   unsigned int func_unit_data_side, int sploop_ii,
2462                   expressionS **fix_exp, int *fix_pcrel,
2463                   bfd_reloc_code_real_type *fx_r_type, bfd_boolean *fix_adda,
2464                   bfd_boolean *fix_needed, bfd_boolean *ok,
2465                   bfd_boolean print_errors, char *str, int opc_len)
2466 {
2467   const tic6x_opcode *opct;
2468   const tic6x_insn_format *fmt;
2469   unsigned int opcode_value;
2470   unsigned int fld;
2471
2472   opct = &tic6x_opcode_table[id];
2473   fmt = &tic6x_insn_format_table[opct->format];
2474   opcode_value = fmt->cst_bits;
2475
2476   for (fld = 0; fld < opct->num_fixed_fields; fld++)
2477     {
2478       if (opct->fixed_fields[fld].min_val == opct->fixed_fields[fld].max_val)
2479         {
2480           const tic6x_insn_field *fldd;
2481           fldd = tic6x_field_from_fmt (fmt, opct->fixed_fields[fld].field_id);
2482           if (fldd == NULL)
2483             abort ();
2484           opcode_value |= opct->fixed_fields[fld].min_val << fldd->bitfields[0].low_pos;
2485         }
2486     }
2487
2488   for (fld = 0; fld < opct->num_variable_fields; fld++)
2489     {
2490       const tic6x_insn_field *fldd;
2491       unsigned int value;
2492       unsigned int opno;
2493       unsigned int ffld;
2494       offsetT sign_value;
2495       unsigned int bits;
2496       unsigned int fcyc_bits;
2497       expressionS *expp;
2498       expressionS ucexp;
2499       tic6x_mem_ref mem;
2500
2501       fldd = tic6x_field_from_fmt (fmt, opct->variable_fields[fld].field_id);
2502       if (fldd == NULL)
2503         abort ();
2504       opno = opct->variable_fields[fld].operand_num;
2505       switch (opct->variable_fields[fld].coding_method)
2506         {
2507         case tic6x_coding_ucst:
2508           if (operands[opno].form != TIC6X_OP_EXP)
2509             abort ();
2510           if (operands[opno].value.exp.X_op != O_constant)
2511             abort ();
2512           ucexp = operands[opno].value.exp;
2513         unsigned_constant:
2514           if (ucexp.X_add_number < 0
2515               || ucexp.X_add_number >= (1 << fldd->bitfields[0].width))
2516             {
2517               if (print_errors)
2518                 as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
2519                         opc_len, str);
2520               *ok = FALSE;
2521               return 0;
2522             }
2523           value = ucexp.X_add_number;
2524           break;
2525
2526         case tic6x_coding_scst:
2527           if (operands[opno].form != TIC6X_OP_EXP)
2528             abort ();
2529           if (operands[opno].value.exp.X_op != O_constant)
2530             {
2531               value = 0;
2532               /* Opcode table should not permit non-constants without
2533                  a known relocation for them.  */
2534               if (fldd->bitfields[0].low_pos != 7 || fldd->bitfields[0].width != 16)
2535                 abort ();
2536               *fix_needed = TRUE;
2537               *fix_exp = &operands[opno].value.exp;
2538               *fix_pcrel = 0;
2539               *fx_r_type = BFD_RELOC_C6000_ABS_S16;
2540               *fix_adda = FALSE;
2541               break;
2542             }
2543           sign_value = SEXT (operands[opno].value.exp.X_add_number);
2544         signed_constant:
2545           if (sign_value < -(1 << (fldd->bitfields[0].width - 1))
2546               || (sign_value >= (1 << (fldd->bitfields[0].width - 1))))
2547             {
2548               if (print_errors)
2549                 as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
2550                         opc_len, str);
2551               *ok = FALSE;
2552               return 0;
2553             }
2554           value = sign_value + (1 << (fldd->bitfields[0].width - 1));
2555           value ^= (1 << (fldd->bitfields[0].width - 1));
2556           break;
2557
2558         case tic6x_coding_ucst_minus_one:
2559           if (operands[opno].form != TIC6X_OP_EXP)
2560             abort ();
2561           if (operands[opno].value.exp.X_op != O_constant)
2562             abort ();
2563           if (operands[opno].value.exp.X_add_number <= 0
2564               || operands[opno].value.exp.X_add_number > (1 << fldd->bitfields[0].width))
2565             {
2566               if (print_errors)
2567                 as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
2568                         opc_len, str);
2569               *ok = FALSE;
2570               return 0;
2571             }
2572           value = operands[opno].value.exp.X_add_number - 1;
2573           break;
2574
2575         case tic6x_coding_scst_negate:
2576           if (operands[opno].form != TIC6X_OP_EXP)
2577             abort ();
2578           if (operands[opno].value.exp.X_op != O_constant)
2579             abort ();
2580           sign_value = SEXT (-operands[opno].value.exp.X_add_number);
2581           goto signed_constant;
2582
2583         case tic6x_coding_ulcst_dpr_byte:
2584         case tic6x_coding_ulcst_dpr_half:
2585         case tic6x_coding_ulcst_dpr_word:
2586           bits = tic6x_dpr_shift (opct->variable_fields[fld].coding_method);
2587           switch (operands[opno].form)
2588             {
2589             case TIC6X_OP_EXP:
2590               if (operands[opno].value.exp.X_op == O_constant)
2591                 {
2592                   ucexp = operands[opno].value.exp;
2593                   goto unsigned_constant;
2594                 }
2595               expp = &operands[opno].value.exp;
2596               break;
2597
2598             case TIC6X_OP_MEM_NOUNREG:
2599               mem = operands[opno].value.mem;
2600               tic6x_default_mem_ref (&mem);
2601               if (mem.offset_is_reg)
2602                 abort ();
2603               if (mem.offset.exp.X_op == O_constant)
2604                 {
2605                   ucexp = mem.offset.exp;
2606                   if (mem.scaled == tic6x_offset_unscaled)
2607                     {
2608                       if (ucexp.X_add_number & ((1 << bits) - 1))
2609                         {
2610                           if (print_errors)
2611                             as_bad (_("offset in operand %u of '%.*s' not "
2612                                       "divisible by %u"), opno + 1, opc_len,
2613                                     str, 1u << bits);
2614                           *ok = FALSE;
2615                           return 0;
2616                         }
2617                       ucexp.X_add_number >>= bits;
2618                     }
2619                   goto unsigned_constant;
2620                 }
2621               if (mem.scaled != tic6x_offset_unscaled)
2622                 abort ();
2623               if (operands[opno].value.mem.mod == tic6x_mem_mod_none
2624                   || operands[opno].value.mem.scaled != tic6x_offset_unscaled
2625                   || operands[opno].value.mem.offset_is_reg)
2626                 abort ();
2627               expp = &operands[opno].value.mem.offset.exp;
2628               break;
2629
2630             default:
2631               abort ();
2632             }
2633           value = 0;
2634           /* Opcode table should not use this encoding without a known
2635              relocation.  */
2636           if (fldd->bitfields[0].low_pos != 8 || fldd->bitfields[0].width != 15)
2637             abort ();
2638           /* We do not check for offset divisibility here; such a
2639              check is not needed at this point to encode the value,
2640              and if there is eventually a problem it will be detected
2641              either in md_apply_fix or at link time.  */
2642           *fix_needed = TRUE;
2643           *fix_exp = expp;
2644           *fix_pcrel = 0;
2645           *fx_r_type
2646             = tic6x_dpr_reloc (opct->variable_fields[fld].coding_method);
2647           if (operands[opno].form == TIC6X_OP_EXP)
2648             *fix_adda = TRUE;
2649           else
2650             *fix_adda = FALSE;
2651           break;
2652
2653         case tic6x_coding_lcst_low16:
2654           if (operands[opno].form != TIC6X_OP_EXP)
2655             abort ();
2656           if (operands[opno].value.exp.X_op == O_constant)
2657             value = operands[opno].value.exp.X_add_number & 0xffff;
2658           else
2659             {
2660               value = 0;
2661               /* Opcode table should not use this encoding without a
2662                  known relocation.  */
2663               if (fldd->bitfields[0].low_pos != 7 || fldd->bitfields[0].width != 16)
2664                 abort ();
2665               *fix_needed = TRUE;
2666               *fix_exp = &operands[opno].value.exp;
2667               *fix_pcrel = 0;
2668               *fx_r_type = BFD_RELOC_C6000_ABS_L16;
2669               *fix_adda = FALSE;
2670             }
2671           break;
2672
2673         case tic6x_coding_lcst_high16:
2674           if (operands[opno].form != TIC6X_OP_EXP)
2675             abort ();
2676           if (operands[opno].value.exp.X_op == O_constant)
2677             value = (operands[opno].value.exp.X_add_number >> 16) & 0xffff;
2678           else
2679             {
2680               value = 0;
2681               /* Opcode table should not use this encoding without a
2682                  known relocation.  */
2683               if (fldd->bitfields[0].low_pos != 7 || fldd->bitfields[0].width != 16)
2684                 abort ();
2685               *fix_needed = TRUE;
2686               *fix_exp = &operands[opno].value.exp;
2687               *fix_pcrel = 0;
2688               *fx_r_type = BFD_RELOC_C6000_ABS_H16;
2689               *fix_adda = FALSE;
2690             }
2691           break;
2692
2693         case tic6x_coding_pcrel:
2694         case tic6x_coding_pcrel_half:
2695           if (operands[opno].form != TIC6X_OP_EXP)
2696             abort ();
2697           value = 0;
2698           *fix_needed = TRUE;
2699           *fix_exp = &operands[opno].value.exp;
2700           *fix_pcrel = 1;
2701           if (fldd->bitfields[0].low_pos == 7 && fldd->bitfields[0].width == 21)
2702             *fx_r_type = BFD_RELOC_C6000_PCR_S21;
2703           else if (fldd->bitfields[0].low_pos == 16 && fldd->bitfields[0].width == 12)
2704             *fx_r_type = BFD_RELOC_C6000_PCR_S12;
2705           else if (fldd->bitfields[0].low_pos == 13 && fldd->bitfields[0].width == 10)
2706             *fx_r_type = BFD_RELOC_C6000_PCR_S10;
2707           else if (fldd->bitfields[0].low_pos == 16 && fldd->bitfields[0].width == 7)
2708             *fx_r_type = BFD_RELOC_C6000_PCR_S7;
2709           else
2710             /* Opcode table should not use this encoding without a
2711                known relocation.  */
2712             abort ();
2713           *fix_adda = FALSE;
2714           break;
2715
2716         case tic6x_coding_regpair_lsb:
2717           switch (operands[opno].form)
2718             {
2719             case TIC6X_OP_REGPAIR:
2720               value = operands[opno].value.reg.num;
2721               break;
2722
2723             default:
2724               abort ();
2725             }
2726           break;
2727
2728         case tic6x_coding_regpair_msb:
2729           switch (operands[opno].form)
2730             {
2731             case TIC6X_OP_REGPAIR:
2732               value = operands[opno].value.reg.num + 1;
2733               break;
2734
2735             default:
2736               abort ();
2737             }
2738           break;
2739
2740         case tic6x_coding_reg:
2741           switch (operands[opno].form)
2742             {
2743             case TIC6X_OP_REG:
2744             case TIC6X_OP_REGPAIR:
2745               value = operands[opno].value.reg.num;
2746               break;
2747
2748             case TIC6X_OP_MEM_NOUNREG:
2749             case TIC6X_OP_MEM_UNREG:
2750               value = operands[opno].value.mem.base_reg.num;
2751               break;
2752
2753             default:
2754               abort ();
2755             }
2756           break;
2757
2758         case tic6x_coding_areg:
2759           switch (operands[opno].form)
2760             {
2761             case TIC6X_OP_REG:
2762               value = (operands[opno].value.reg.num == 15 ? 1 : 0);
2763               break;
2764
2765             case TIC6X_OP_MEM_NOUNREG:
2766               value = (operands[opno].value.mem.base_reg.num == 15 ? 1 : 0);
2767               break;
2768
2769             default:
2770               abort ();
2771             }
2772           break;
2773
2774         case tic6x_coding_crlo:
2775           if (operands[opno].form != TIC6X_OP_CTRL)
2776             abort ();
2777           value = tic6x_ctrl_table[operands[opno].value.ctrl].crlo;
2778           break;
2779
2780         case tic6x_coding_crhi:
2781           if (operands[opno].form != TIC6X_OP_CTRL)
2782             abort ();
2783           value = 0;
2784           break;
2785
2786         case tic6x_coding_reg_shift:
2787           if (operands[opno].form != TIC6X_OP_REGPAIR)
2788             abort ();
2789           value = operands[opno].value.reg.num >> 1;
2790           break;
2791
2792         case tic6x_coding_mem_offset:
2793           if (operands[opno].form != TIC6X_OP_MEM_NOUNREG)
2794             abort ();
2795           mem = operands[opno].value.mem;
2796           tic6x_default_mem_ref (&mem);
2797           if (mem.offset_is_reg)
2798             {
2799               if (mem.scaled != tic6x_offset_scaled)
2800                 abort ();
2801               value = mem.offset.reg.num;
2802             }
2803           else
2804             {
2805               int scale;
2806
2807               if (mem.offset.exp.X_op != O_constant)
2808                 abort ();
2809               switch (mem.scaled)
2810                 {
2811                 case tic6x_offset_scaled:
2812                   scale = 1;
2813                   break;
2814
2815                 case tic6x_offset_unscaled:
2816                   scale = opct->operand_info[opno].size;
2817                   if (scale != 1 && scale != 2 && scale != 4 && scale != 8)
2818                     abort ();
2819                   break;
2820
2821                 default:
2822                   abort ();
2823                 }
2824               if (mem.offset.exp.X_add_number < 0
2825                   || mem.offset.exp.X_add_number >= (1 << fldd->bitfields[0].width) * scale)
2826                 {
2827                   if (print_errors)
2828                     as_bad (_("offset in operand %u of '%.*s' out of range"),
2829                             opno + 1, opc_len, str);
2830                   *ok = FALSE;
2831                   return 0;
2832                 }
2833               if (mem.offset.exp.X_add_number % scale)
2834                 {
2835                   if (print_errors)
2836                     as_bad (_("offset in operand %u of '%.*s' not "
2837                               "divisible by %u"),
2838                             opno + 1, opc_len, str, scale);
2839                   *ok = FALSE;
2840                   return 0;
2841                 }
2842               value = mem.offset.exp.X_add_number / scale;
2843             }
2844           break;
2845
2846         case tic6x_coding_mem_offset_noscale:
2847           if (operands[opno].form != TIC6X_OP_MEM_UNREG)
2848             abort ();
2849           mem = operands[opno].value.mem;
2850           tic6x_default_mem_ref (&mem);
2851           if (mem.offset_is_reg)
2852             value = mem.offset.reg.num;
2853           else
2854             {
2855               if (mem.offset.exp.X_op != O_constant)
2856                 abort ();
2857               if (mem.offset.exp.X_add_number < 0
2858                   || mem.offset.exp.X_add_number >= (1 << fldd->bitfields[0].width))
2859                 {
2860                   if (print_errors)
2861                     as_bad (_("offset in operand %u of '%.*s' out of range"),
2862                             opno + 1, opc_len, str);
2863                   *ok = FALSE;
2864                   return 0;
2865                 }
2866               value = mem.offset.exp.X_add_number;
2867             }
2868           break;
2869
2870         case tic6x_coding_mem_mode:
2871           if (operands[opno].form != TIC6X_OP_MEM_NOUNREG
2872               && operands[opno].form != TIC6X_OP_MEM_UNREG)
2873             abort ();
2874           mem = operands[opno].value.mem;
2875           tic6x_default_mem_ref (&mem);
2876           switch (mem.mod)
2877             {
2878             case tic6x_mem_mod_plus:
2879               value = 1;
2880               break;
2881
2882             case tic6x_mem_mod_minus:
2883               value = 0;
2884               break;
2885
2886             case tic6x_mem_mod_preinc:
2887               value = 9;
2888               break;
2889
2890             case tic6x_mem_mod_predec:
2891               value = 8;
2892               break;
2893
2894             case tic6x_mem_mod_postinc:
2895               value = 11;
2896               break;
2897
2898             case tic6x_mem_mod_postdec:
2899               value = 10;
2900               break;
2901
2902             default:
2903               abort ();
2904             }
2905           value += (mem.offset_is_reg ? 4 : 0);
2906           break;
2907
2908         case tic6x_coding_scaled:
2909           if (operands[opno].form != TIC6X_OP_MEM_UNREG)
2910             abort ();
2911           mem = operands[opno].value.mem;
2912           tic6x_default_mem_ref (&mem);
2913           switch (mem.scaled)
2914             {
2915             case tic6x_offset_unscaled:
2916               value = 0;
2917               break;
2918
2919             case tic6x_offset_scaled:
2920               value = 1;
2921               break;
2922
2923             default:
2924               abort ();
2925             }
2926           break;
2927
2928         case tic6x_coding_spmask:
2929           /* The position of such a field is hardcoded in the handling
2930              of "||^".  */
2931           if (fldd->bitfields[0].low_pos != 18)
2932             abort ();
2933           value = 0;
2934           for (opno = 0; opno < num_operands; opno++)
2935             {
2936               unsigned int v;
2937
2938               v = tic6x_encode_spmask (operands[opno].value.func_unit.base,
2939                                        operands[opno].value.func_unit.side);
2940               if (value & v)
2941                 {
2942                   if (print_errors)
2943                     as_bad (_("functional unit already masked for operand "
2944                               "%u of '%.*s'"), opno + 1, opc_len, str);
2945                   *ok = FALSE;
2946                   return 0;
2947                 }
2948               value |= v;
2949             }
2950           break;
2951
2952         case tic6x_coding_reg_unused:
2953           /* This is a placeholder; correct handling goes along with
2954              resource constraint checks.  */
2955           value = 0;
2956           break;
2957
2958         case tic6x_coding_fstg:
2959         case tic6x_coding_fcyc:
2960           if (operands[opno].form != TIC6X_OP_EXP)
2961             abort ();
2962           if (operands[opno].value.exp.X_op != O_constant)
2963             abort ();
2964           if (!sploop_ii)
2965             {
2966               if (print_errors)
2967                 as_bad (_("'%.*s' instruction not in a software "
2968                           "pipelined loop"),
2969                         opc_len, str);
2970               *ok = FALSE;
2971               return 0;
2972             }
2973
2974           if (sploop_ii <= 1)
2975             fcyc_bits = 0;
2976           else if (sploop_ii <= 2)
2977             fcyc_bits = 1;
2978           else if (sploop_ii <= 4)
2979             fcyc_bits = 2;
2980           else if (sploop_ii <= 8)
2981             fcyc_bits = 3;
2982           else if (sploop_ii <= 14)
2983             fcyc_bits = 4;
2984           else
2985             abort ();
2986           if (fcyc_bits > fldd->bitfields[0].width)
2987             abort ();
2988
2989           if (opct->variable_fields[fld].coding_method == tic6x_coding_fstg)
2990             {
2991               int i, t;
2992               if (operands[opno].value.exp.X_add_number < 0
2993                   || (operands[opno].value.exp.X_add_number
2994                       >= (1 << (fldd->bitfields[0].width - fcyc_bits))))
2995                 {
2996                   if (print_errors)
2997                     as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
2998                             opc_len, str);
2999                   *ok = FALSE;
3000                   return 0;
3001                 }
3002               value = operands[opno].value.exp.X_add_number;
3003               for (t = 0, i = fcyc_bits; i < fldd->bitfields[0].width; i++)
3004                 {
3005                   t = (t << 1) | (value & 1);
3006                   value >>= 1;
3007                 }
3008               value = t << fcyc_bits;
3009             }
3010           else
3011             {
3012               if (operands[opno].value.exp.X_add_number < 0
3013                   || (operands[opno].value.exp.X_add_number >= sploop_ii))
3014                 {
3015                   if (print_errors)
3016                     as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
3017                             opc_len, str);
3018                   *ok = FALSE;
3019                   return 0;
3020                 }
3021               value = operands[opno].value.exp.X_add_number;
3022             }
3023           break;
3024
3025         case tic6x_coding_fu:
3026           value = func_unit_side == 2 ? 1 : 0;
3027           break;
3028
3029         case tic6x_coding_data_fu:
3030           value = func_unit_data_side == 2 ? 1 : 0;
3031           break;
3032
3033         case tic6x_coding_xpath:
3034           value = func_unit_cross;
3035           break;
3036
3037         default:
3038           abort ();
3039         }
3040
3041       for (ffld = 0; ffld < opct->num_fixed_fields; ffld++)
3042         if ((opct->fixed_fields[ffld].field_id
3043              == opct->variable_fields[fld].field_id)
3044             && (value < opct->fixed_fields[ffld].min_val
3045                 || value > opct->fixed_fields[ffld].max_val))
3046           {
3047             if (print_errors)
3048               as_bad (_("operand %u of '%.*s' out of range"), opno + 1,
3049                       opc_len, str);
3050             *ok = FALSE;
3051             return 0;
3052           }
3053
3054       opcode_value |= value << fldd->bitfields[0].low_pos;
3055     }
3056
3057   if (this_line_creg)
3058     {
3059       const tic6x_insn_field *creg;
3060       const tic6x_insn_field *z;
3061
3062       creg = tic6x_field_from_fmt (fmt, tic6x_field_creg);
3063       if (creg == NULL)
3064         {
3065           if (print_errors)
3066             as_bad (_("instruction '%.*s' cannot be predicated"),
3067                     opc_len, str);
3068           *ok = FALSE;
3069           return 0;
3070         }
3071       z = tic6x_field_from_fmt (fmt, tic6x_field_z);
3072       /* If there is a creg field, there must be a z field; otherwise
3073          there is an error in the format table.  */
3074       if (z == NULL)
3075         abort ();
3076
3077       opcode_value |= this_line_creg << creg->bitfields[0].low_pos;
3078       opcode_value |= this_line_z << z->bitfields[0].low_pos;
3079     }
3080
3081   *ok = TRUE;
3082   return opcode_value;
3083 }
3084
3085 /* Convert the target integer stored in N bytes in BUF to a host
3086    integer, returning that value.  */
3087
3088 static valueT
3089 md_chars_to_number (char *buf, int n)
3090 {
3091   valueT result = 0;
3092   unsigned char *p = (unsigned char *) buf;
3093
3094   if (target_big_endian)
3095     {
3096       while (n--)
3097         {
3098           result <<= 8;
3099           result |= (*p++ & 0xff);
3100         }
3101     }
3102   else
3103     {
3104       while (n--)
3105         {
3106           result <<= 8;
3107           result |= (p[n] & 0xff);
3108         }
3109     }
3110
3111   return result;
3112 }
3113
3114 /* Assemble the instruction starting at STR (an opcode, with the
3115    opcode name all-lowercase).  */
3116
3117 void
3118 md_assemble (char *str)
3119 {
3120   char *p;
3121   int opc_len;
3122   bfd_boolean this_line_parallel;
3123   bfd_boolean this_line_spmask;
3124   unsigned int this_line_creg;
3125   unsigned int this_line_z;
3126   tic6x_label_list *this_insn_label_list;
3127   segment_info_type *seginfo;
3128   tic6x_opcode_list *opc_list, *opc;
3129   tic6x_func_unit_base func_unit_base = tic6x_func_unit_nfu;
3130   unsigned int func_unit_side = 0;
3131   unsigned int func_unit_cross = 0;
3132   unsigned int cross_side = 0;
3133   unsigned int func_unit_data_side = 0;
3134   unsigned int max_matching_opcodes, num_matching_opcodes;
3135   tic6x_opcode_id *opcm = NULL;
3136   unsigned int opc_rank[TIC6X_NUM_PREFER];
3137   const tic6x_opcode *opct = NULL;
3138   int min_rank, try_rank, max_rank;
3139   bfd_boolean num_operands_permitted[TIC6X_MAX_SOURCE_OPERANDS + 1]
3140     = { FALSE };
3141   unsigned int operand_forms[TIC6X_MAX_SOURCE_OPERANDS] = { 0 };
3142   tic6x_operand operands[TIC6X_MAX_SOURCE_OPERANDS];
3143   unsigned int max_num_operands;
3144   unsigned int num_operands_read;
3145   bfd_boolean ok_this_arch, ok_this_fu, ok_this_arch_fu;
3146   bfd_boolean bad_operands = FALSE;
3147   unsigned int opcode_value;
3148   bfd_boolean encoded_ok;
3149   bfd_boolean fix_needed = FALSE;
3150   expressionS *fix_exp = NULL;
3151   int fix_pcrel = 0;
3152   bfd_reloc_code_real_type fx_r_type = BFD_RELOC_UNUSED;
3153   bfd_boolean fix_adda = FALSE;
3154   fragS *insn_frag;
3155   char *output;
3156
3157   p = str;
3158   while (*p && !is_end_of_line[(unsigned char) *p] && *p != ' ')
3159     p++;
3160
3161   /* This function should only have been called when there is actually
3162      an instruction to assemble.  */
3163   if (p == str)
3164     abort ();
3165
3166   /* Now an instruction has been seen, architecture attributes from
3167      .arch directives merge with rather than overriding the previous
3168      value.  */
3169   tic6x_seen_insns = TRUE;
3170   /* If no .arch directives or -march options have been seen, we are
3171      assessing instruction validity based on the C674X default, so set
3172      the attribute accordingly.  */
3173   if (tic6x_arch_attribute == C6XABI_Tag_ISA_none)
3174     tic6x_arch_attribute = C6XABI_Tag_ISA_C674X;
3175
3176   /* Reset global settings for parallel bars and predicates now to
3177      avoid extra errors if there are problems with this opcode.  */
3178   this_line_parallel = tic6x_line_parallel;
3179   this_line_spmask = tic6x_line_spmask;
3180   this_line_creg = tic6x_line_creg;
3181   this_line_z = tic6x_line_z;
3182   tic6x_line_parallel = FALSE;
3183   tic6x_line_spmask = FALSE;
3184   tic6x_line_creg = 0;
3185   tic6x_line_z = 0;
3186   seginfo = seg_info (now_seg);
3187   this_insn_label_list = seginfo->tc_segment_info_data.label_list;
3188   seginfo->tc_segment_info_data.label_list = NULL;
3189
3190   opc_list = hash_find_n (opcode_hash, str, p - str);
3191   if (opc_list == NULL)
3192     {
3193       char c = *p;
3194       *p = 0;
3195       as_bad (_("unknown opcode '%s'"), str);
3196       *p = c;
3197       return;
3198     }
3199
3200   opc_len = p - str;
3201   skip_whitespace (p);
3202
3203   /* See if there is something that looks like a functional unit
3204      specifier.  */
3205   if (*p == '.')
3206     {
3207       bfd_boolean good_func_unit;
3208       tic6x_func_unit_base maybe_base = tic6x_func_unit_nfu;
3209       unsigned int maybe_side = 0;
3210       unsigned int maybe_cross = 0;
3211       unsigned int maybe_data_side = 0;
3212
3213       good_func_unit = tic6x_parse_func_unit_base (p + 1, &maybe_base,
3214                                                    &maybe_side);
3215
3216       if (good_func_unit)
3217         {
3218           if (p[3] == ' ' || is_end_of_line[(unsigned char) p[3]])
3219             p += 3;
3220           else if ((p[3] == 'x' || p[3] == 'X')
3221                    && (p[4] == ' ' || is_end_of_line[(unsigned char) p[4]]))
3222             {
3223               maybe_cross = 1;
3224               p += 4;
3225             }
3226           else if (maybe_base == tic6x_func_unit_d
3227                    && (p[3] == 't' || p[3] == 'T')
3228                    && (p[4] == '1' || p[4] == '2')
3229                    && (p[5] == ' ' || is_end_of_line[(unsigned char) p[5]]))
3230             {
3231               maybe_data_side = p[4] - '0';
3232               p += 5;
3233             }
3234           else
3235             good_func_unit = FALSE;
3236         }
3237
3238       if (good_func_unit)
3239         {
3240           func_unit_base = maybe_base;
3241           func_unit_side = maybe_side;
3242           func_unit_cross = maybe_cross;
3243           cross_side = (func_unit_cross ? 3 - func_unit_side : func_unit_side);
3244           func_unit_data_side = maybe_data_side;
3245         }
3246
3247       skip_whitespace (p);
3248     }
3249
3250   /* Determine which entries in the opcode table match, and the
3251      associated permitted forms of operands.  */
3252   max_matching_opcodes = 0;
3253   for (opc = opc_list; opc; opc = opc->next)
3254     max_matching_opcodes++;
3255   num_matching_opcodes = 0;
3256   opcm = XNEWVEC (tic6x_opcode_id, max_matching_opcodes);
3257   max_num_operands = 0;
3258   ok_this_arch = FALSE;
3259   ok_this_fu = FALSE;
3260   ok_this_arch_fu = FALSE;
3261   for (opc = opc_list; opc; opc = opc->next)
3262     {
3263       unsigned int num_operands;
3264       unsigned int i;
3265       bfd_boolean this_opc_arch_ok = TRUE;
3266       bfd_boolean this_opc_fu_ok = TRUE;
3267
3268       if (tic6x_insn_format_table[tic6x_opcode_table[opc->id].format].num_bits
3269           != 32)
3270         continue;
3271       if (!(tic6x_opcode_table[opc->id].isa_variants & tic6x_features))
3272         this_opc_arch_ok = FALSE;
3273       if (tic6x_opcode_table[opc->id].func_unit != func_unit_base)
3274         this_opc_fu_ok = FALSE;
3275       if (func_unit_side == 1
3276           && (tic6x_opcode_table[opc->id].flags & TIC6X_FLAG_SIDE_B_ONLY))
3277         this_opc_fu_ok = FALSE;
3278       if (func_unit_cross
3279           && (tic6x_opcode_table[opc->id].flags & TIC6X_FLAG_NO_CROSS))
3280         this_opc_fu_ok = FALSE;
3281       if (!func_unit_data_side
3282           && (tic6x_opcode_table[opc->id].flags
3283               & (TIC6X_FLAG_LOAD | TIC6X_FLAG_STORE)))
3284         this_opc_fu_ok = FALSE;
3285       if (func_unit_data_side
3286           && !(tic6x_opcode_table[opc->id].flags
3287                & (TIC6X_FLAG_LOAD | TIC6X_FLAG_STORE)))
3288         this_opc_fu_ok = FALSE;
3289       if (func_unit_data_side == 1
3290           && (tic6x_opcode_table[opc->id].flags & TIC6X_FLAG_SIDE_T2_ONLY))
3291         this_opc_fu_ok = FALSE;
3292       if (this_opc_arch_ok)
3293         ok_this_arch = TRUE;
3294       if (this_opc_fu_ok)
3295         ok_this_fu = TRUE;
3296       if (!this_opc_arch_ok || !this_opc_fu_ok)
3297         continue;
3298       ok_this_arch_fu = TRUE;
3299       opcm[num_matching_opcodes] = opc->id;
3300       num_matching_opcodes++;
3301       num_operands = tic6x_opcode_table[opc->id].num_operands;
3302
3303       if (tic6x_opcode_table[opc->id].flags & TIC6X_FLAG_SPMASK)
3304         {
3305           if (num_operands != 1
3306               || (tic6x_opcode_table[opc->id].operand_info[0].form
3307                   != tic6x_operand_func_unit))
3308             abort ();
3309           num_operands = 8;
3310           for (i = 0; i < num_operands; i++)
3311             {
3312               operand_forms[i]
3313                 |= tic6x_coarse_operand_form (tic6x_operand_func_unit);
3314               num_operands_permitted[i] = TRUE;
3315             }
3316         }
3317       else
3318         {
3319           for (i = 0; i < num_operands; i++)
3320             {
3321               tic6x_operand_form f
3322                 = tic6x_opcode_table[opc->id].operand_info[i].form;
3323
3324               operand_forms[i] |= tic6x_coarse_operand_form (f);
3325             }
3326         }
3327       num_operands_permitted[num_operands] = TRUE;
3328       if (num_operands > max_num_operands)
3329         max_num_operands = num_operands;
3330     }
3331
3332   if (!ok_this_arch)
3333     {
3334       as_bad (_("'%.*s' instruction not supported on this architecture"),
3335               opc_len, str);
3336       free (opcm);
3337       return;
3338     }
3339
3340   if (!ok_this_fu)
3341     {
3342       as_bad (_("'%.*s' instruction not supported on this functional unit"),
3343               opc_len, str);
3344       free (opcm);
3345       return;
3346     }
3347
3348   if (!ok_this_arch_fu)
3349     {
3350       as_bad (_("'%.*s' instruction not supported on this functional unit"
3351                 " for this architecture"),
3352               opc_len, str);
3353       free (opcm);
3354       return;
3355     }
3356
3357   /* If there were no instructions matching the above availability
3358      checks, we should now have given an error and returned.  */
3359   if (num_matching_opcodes == 0)
3360     abort ();
3361
3362   num_operands_read = 0;
3363   while (TRUE)
3364     {
3365       skip_whitespace (p);
3366       if (is_end_of_line[(unsigned char) *p])
3367         {
3368           if (num_operands_read > 0)
3369             {
3370               as_bad (_("missing operand after comma"));
3371               bad_operands = TRUE;
3372             }
3373           break;
3374         }
3375
3376       if (max_num_operands == 0)
3377         {
3378           as_bad (_("too many operands to '%.*s'"), opc_len, str);
3379           bad_operands = TRUE;
3380           break;
3381         }
3382
3383       if (!tic6x_parse_operand (&p, &operands[num_operands_read],
3384                                 operand_forms[num_operands_read], str, opc_len,
3385                                 num_operands_read + 1))
3386         bad_operands = TRUE;
3387       num_operands_read++;
3388
3389       if (is_end_of_line[(unsigned char) *p])
3390         break;
3391       else if (*p == ',')
3392         {
3393           p++;
3394           if (num_operands_read == max_num_operands)
3395             {
3396               as_bad (_("too many operands to '%.*s'"), opc_len, str);
3397               bad_operands = TRUE;
3398               break;
3399             }
3400           continue;
3401         }
3402       else
3403         /* Operand parsing should consume whole operands.  */
3404         abort ();
3405     }
3406
3407   if (!bad_operands && !num_operands_permitted[num_operands_read])
3408     {
3409       as_bad (_("bad number of operands to '%.*s'"), opc_len, str);
3410       bad_operands = TRUE;
3411     }
3412
3413   if (!bad_operands)
3414     {
3415       /* Each operand is of the right syntactic form for some opcode
3416          choice, and the number of operands is valid.  Check that each
3417          operand is OK in detail for some opcode choice with the right
3418          number of operands.  */
3419       unsigned int i;
3420
3421       for (i = 0; i < num_operands_read; i++)
3422         {
3423           bfd_boolean coarse_ok = FALSE;
3424           bfd_boolean fine_ok = FALSE;
3425           tic6x_operand_match fine_failure = tic6x_match_matches;
3426           unsigned int j;
3427
3428           for (j = 0; j < num_matching_opcodes; j++)
3429             {
3430               tic6x_operand_form f;
3431               tic6x_rw rw;
3432               unsigned int cf;
3433               tic6x_operand_match this_fine_failure;
3434
3435               if (tic6x_opcode_table[opcm[j]].flags & TIC6X_FLAG_SPMASK)
3436                 {
3437                   f = tic6x_operand_func_unit;
3438                   rw = tic6x_rw_none;
3439                 }
3440               else
3441                 {
3442                   if (tic6x_opcode_table[opcm[j]].num_operands
3443                       != num_operands_read)
3444                     continue;
3445
3446                   f = tic6x_opcode_table[opcm[j]].operand_info[i].form;
3447                   rw = tic6x_opcode_table[opcm[j]].operand_info[i].rw;
3448                 }
3449               cf = tic6x_coarse_operand_form (f);
3450
3451               if (operands[i].form != cf)
3452                 continue;
3453
3454               coarse_ok = TRUE;
3455               this_fine_failure
3456                 = tic6x_operand_matches_form (&operands[i], f, rw,
3457                                               func_unit_side,
3458                                               cross_side,
3459                                               func_unit_data_side);
3460               if (this_fine_failure == tic6x_match_matches)
3461                 {
3462                   fine_ok = TRUE;
3463                   break;
3464                 }
3465               if (fine_failure == tic6x_match_matches
3466                   || fine_failure > this_fine_failure)
3467                 fine_failure = this_fine_failure;
3468             }
3469
3470           /* No instructions should have operand syntactic forms only
3471              acceptable with certain numbers of operands, so no
3472              diagnostic for this case.  */
3473           if (!coarse_ok)
3474             abort ();
3475
3476           if (!fine_ok)
3477             {
3478               switch (fine_failure)
3479                 {
3480                 case tic6x_match_non_const:
3481                   as_bad (_("operand %u of '%.*s' not constant"),
3482                           i + 1, opc_len, str);
3483                   break;
3484
3485                 case tic6x_match_wrong_side:
3486                   as_bad (_("operand %u of '%.*s' on wrong side"),
3487                           i + 1, opc_len, str);
3488                   break;
3489
3490                 case tic6x_match_bad_return:
3491                   as_bad (_("operand %u of '%.*s' not a valid return "
3492                             "address register"),
3493                           i + 1, opc_len, str);
3494                   break;
3495
3496                 case tic6x_match_ctrl_write_only:
3497                   as_bad (_("operand %u of '%.*s' is write-only"),
3498                           i + 1, opc_len, str);
3499                   break;
3500
3501                 case tic6x_match_ctrl_read_only:
3502                   as_bad (_("operand %u of '%.*s' is read-only"),
3503                           i + 1, opc_len, str);
3504                   break;
3505
3506                 case tic6x_match_bad_mem:
3507                   as_bad (_("operand %u of '%.*s' not a valid memory "
3508                             "reference"),
3509                           i + 1, opc_len, str);
3510                   break;
3511
3512                 case tic6x_match_bad_address:
3513                   as_bad (_("operand %u of '%.*s' not a valid base "
3514                             "address register"),
3515                           i + 1, opc_len, str);
3516                   break;
3517
3518                 default:
3519                   abort ();
3520                 }
3521               bad_operands = TRUE;
3522               break;
3523             }
3524         }
3525     }
3526
3527   if (!bad_operands)
3528     {
3529       /* Each operand is OK for some opcode choice, and the number of
3530          operands is valid.  Check whether there is an opcode choice
3531          for which all operands are simultaneously valid.  */
3532       unsigned int i;
3533       bfd_boolean found_match = FALSE;
3534
3535       for (i = 0; i < TIC6X_NUM_PREFER; i++)
3536         opc_rank[i] = (unsigned int) -1;
3537
3538       min_rank = TIC6X_NUM_PREFER - 1;
3539       max_rank = 0;
3540
3541       for (i = 0; i < num_matching_opcodes; i++)
3542         {
3543           unsigned int j;
3544           bfd_boolean this_matches = TRUE;
3545
3546           if (!(tic6x_opcode_table[opcm[i]].flags & TIC6X_FLAG_SPMASK)
3547               && tic6x_opcode_table[opcm[i]].num_operands != num_operands_read)
3548             continue;
3549
3550           for (j = 0; j < num_operands_read; j++)
3551             {
3552               tic6x_operand_form f;
3553               tic6x_rw rw;
3554
3555               if (tic6x_opcode_table[opcm[i]].flags & TIC6X_FLAG_SPMASK)
3556                 {
3557                   f = tic6x_operand_func_unit;
3558                   rw = tic6x_rw_none;
3559                 }
3560               else
3561                 {
3562                   f = tic6x_opcode_table[opcm[i]].operand_info[j].form;
3563                   rw = tic6x_opcode_table[opcm[i]].operand_info[j].rw;
3564                 }
3565               if (tic6x_operand_matches_form (&operands[j], f, rw,
3566                                               func_unit_side,
3567                                               cross_side,
3568                                               func_unit_data_side)
3569                   != tic6x_match_matches)
3570                 {
3571                   this_matches = FALSE;
3572                   break;
3573                 }
3574             }
3575
3576           if (this_matches)
3577             {
3578               int rank = TIC6X_PREFER_VAL (tic6x_opcode_table[opcm[i]].flags);
3579
3580               if (rank < min_rank)
3581                 min_rank = rank;
3582               if (rank > max_rank)
3583                 max_rank = rank;
3584
3585               if (opc_rank[rank] == (unsigned int) -1)
3586                 opc_rank[rank] = i;
3587               else
3588                 /* The opcode table should provide a total ordering
3589                    for all cases where multiple matches may get
3590                    here.  */
3591                 abort ();
3592
3593               found_match = TRUE;
3594             }
3595         }
3596
3597       if (!found_match)
3598         {
3599           as_bad (_("bad operand combination for '%.*s'"), opc_len, str);
3600           bad_operands = TRUE;
3601         }
3602     }
3603
3604   if (bad_operands)
3605     {
3606       free (opcm);
3607       return;
3608     }
3609
3610   opcode_value = 0;
3611   encoded_ok = FALSE;
3612   for (try_rank = max_rank; try_rank >= min_rank; try_rank--)
3613     {
3614       fix_needed = FALSE;
3615
3616       if (opc_rank[try_rank] == (unsigned int) -1)
3617         continue;
3618
3619       opcode_value = tic6x_try_encode (opcm[opc_rank[try_rank]], operands,
3620                                        num_operands_read, this_line_creg,
3621                                        this_line_z, func_unit_side,
3622                                        func_unit_cross, func_unit_data_side,
3623                                        seginfo->tc_segment_info_data.sploop_ii,
3624                                        &fix_exp, &fix_pcrel, &fx_r_type,
3625                                        &fix_adda, &fix_needed, &encoded_ok,
3626                                        (try_rank == min_rank ? TRUE : FALSE),
3627                                        str, opc_len);
3628       if (encoded_ok)
3629         {
3630           opct = &tic6x_opcode_table[opcm[opc_rank[try_rank]]];
3631           break;
3632         }
3633     }
3634
3635   free (opcm);
3636
3637   if (!encoded_ok)
3638     return;
3639
3640   if (this_line_parallel)
3641     {
3642       insn_frag = seginfo->tc_segment_info_data.execute_packet_frag;
3643       if (insn_frag == NULL)
3644         {
3645           as_bad (_("parallel instruction not following another instruction"));
3646           return;
3647         }
3648
3649       if (insn_frag->fr_fix >= 32)
3650         {
3651           as_bad (_("too many instructions in execute packet"));
3652           return;
3653         }
3654
3655       if (this_insn_label_list != NULL)
3656         as_bad (_("label not at start of execute packet"));
3657
3658       if (opct->flags & TIC6X_FLAG_FIRST)
3659         as_bad (_("'%.*s' instruction not at start of execute packet"),
3660                 opc_len, str);
3661
3662       *seginfo->tc_segment_info_data.last_insn_lsb |= 0x1;
3663       output = insn_frag->fr_literal + insn_frag->fr_fix;
3664     }
3665   else
3666     {
3667       tic6x_label_list *l;
3668
3669       seginfo->tc_segment_info_data.spmask_addr = NULL;
3670       seginfo->tc_segment_info_data.func_units_used = 0;
3671
3672       /* Start a new frag for this execute packet.  */
3673       if (frag_now_fix () != 0)
3674         {
3675           if (frag_now->fr_type != rs_machine_dependent)
3676             frag_wane (frag_now);
3677
3678           frag_new (0);
3679         }
3680       frag_grow (32);
3681       insn_frag = seginfo->tc_segment_info_data.execute_packet_frag = frag_now;
3682       for (l = this_insn_label_list; l; l = l->next)
3683         {
3684           symbol_set_frag (l->label, frag_now);
3685           S_SET_VALUE (l->label, 0);
3686           S_SET_SEGMENT (l->label, now_seg);
3687         }
3688       tic6x_free_label_list (this_insn_label_list);
3689       dwarf2_emit_insn (0);
3690       output = frag_var (rs_machine_dependent, 32, 32, 0, NULL, 0, NULL);
3691       /* This must be the same as the frag to which a pointer was just
3692          saved.  */
3693       if (output != insn_frag->fr_literal)
3694         abort ();
3695       insn_frag->tc_frag_data.is_insns = TRUE;
3696       insn_frag->tc_frag_data.can_cross_fp_boundary
3697         = tic6x_can_cross_fp_boundary;
3698     }
3699
3700   if (func_unit_base != tic6x_func_unit_nfu)
3701     {
3702       unsigned int func_unit_enc;
3703
3704       func_unit_enc = tic6x_encode_spmask (func_unit_base, func_unit_side);
3705
3706       if (seginfo->tc_segment_info_data.func_units_used & func_unit_enc)
3707         as_bad (_("functional unit already used in this execute packet"));
3708
3709       seginfo->tc_segment_info_data.func_units_used |= func_unit_enc;
3710     }
3711
3712   if (opct->flags & TIC6X_FLAG_SPLOOP)
3713     {
3714       if (seginfo->tc_segment_info_data.sploop_ii)
3715         as_bad (_("nested software pipelined loop"));
3716       if (num_operands_read != 1
3717           || operands[0].form != TIC6X_OP_EXP
3718           || operands[0].value.exp.X_op != O_constant)
3719         abort ();
3720       seginfo->tc_segment_info_data.sploop_ii
3721         = operands[0].value.exp.X_add_number;
3722     }
3723   else if (opct->flags & TIC6X_FLAG_SPKERNEL)
3724     {
3725       if (!seginfo->tc_segment_info_data.sploop_ii)
3726         as_bad (_("'%.*s' instruction not in a software pipelined loop"),
3727                 opc_len, str);
3728       seginfo->tc_segment_info_data.sploop_ii = 0;
3729     }
3730
3731   if (this_line_spmask)
3732     {
3733       if (seginfo->tc_segment_info_data.spmask_addr == NULL)
3734         as_bad (_("'||^' without previous SPMASK"));
3735       else if (func_unit_base == tic6x_func_unit_nfu)
3736         as_bad (_("cannot mask instruction using no functional unit"));
3737       else
3738         {
3739           unsigned int spmask_opcode;
3740           unsigned int mask_bit;
3741
3742           spmask_opcode
3743             = md_chars_to_number (seginfo->tc_segment_info_data.spmask_addr,
3744                                   4);
3745           mask_bit = tic6x_encode_spmask (func_unit_base, func_unit_side);
3746           mask_bit <<= 18;
3747           if (spmask_opcode & mask_bit)
3748             as_bad (_("functional unit already masked"));
3749           spmask_opcode |= mask_bit;
3750           md_number_to_chars (seginfo->tc_segment_info_data.spmask_addr,
3751                               spmask_opcode, 4);
3752         }
3753     }
3754
3755   record_alignment (now_seg, 5);
3756   md_number_to_chars (output, opcode_value, 4);
3757   if (fix_needed)
3758     tic6x_fix_new_exp (insn_frag, output - insn_frag->fr_literal, 4, fix_exp,
3759                        fix_pcrel, fx_r_type, fix_adda);
3760   insn_frag->fr_fix += 4;
3761   insn_frag->fr_var -= 4;
3762   seginfo->tc_segment_info_data.last_insn_lsb
3763     = (target_big_endian ? output + 3 : output);
3764   if (opct->flags & TIC6X_FLAG_SPMASK)
3765     seginfo->tc_segment_info_data.spmask_addr = output;
3766 }
3767
3768 /* Modify NEWVAL (32-bit) by inserting VALUE, shifted right by SHIFT
3769    and the least significant BITS bits taken, at position POS.  */
3770 #define MODIFY_VALUE(NEWVAL, VALUE, SHIFT, POS, BITS)                   \
3771   do {                                                                  \
3772     (NEWVAL) &= 0xffffffffU & ~(((1U << (BITS)) - 1) << (POS));         \
3773     (NEWVAL) |= (((VALUE) >> (SHIFT)) & ((1U << (BITS)) - 1)) << (POS); \
3774   } while (0)
3775
3776 /* Apply a fixup to the object file.  */
3777
3778 void
3779 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
3780 {
3781   offsetT value = *valP;
3782   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
3783
3784   value = SEXT (value);
3785   *valP = value;
3786
3787   fixP->fx_offset = SEXT (fixP->fx_offset);
3788
3789   if (fixP->fx_addsy == NULL && fixP->fx_pcrel == 0)
3790     fixP->fx_done = 1;
3791
3792   /* We do our own overflow checks.  */
3793   fixP->fx_no_overflow = 1;
3794
3795   switch (fixP->fx_r_type)
3796     {
3797     case BFD_RELOC_NONE:
3798     case BFD_RELOC_C6000_EHTYPE:
3799       /* Force output to the object file.  */
3800       fixP->fx_done = 0;
3801       break;
3802
3803     case BFD_RELOC_32:
3804       if (fixP->fx_done || !seg->use_rela_p)
3805         md_number_to_chars (buf, value, 4);
3806       break;
3807
3808     case BFD_RELOC_16:
3809       if (fixP->fx_done || !seg->use_rela_p)
3810         {
3811           if (value < -0x8000 || value > 0xffff)
3812             as_bad_where (fixP->fx_file, fixP->fx_line,
3813                           _("value too large for 2-byte field"));
3814           md_number_to_chars (buf, value, 2);
3815         }
3816       break;
3817
3818     case BFD_RELOC_8:
3819       if (fixP->fx_done || !seg->use_rela_p)
3820         {
3821           if (value < -0x80 || value > 0xff)
3822             as_bad_where (fixP->fx_file, fixP->fx_line,
3823                           _("value too large for 1-byte field"));
3824           *buf = value;
3825         }
3826       break;
3827
3828     case BFD_RELOC_C6000_ABS_S16:
3829     case BFD_RELOC_C6000_ABS_L16:
3830     case BFD_RELOC_C6000_SBR_S16:
3831     case BFD_RELOC_C6000_SBR_L16_B:
3832     case BFD_RELOC_C6000_SBR_L16_H:
3833     case BFD_RELOC_C6000_SBR_L16_W:
3834     case BFD_RELOC_C6000_SBR_GOT_L16_W:
3835       if (fixP->fx_done || !seg->use_rela_p)
3836         {
3837           offsetT newval = md_chars_to_number (buf, 4);
3838           int shift;
3839
3840           switch (fixP->fx_r_type)
3841             {
3842             case BFD_RELOC_C6000_SBR_L16_H:
3843               shift = 1;
3844               break;
3845
3846             case BFD_RELOC_C6000_SBR_L16_W:
3847             case BFD_RELOC_C6000_SBR_GOT_L16_W:
3848               shift = 2;
3849               break;
3850
3851             default:
3852               shift = 0;
3853               break;
3854             }
3855
3856           MODIFY_VALUE (newval, value, shift, 7, 16);
3857           if ((value < -0x8000 || value > 0x7fff)
3858               && (fixP->fx_r_type == BFD_RELOC_C6000_ABS_S16
3859                   || fixP->fx_r_type == BFD_RELOC_C6000_SBR_S16))
3860             as_bad_where (fixP->fx_file, fixP->fx_line,
3861                           _("immediate offset out of range"));
3862
3863           md_number_to_chars (buf, newval, 4);
3864         }
3865       if (fixP->fx_done
3866           && fixP->fx_r_type != BFD_RELOC_C6000_ABS_S16
3867           && fixP->fx_r_type != BFD_RELOC_C6000_ABS_L16)
3868         abort ();
3869       break;
3870
3871     case BFD_RELOC_C6000_ABS_H16:
3872     case BFD_RELOC_C6000_SBR_H16_B:
3873     case BFD_RELOC_C6000_SBR_H16_H:
3874     case BFD_RELOC_C6000_SBR_H16_W:
3875     case BFD_RELOC_C6000_SBR_GOT_H16_W:
3876       if (fixP->fx_done || !seg->use_rela_p)
3877         {
3878           offsetT newval = md_chars_to_number (buf, 4);
3879           int shift;
3880
3881           switch (fixP->fx_r_type)
3882             {
3883             case BFD_RELOC_C6000_SBR_H16_H:
3884               shift = 17;
3885               break;
3886
3887             case BFD_RELOC_C6000_SBR_H16_W:
3888             case BFD_RELOC_C6000_SBR_GOT_H16_W:
3889               shift = 18;
3890               break;
3891
3892             default:
3893               shift = 16;
3894               break;
3895             }
3896
3897           MODIFY_VALUE (newval, value, shift, 7, 16);
3898
3899           md_number_to_chars (buf, newval, 4);
3900         }
3901       if (fixP->fx_done && fixP->fx_r_type != BFD_RELOC_C6000_ABS_H16)
3902         abort ();
3903       break;
3904
3905     case BFD_RELOC_C6000_PCR_H16:
3906     case BFD_RELOC_C6000_PCR_L16:
3907       if (fixP->fx_done || !seg->use_rela_p)
3908         {
3909           offsetT newval = md_chars_to_number (buf, 4);
3910           int shift = fixP->fx_r_type == BFD_RELOC_C6000_PCR_H16 ? 16 : 0;
3911
3912           MODIFY_VALUE (newval, value, shift, 7, 16);
3913
3914           md_number_to_chars (buf, newval, 4);
3915         }
3916       break;
3917
3918     case BFD_RELOC_C6000_SBR_U15_B:
3919       if (fixP->fx_done || !seg->use_rela_p)
3920         {
3921           offsetT newval = md_chars_to_number (buf, 4);
3922
3923           MODIFY_VALUE (newval, value, 0, 8, 15);
3924           if (value < 0 || value > 0x7fff)
3925             as_bad_where (fixP->fx_file, fixP->fx_line,
3926                           _("immediate offset out of range"));
3927
3928           md_number_to_chars (buf, newval, 4);
3929         }
3930       break;
3931
3932     case BFD_RELOC_C6000_SBR_U15_H:
3933       if (fixP->fx_done || !seg->use_rela_p)
3934         {
3935           offsetT newval = md_chars_to_number (buf, 4);
3936
3937           /* Constant ADDA operands, processed as constant when the
3938              instruction is parsed, are encoded as-is rather than
3939              shifted.  If the operand of an ADDA instruction is now
3940              constant (for example, the difference between two labels
3941              found after the instruction), ensure it is encoded the
3942              same way it would have been if the constant value had
3943              been known when the instruction was parsed.  */
3944           if (fixP->tc_fix_data.fix_adda && fixP->fx_done)
3945             value <<= 1;
3946
3947           MODIFY_VALUE (newval, value, 1, 8, 15);
3948           if (value & 1)
3949             as_bad_where (fixP->fx_file, fixP->fx_line,
3950                           _("immediate offset not 2-byte-aligned"));
3951           if (value < 0 || value > 0xfffe)
3952             as_bad_where (fixP->fx_file, fixP->fx_line,
3953                           _("immediate offset out of range"));
3954
3955           md_number_to_chars (buf, newval, 4);
3956         }
3957       break;
3958
3959     case BFD_RELOC_C6000_SBR_U15_W:
3960     case BFD_RELOC_C6000_SBR_GOT_U15_W:
3961       if (fixP->fx_done || !seg->use_rela_p)
3962         {
3963           offsetT newval = md_chars_to_number (buf, 4);
3964
3965           /* Constant ADDA operands, processed as constant when the
3966              instruction is parsed, are encoded as-is rather than
3967              shifted.  If the operand of an ADDA instruction is now
3968              constant (for example, the difference between two labels
3969              found after the instruction), ensure it is encoded the
3970              same way it would have been if the constant value had
3971              been known when the instruction was parsed.  */
3972           if (fixP->tc_fix_data.fix_adda && fixP->fx_done)
3973             value <<= 2;
3974
3975           MODIFY_VALUE (newval, value, 2, 8, 15);
3976           if (value & 3)
3977             as_bad_where (fixP->fx_file, fixP->fx_line,
3978                           _("immediate offset not 4-byte-aligned"));
3979           if (value < 0 || value > 0x1fffc)
3980             as_bad_where (fixP->fx_file, fixP->fx_line,
3981                           _("immediate offset out of range"));
3982
3983           md_number_to_chars (buf, newval, 4);
3984         }
3985       if (fixP->fx_done && fixP->fx_r_type != BFD_RELOC_C6000_SBR_U15_W)
3986         abort ();
3987       break;
3988
3989     case BFD_RELOC_C6000_DSBT_INDEX:
3990       if (value != 0)
3991         as_bad_where (fixP->fx_file, fixP->fx_line,
3992                       _("addend used with $DSBT_INDEX"));
3993       if (fixP->fx_done)
3994         abort ();
3995       break;
3996
3997     case BFD_RELOC_C6000_PCR_S21:
3998       if (fixP->fx_done || !seg->use_rela_p)
3999         {
4000           offsetT newval = md_chars_to_number (buf, 4);
4001
4002           MODIFY_VALUE (newval, value, 2, 7, 21);
4003
4004           if (value & 3)
4005             as_bad_where (fixP->fx_file, fixP->fx_line,
4006                           _("PC-relative offset not 4-byte-aligned"));
4007           if (value < -0x400000 || value > 0x3ffffc)
4008             as_bad_where (fixP->fx_file, fixP->fx_line,
4009                           _("PC-relative offset out of range"));
4010
4011           md_number_to_chars (buf, newval, 4);
4012         }
4013       break;
4014
4015     case BFD_RELOC_C6000_PCR_S12:
4016       if (fixP->fx_done || !seg->use_rela_p)
4017         {
4018           offsetT newval = md_chars_to_number (buf, 4);
4019
4020           MODIFY_VALUE (newval, value, 2, 16, 12);
4021
4022           if (value & 3)
4023             as_bad_where (fixP->fx_file, fixP->fx_line,
4024                           _("PC-relative offset not 4-byte-aligned"));
4025           if (value < -0x2000 || value > 0x1ffc)
4026             as_bad_where (fixP->fx_file, fixP->fx_line,
4027                           _("PC-relative offset out of range"));
4028
4029           md_number_to_chars (buf, newval, 4);
4030         }
4031       break;
4032
4033     case BFD_RELOC_C6000_PCR_S10:
4034       if (fixP->fx_done || !seg->use_rela_p)
4035         {
4036           offsetT newval = md_chars_to_number (buf, 4);
4037
4038           MODIFY_VALUE (newval, value, 2, 13, 10);
4039
4040           if (value & 3)
4041             as_bad_where (fixP->fx_file, fixP->fx_line,
4042                           _("PC-relative offset not 4-byte-aligned"));
4043           if (value < -0x800 || value > 0x7fc)
4044             as_bad_where (fixP->fx_file, fixP->fx_line,
4045                           _("PC-relative offset out of range"));
4046
4047           md_number_to_chars (buf, newval, 4);
4048         }
4049       break;
4050
4051     case BFD_RELOC_C6000_PCR_S7:
4052       if (fixP->fx_done || !seg->use_rela_p)
4053         {
4054           offsetT newval = md_chars_to_number (buf, 4);
4055
4056           MODIFY_VALUE (newval, value, 2, 16, 7);
4057
4058           if (value & 3)
4059             as_bad_where (fixP->fx_file, fixP->fx_line,
4060                           _("PC-relative offset not 4-byte-aligned"));
4061           if (value < -0x100 || value > 0xfc)
4062             as_bad_where (fixP->fx_file, fixP->fx_line,
4063                           _("PC-relative offset out of range"));
4064
4065           md_number_to_chars (buf, newval, 4);
4066         }
4067       break;
4068
4069     case BFD_RELOC_C6000_PREL31:
4070       /* Force output to the object file.  */
4071       fixP->fx_done = 0;
4072       break;
4073
4074     default:
4075       abort ();
4076     }
4077 }
4078
4079 /* Convert a floating-point number to target (IEEE) format.  */
4080
4081 const char *
4082 md_atof (int type, char *litP, int *sizeP)
4083 {
4084   return ieee_md_atof (type, litP, sizeP, target_big_endian);
4085 }
4086
4087 /* Adjust the frags in SECTION (see tic6x_end).  */
4088
4089 static void
4090 tic6x_adjust_section (bfd *abfd ATTRIBUTE_UNUSED, segT section,
4091                       void *dummy ATTRIBUTE_UNUSED)
4092 {
4093   segment_info_type *info;
4094   frchainS *frchp;
4095   fragS *fragp;
4096   bfd_boolean have_code = FALSE;
4097   bfd_boolean have_non_code = FALSE;
4098
4099   info = seg_info (section);
4100   if (info == NULL)
4101     return;
4102
4103   for (frchp = info->frchainP; frchp; frchp = frchp->frch_next)
4104     for (fragp = frchp->frch_root; fragp; fragp = fragp->fr_next)
4105       switch (fragp->fr_type)
4106         {
4107         case rs_machine_dependent:
4108           if (fragp->tc_frag_data.is_insns)
4109             have_code = TRUE;
4110           break;
4111
4112         case rs_dummy:
4113         case rs_fill:
4114           if (fragp->fr_fix > 0)
4115             have_non_code = TRUE;
4116           break;
4117
4118         default:
4119           have_non_code = TRUE;
4120           break;
4121         }
4122
4123   /* Process alignment requirements in a code-only section.  */
4124   if (have_code && !have_non_code)
4125     {
4126       /* If we need to insert an odd number of instructions to meet an
4127          alignment requirement, there must have been an odd number of
4128          instructions since the last 8-byte-aligned execute packet
4129          boundary.  So there must have been an execute packet with an
4130          odd number (and so a number fewer than 8) of instructions
4131          into which we can insert a NOP without breaking any previous
4132          alignments.
4133
4134          If then we need to insert a number 2 mod 4 of instructions,
4135          the number of instructions since the last 16-byte-aligned
4136          execute packet boundary must be 2 mod 4.  So between that
4137          boundary and the following 8-byte-aligned boundary there must
4138          either be at least one execute packet with 2-mod-4
4139          instructions, or at least two with an odd number of
4140          instructions; again, greedily inserting NOPs as soon as
4141          possible suffices to meet the alignment requirement.
4142
4143          If then we need to insert 4 instructions, we look between the
4144          last 32-byte-aligned boundary and the following
4145          16-byte-aligned boundary.  The sizes of the execute packets
4146          in this range total 4 instructions mod 8, so again there is
4147          room for greedy insertion of NOPs to meet the alignment
4148          requirement, and before any intermediate point with 8-byte
4149          (2-instruction) alignment requirement the sizes of execute
4150          packets (and so the room for NOPs) will total 2 instructions
4151          mod 4 so greedy insertion will not break such alignments.
4152
4153          So we can always meet these alignment requirements by
4154          inserting NOPs in parallel with existing execute packets, and
4155          by induction the approach described above inserts the minimum
4156          number of such NOPs.  */
4157
4158       /* The number of NOPs we are currently looking to insert, if we
4159          have gone back to insert NOPs.  */
4160       unsigned int want_insert = 0;
4161
4162       /* Out of that number, the number inserted so far in the current
4163          stage of the above algorithm.  */
4164       unsigned int want_insert_done_so_far = 0;
4165
4166       /* The position mod 32 at the start of the current frag.  */
4167       unsigned int pos = 0;
4168
4169       /* The locations in the frag chain of the most recent frags at
4170          the start of which there is the given alignment.  */
4171       frchainS *frchp_last32, *frchp_last16, *frchp_last8;
4172       fragS *fragp_last32, *fragp_last16, *fragp_last8;
4173       unsigned int pos_last32, pos_last16, pos_last8;
4174
4175       frchp_last32 = frchp_last16 = frchp_last8 = info->frchainP;
4176       fragp_last32 = fragp_last16 = fragp_last8 = info->frchainP->frch_root;
4177       pos_last32 = pos_last16 = pos_last8 = 0;
4178
4179       for (frchp = info->frchainP; frchp; frchp = frchp->frch_next)
4180         for (fragp = frchp->frch_root; fragp; fragp = fragp->fr_next)
4181         look_at_frag:
4182           {
4183             bfd_boolean go_back = FALSE;
4184             frchainS *frchp_next;
4185             fragS *fragp_next;
4186
4187             if (fragp->fr_type != rs_machine_dependent)
4188               continue;
4189
4190             if (fragp->tc_frag_data.is_insns
4191                 && pos + fragp->fr_fix > 32
4192                 && !fragp->tc_frag_data.can_cross_fp_boundary)
4193               {
4194                 /* As described above, we should always have met an
4195                    alignment requirement by the time we come back to
4196                    it.  */
4197                 if (want_insert)
4198                   abort ();
4199
4200                 if (pos & 3)
4201                   abort ();
4202                 want_insert = (32 - pos) >> 2;
4203                 if (want_insert > 7)
4204                   abort ();
4205                 want_insert_done_so_far = 0;
4206                 go_back = TRUE;
4207               }
4208
4209             if (!fragp->tc_frag_data.is_insns)
4210               {
4211                 unsigned int would_insert_bytes;
4212
4213                 if (!(pos & ((1 << fragp->fr_offset) - 1)))
4214                   /* This alignment requirement is already met.  */
4215                   continue;
4216
4217                 /* As described above, we should always have met an
4218                    alignment requirement by the time we come back to
4219                    it.  */
4220                 if (want_insert)
4221                   abort ();
4222
4223                 /* We may not be able to meet this requirement within
4224                    the given number of characters.  */
4225                 would_insert_bytes
4226                   = ((1 << fragp->fr_offset)
4227                      - (pos & ((1 << fragp->fr_offset) - 1)));
4228
4229                 if (fragp->fr_subtype != 0
4230                     && would_insert_bytes > fragp->fr_subtype)
4231                   continue;
4232
4233                 /* An unmet alignment must be 8, 16 or 32 bytes;
4234                    smaller ones must always be met within code-only
4235                    sections and larger ones cause the section not to
4236                    be code-only.  */
4237                 if (fragp->fr_offset != 3
4238                     && fragp->fr_offset != 4
4239                     && fragp->fr_offset != 5)
4240                   abort ();
4241
4242                 if (would_insert_bytes & 3)
4243                   abort ();
4244                 want_insert = would_insert_bytes >> 2;
4245                 if (want_insert > 7)
4246                   abort ();
4247                 want_insert_done_so_far = 0;
4248                 go_back = TRUE;
4249               }
4250             else if (want_insert && !go_back)
4251               {
4252                 unsigned int num_insns = fragp->fr_fix >> 2;
4253                 unsigned int max_poss_nops = 8 - num_insns;
4254
4255                 if (max_poss_nops)
4256                   {
4257                     unsigned int cur_want_nops, max_want_nops, do_nops, i;
4258
4259                     if (want_insert & 1)
4260                       cur_want_nops = 1;
4261                     else if (want_insert & 2)
4262                       cur_want_nops = 2;
4263                     else if (want_insert & 4)
4264                       cur_want_nops = 4;
4265                     else
4266                       abort ();
4267
4268                     max_want_nops = cur_want_nops - want_insert_done_so_far;
4269
4270                     do_nops = (max_poss_nops < max_want_nops
4271                                ? max_poss_nops
4272                                : max_want_nops);
4273                     for (i = 0; i < do_nops; i++)
4274                       {
4275                         md_number_to_chars (fragp->fr_literal + fragp->fr_fix,
4276                                             0, 4);
4277                         if (target_big_endian)
4278                           fragp->fr_literal[fragp->fr_fix - 1] |= 0x1;
4279                         else
4280                           fragp->fr_literal[fragp->fr_fix - 4] |= 0x1;
4281                         fragp->fr_fix += 4;
4282                         fragp->fr_var -= 4;
4283                       }
4284                     want_insert_done_so_far += do_nops;
4285                     if (want_insert_done_so_far == cur_want_nops)
4286                       {
4287                         want_insert -= want_insert_done_so_far;
4288                         want_insert_done_so_far = 0;
4289                         if (want_insert)
4290                           go_back = TRUE;
4291                       }
4292                   }
4293               }
4294             if (go_back)
4295               {
4296                 if (want_insert & 1)
4297                   {
4298                     frchp = frchp_last8;
4299                     fragp = fragp_last8;
4300                     pos = pos_last8;
4301                   }
4302                 else if (want_insert & 2)
4303                   {
4304                     frchp = frchp_last8 = frchp_last16;
4305                     fragp = fragp_last8 = fragp_last16;
4306                     pos = pos_last8 = pos_last16;
4307                   }
4308                 else if (want_insert & 4)
4309                   {
4310                     frchp = frchp_last8 = frchp_last16 = frchp_last32;
4311                     fragp = fragp_last8 = fragp_last16 = fragp_last32;
4312                     pos = pos_last8 = pos_last16 = pos_last32;
4313                   }
4314                 else
4315                   abort ();
4316
4317                 goto look_at_frag;
4318               }
4319
4320             /* Update current position for moving past a code
4321                frag.  */
4322             pos += fragp->fr_fix;
4323             pos &= 31;
4324             frchp_next = frchp;
4325             fragp_next = fragp->fr_next;
4326             if (fragp_next == NULL)
4327               {
4328                 frchp_next = frchp->frch_next;
4329                 if (frchp_next != NULL)
4330                   fragp_next = frchp_next->frch_root;
4331               }
4332             if (!(pos & 7))
4333               {
4334                 frchp_last8 = frchp_next;
4335                 fragp_last8 = fragp_next;
4336                 pos_last8 = pos;
4337               }
4338             if (!(pos & 15))
4339               {
4340                 frchp_last16 = frchp_next;
4341                 fragp_last16 = fragp_next;
4342                 pos_last16 = pos;
4343               }
4344             if (!(pos & 31))
4345               {
4346                 frchp_last32 = frchp_next;
4347                 fragp_last32 = fragp_next;
4348                 pos_last32 = pos;
4349               }
4350           }
4351     }
4352
4353   /* Now convert the machine-dependent frags to machine-independent
4354      ones.  */
4355   for (frchp = info->frchainP; frchp; frchp = frchp->frch_next)
4356     for (fragp = frchp->frch_root; fragp; fragp = fragp->fr_next)
4357       {
4358         if (fragp->fr_type == rs_machine_dependent)
4359           {
4360             if (fragp->tc_frag_data.is_insns)
4361               frag_wane (fragp);
4362             else
4363               {
4364                 fragp->fr_type = rs_align_code;
4365                 fragp->fr_var = 1;
4366                 *fragp->fr_literal = 0;
4367               }
4368           }
4369       }
4370 }
4371
4372 /* Initialize the machine-dependent parts of a frag.  */
4373
4374 void
4375 tic6x_frag_init (fragS *fragp)
4376 {
4377   fragp->tc_frag_data.is_insns = FALSE;
4378   fragp->tc_frag_data.can_cross_fp_boundary = FALSE;
4379 }
4380
4381 /* Set an attribute if it has not already been set by the user.  */
4382
4383 static void
4384 tic6x_set_attribute_int (int tag, int value)
4385 {
4386   if (tag < 1
4387       || tag >= NUM_KNOWN_OBJ_ATTRIBUTES)
4388     abort ();
4389   if (!tic6x_attributes_set_explicitly[tag])
4390     bfd_elf_add_proc_attr_int (stdoutput, tag, value);
4391 }
4392
4393 /* Set object attributes deduced from the input file and command line
4394    rather than given explicitly.  */
4395 static void
4396 tic6x_set_attributes (void)
4397 {
4398   if (tic6x_arch_attribute == C6XABI_Tag_ISA_none)
4399     tic6x_arch_attribute = C6XABI_Tag_ISA_C674X;
4400
4401   tic6x_set_attribute_int (Tag_ISA, tic6x_arch_attribute);
4402   tic6x_set_attribute_int (Tag_ABI_DSBT, tic6x_dsbt);
4403   tic6x_set_attribute_int (Tag_ABI_PID, tic6x_pid);
4404   tic6x_set_attribute_int (Tag_ABI_PIC, tic6x_pic);
4405 }
4406
4407 /* Do machine-dependent manipulations of the frag chains after all
4408    input has been read and before the machine-independent sizing and
4409    relaxing.  */
4410
4411 void
4412 tic6x_end (void)
4413 {
4414   /* Set object attributes at this point if not explicitly set.  */
4415   tic6x_set_attributes ();
4416
4417   /* Meeting alignment requirements may require inserting NOPs in
4418      parallel in execute packets earlier in the segment.  Future
4419      16-bit instruction generation involves whole-segment optimization
4420      to determine the best choice and ordering of 32-bit or 16-bit
4421      instructions.  This doesn't fit will in the general relaxation
4422      framework, so handle alignment and 16-bit instruction generation
4423      here.  */
4424   bfd_map_over_sections (stdoutput, tic6x_adjust_section, NULL);
4425 }
4426
4427 /* No machine-dependent frags at this stage; all converted in
4428    tic6x_end.  */
4429
4430 void
4431 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT asec ATTRIBUTE_UNUSED,
4432                  fragS *fragp ATTRIBUTE_UNUSED)
4433 {
4434   abort ();
4435 }
4436
4437 /* No machine-dependent frags at this stage; all converted in
4438    tic6x_end.  */
4439
4440 int
4441 md_estimate_size_before_relax (fragS *fragp ATTRIBUTE_UNUSED,
4442                                segT seg ATTRIBUTE_UNUSED)
4443 {
4444   abort ();
4445 }
4446
4447 /* Put a number into target byte order.  */
4448
4449 void
4450 md_number_to_chars (char *buf, valueT val, int n)
4451 {
4452   if (target_big_endian)
4453     number_to_chars_bigendian (buf, val, n);
4454   else
4455     number_to_chars_littleendian (buf, val, n);
4456 }
4457
4458 /* Machine-dependent operand parsing not currently needed.  */
4459
4460 void
4461 md_operand (expressionS *op ATTRIBUTE_UNUSED)
4462 {
4463 }
4464
4465 /* PC-relative operands are relative to the start of the fetch
4466    packet.  */
4467
4468 long
4469 tic6x_pcrel_from_section (fixS *fixp, segT sec)
4470 {
4471   if (fixp->fx_addsy != NULL
4472       && (!S_IS_DEFINED (fixp->fx_addsy)
4473           || S_GET_SEGMENT (fixp->fx_addsy) != sec))
4474     return 0;
4475   return (fixp->fx_where + fixp->fx_frag->fr_address) & ~(long) 0x1f;
4476 }
4477
4478 /* Round up a section size to the appropriate boundary.  */
4479
4480 valueT
4481 md_section_align (segT segment ATTRIBUTE_UNUSED,
4482                   valueT size)
4483 {
4484   /* Round up section sizes to ensure that text sections consist of
4485      whole fetch packets.  */
4486   int align = bfd_get_section_alignment (stdoutput, segment);
4487   return ((size + (1 << align) - 1) & (-((valueT) 1 << align)));
4488 }
4489
4490 /* No special undefined symbol handling needed for now.  */
4491
4492 symbolS *
4493 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
4494 {
4495   return NULL;
4496 }
4497
4498 /* Translate internal representation of relocation info to BFD target
4499    format.  */
4500
4501 arelent *
4502 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
4503 {
4504   arelent *reloc;
4505   asymbol *symbol;
4506   bfd_reloc_code_real_type r_type;
4507
4508   reloc = XNEW (arelent);
4509   reloc->sym_ptr_ptr = XNEW (asymbol *);
4510   symbol = symbol_get_bfdsym (fixp->fx_addsy);
4511   *reloc->sym_ptr_ptr = symbol;
4512   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
4513   reloc->addend = (tic6x_generate_rela ? fixp->fx_offset : 0);
4514   r_type = fixp->fx_r_type;
4515   reloc->howto = bfd_reloc_type_lookup (stdoutput, r_type);
4516
4517   if (reloc->howto == NULL)
4518     {
4519       as_bad_where (fixp->fx_file, fixp->fx_line,
4520                     _("Cannot represent relocation type %s"),
4521                     bfd_get_reloc_code_name (r_type));
4522       return NULL;
4523     }
4524
4525   /* Correct for adjustments bfd_install_relocation will make.  */
4526   if (reloc->howto->pcrel_offset && reloc->howto->partial_inplace)
4527     {
4528       reloc->addend += reloc->address;
4529       if (!bfd_is_com_section (symbol))
4530         reloc->addend -= symbol->value;
4531     }
4532   if (r_type == BFD_RELOC_C6000_PCR_H16
4533       || r_type == BFD_RELOC_C6000_PCR_L16)
4534     {
4535       symbolS *t = fixp->tc_fix_data.fix_subsy;
4536       segT sub_symbol_segment;
4537
4538       resolve_symbol_value (t);
4539       sub_symbol_segment = S_GET_SEGMENT (t);
4540       if (sub_symbol_segment == undefined_section)
4541         as_bad_where (fixp->fx_file, fixp->fx_line,
4542                       _("undefined symbol %s in PCR relocation"),
4543                       S_GET_NAME (t));
4544       else
4545         {
4546           reloc->addend = reloc->address & ~0x1F;
4547           reloc->addend -= S_GET_VALUE (t);
4548         }
4549     }
4550   return reloc;
4551 }
4552
4553 /* Convert REGNAME to a DWARF-2 register number.  */
4554
4555 int
4556 tic6x_regname_to_dw2regnum (char *regname)
4557 {
4558   bfd_boolean reg_ok;
4559   tic6x_register reg;
4560   char *rq = regname;
4561
4562   reg_ok = tic6x_parse_register (&rq, &reg);
4563
4564   if (!reg_ok)
4565     return -1;
4566
4567   switch (reg.side)
4568     {
4569     case 1: /* A regs.  */
4570       if (reg.num < 16)
4571         return reg.num;
4572       else if (reg.num < 32)
4573         return (reg.num - 16) + 37;
4574       else
4575         return -1;
4576
4577     case 2: /* B regs.  */
4578       if (reg.num < 16)
4579         return reg.num + 16;
4580       else if (reg.num < 32)
4581         return (reg.num - 16) + 53;
4582       else
4583         return -1;
4584
4585     default:
4586       return -1;
4587     }
4588 }
4589
4590 /* Initialize the DWARF-2 unwind information for this procedure.  */
4591
4592 void
4593 tic6x_frame_initial_instructions (void)
4594 {
4595   /* CFA is initial stack pointer (B15).  */
4596   cfi_add_CFA_def_cfa (31, 0);
4597 }
4598
4599 /* Start an exception table entry.  If idx is nonzero this is an index table
4600    entry.  */
4601
4602 static void
4603 tic6x_start_unwind_section (const segT text_seg, int idx)
4604 {
4605   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4606   const char * text_name;
4607   const char * prefix;
4608   const char * prefix_once;
4609   const char * group_name;
4610   size_t prefix_len;
4611   size_t text_len;
4612   char * sec_name;
4613   size_t sec_name_len;
4614   int type;
4615   int flags;
4616   int linkonce;
4617
4618   if (idx)
4619     {
4620       prefix = ELF_STRING_C6000_unwind;
4621       prefix_once = ELF_STRING_C6000_unwind_once;
4622       type = SHT_C6000_UNWIND;
4623     }
4624   else
4625     {
4626       prefix = ELF_STRING_C6000_unwind_info;
4627       prefix_once = ELF_STRING_C6000_unwind_info_once;
4628       type = SHT_PROGBITS;
4629     }
4630
4631   text_name = segment_name (text_seg);
4632   if (streq (text_name, ".text"))
4633     text_name = "";
4634
4635   if (strncmp (text_name, ".gnu.linkonce.t.",
4636                strlen (".gnu.linkonce.t.")) == 0)
4637     {
4638       prefix = prefix_once;
4639       text_name += strlen (".gnu.linkonce.t.");
4640     }
4641
4642   prefix_len = strlen (prefix);
4643   text_len = strlen (text_name);
4644   sec_name_len = prefix_len + text_len;
4645   sec_name = XNEWVEC (char, sec_name_len + 1);
4646   memcpy (sec_name, prefix, prefix_len);
4647   memcpy (sec_name + prefix_len, text_name, text_len);
4648   sec_name[prefix_len + text_len] = '\0';
4649
4650   flags = SHF_ALLOC;
4651   linkonce = 0;
4652   group_name = 0;
4653
4654   /* Handle COMDAT group.  */
4655   if (prefix != prefix_once && (text_seg->flags & SEC_LINK_ONCE) != 0)
4656     {
4657       group_name = elf_group_name (text_seg);
4658       if (group_name == NULL)
4659         {
4660           as_bad (_("group section `%s' has no group signature"),
4661                   segment_name (text_seg));
4662           ignore_rest_of_line ();
4663           return;
4664         }
4665       flags |= SHF_GROUP;
4666       linkonce = 1;
4667     }
4668
4669   obj_elf_change_section (sec_name, type, 0, flags, 0, group_name,
4670                           linkonce, 0);
4671
4672   /* Set the section link for index tables.  */
4673   if (idx)
4674     elf_linked_to_section (now_seg) = text_seg;
4675
4676   seg_info (now_seg)->tc_segment_info_data.text_unwind = unwind;
4677 }
4678
4679
4680 static const int
4681 tic6x_unwind_frame_regs[TIC6X_NUM_UNWIND_REGS] =
4682 /* A15 B15 B14 B13 B12 B11 B10  B3 A14 A13 A12 A11 A10.  */
4683   { 15, 31, 30, 29, 28, 27, 26, 19, 14, 13, 12, 11, 10 };
4684
4685 /* Register save offsets for __c6xabi_push_rts.  */
4686 static const int
4687 tic6x_pop_rts_offset_little[TIC6X_NUM_UNWIND_REGS] =
4688 /* A15 B15 B14 B13 B12 B11 B10  B3 A14 A13 A12 A11 A10.  */
4689   { -1,  1,  0, -3, -4, -7, -8,-11, -2, -5, -6, -9,-10};
4690
4691 static const int
4692 tic6x_pop_rts_offset_big[TIC6X_NUM_UNWIND_REGS] =
4693 /* A15 B15 B14 B13 B12 B11 B10  B3 A14 A13 A12 A11 A10.  */
4694   { -2,  1,  0, -4, -3, -8, -7,-12, -1, -6, -5,-10, -9};
4695
4696 /* Map from dwarf register number to unwind frame register number.  */
4697 static int
4698 tic6x_unwind_reg_from_dwarf (int dwarf)
4699 {
4700   int reg;
4701
4702   for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
4703     {
4704       if (tic6x_unwind_frame_regs[reg] == dwarf)
4705         return reg;
4706     }
4707
4708   return -1;
4709 }
4710
4711 /* Unwinding bytecode definitions.  */
4712 #define UNWIND_OP_ADD_SP  0x00
4713 #define UNWIND_OP_ADD_SP2 0xd2
4714 #define UNWIND_OP2_POP 0x8000
4715 #define UNWIND_OP2_POP_COMPACT 0xa000
4716 #define UNWIND_OP_POP_REG 0xc0
4717 #define UNWIND_OP_MV_FP 0xd0
4718 #define UNWIND_OP_POP_RTS 0xd1
4719 #define UNWIND_OP_RET 0xe0
4720
4721 /* Maximum stack adjustment for __c6xabi_unwind_cpp_pr3/4 */
4722 #define MAX_COMPACT_SP_OFFSET (0x7f << 3)
4723
4724 static void
4725 tic6x_flush_unwind_word (valueT data)
4726 {
4727   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4728   char *ptr;
4729
4730   /* Create EXTAB entry if it does not exist.  */
4731   if (unwind->table_entry == NULL)
4732     {
4733       tic6x_start_unwind_section (unwind->saved_seg, 0);
4734       frag_align (2, 0, 0);
4735       record_alignment (now_seg, 2);
4736       unwind->table_entry = expr_build_dot ();
4737       ptr = frag_more (4);
4738       unwind->frag_start = ptr;
4739     }
4740   else
4741     {
4742       /* Append additional word of data.  */
4743       ptr = frag_more (4);
4744     }
4745
4746   md_number_to_chars (ptr, data, 4);
4747 }
4748
4749 /* Add a single byte of unwinding data.  */
4750
4751 static void
4752 tic6x_unwind_byte (int byte)
4753 {
4754   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4755
4756   unwind->data_bytes++;
4757   /* Only flush the first word after we know multiple words are required.  */
4758   if (unwind->data_bytes == 5)
4759     {
4760       if (unwind->personality_index == -1)
4761         {
4762           /* At this point we know we are too big for pr0.  */
4763           unwind->personality_index = 1;
4764           tic6x_flush_unwind_word (0x81000000 | ((unwind->data >> 8) & 0xffff));
4765           unwind->data = ((unwind->data & 0xff) << 8) | byte;
4766           unwind->data_bytes++;
4767         }
4768       else
4769         {
4770           tic6x_flush_unwind_word (unwind->data);
4771           unwind->data = byte;
4772         }
4773     }
4774   else
4775     {
4776       unwind->data = (unwind->data << 8) | byte;
4777       if ((unwind->data_bytes & 3) == 0 && unwind->data_bytes > 4)
4778         {
4779           tic6x_flush_unwind_word (unwind->data);
4780           unwind->data = 0;
4781         }
4782     }
4783 }
4784
4785 /* Add a two-byte unwinding opcode.  */
4786 static void
4787 tic6x_unwind_2byte (int bytes)
4788 {
4789   tic6x_unwind_byte (bytes >> 8);
4790   tic6x_unwind_byte (bytes & 0xff);
4791 }
4792
4793 static void
4794 tic6x_unwind_uleb (offsetT offset)
4795 {
4796   while (offset > 0x7f)
4797     {
4798       tic6x_unwind_byte ((offset & 0x7f) | 0x80);
4799       offset >>= 7;
4800     }
4801   tic6x_unwind_byte (offset);
4802 }
4803
4804 void
4805 tic6x_cfi_startproc (void)
4806 {
4807   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4808
4809   unwind->personality_index = -1;
4810   unwind->personality_routine = NULL;
4811   if (unwind->table_entry)
4812     as_bad (_("missing .endp before .cfi_startproc"));
4813
4814   unwind->table_entry = NULL;
4815   unwind->data_bytes = -1;
4816 }
4817
4818 static void
4819 tic6x_output_exidx_entry (void)
4820 {
4821   char *ptr;
4822   long where;
4823   unsigned int marked_pr_dependency;
4824   segT old_seg;
4825   subsegT old_subseg;
4826   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4827
4828   old_seg = now_seg;
4829   old_subseg = now_subseg;
4830
4831   /* Add index table entry.  This is two words.  */
4832   tic6x_start_unwind_section (unwind->saved_seg, 1);
4833   frag_align (2, 0, 0);
4834   record_alignment (now_seg, 2);
4835
4836   ptr = frag_more (8);
4837   memset (ptr, 0, 8);
4838   where = frag_now_fix () - 8;
4839
4840   /* Self relative offset of the function start.  */
4841   fix_new (frag_now, where, 4, unwind->function_start, 0, 1,
4842            BFD_RELOC_C6000_PREL31);
4843
4844   /* Indicate dependency on ABI-defined personality routines to the
4845      linker, if it hasn't been done already.  */
4846   marked_pr_dependency
4847     = seg_info (now_seg)->tc_segment_info_data.marked_pr_dependency;
4848   if (unwind->personality_index >= 0 && unwind->personality_index < 5
4849       && !(marked_pr_dependency & (1 << unwind->personality_index)))
4850     {
4851       static const char *const name[] =
4852         {
4853           "__c6xabi_unwind_cpp_pr0",
4854           "__c6xabi_unwind_cpp_pr1",
4855           "__c6xabi_unwind_cpp_pr2",
4856           "__c6xabi_unwind_cpp_pr3",
4857           "__c6xabi_unwind_cpp_pr4"
4858         };
4859       symbolS *pr = symbol_find_or_make (name[unwind->personality_index]);
4860       fix_new (frag_now, where, 0, pr, 0, 1, BFD_RELOC_NONE);
4861       seg_info (now_seg)->tc_segment_info_data.marked_pr_dependency
4862         |= 1 << unwind->personality_index;
4863     }
4864
4865   if (unwind->table_entry)
4866     {
4867       /* Self relative offset of the table entry.        */
4868       fix_new (frag_now, where + 4, 4, unwind->table_entry, 0, 1,
4869                BFD_RELOC_C6000_PREL31);
4870     }
4871   else
4872     {
4873       /* Inline exception table entry.  */
4874       md_number_to_chars (ptr + 4, unwind->data, 4);
4875     }
4876
4877   /* Restore the original section.  */
4878   subseg_set (old_seg, old_subseg);
4879 }
4880
4881 static void
4882 tic6x_output_unwinding (bfd_boolean need_extab)
4883 {
4884   tic6x_unwind_info *unwind = tic6x_get_unwind ();
4885   unsigned safe_mask = unwind->safe_mask;
4886   unsigned compact_mask = unwind->compact_mask;
4887   unsigned reg_saved_mask = unwind->reg_saved_mask;
4888   offsetT cfa_offset = unwind->cfa_offset;
4889   long where;
4890   int reg;
4891
4892   if (unwind->personality_index == -2)
4893     {
4894       /* Function can not be unwound.  */
4895       unwind->data = 1;
4896       tic6x_output_exidx_entry ();
4897       return;
4898     }
4899
4900   if (unwind->personality_index == -1 && unwind->personality_routine == NULL)
4901     {
4902       /* Auto-select a personality routine if none specified.  */
4903       if (reg_saved_mask || cfa_offset >= MAX_COMPACT_SP_OFFSET)
4904         unwind->personality_index = -1;
4905       else if (safe_mask)
4906         unwind->personality_index = 3;
4907       else
4908         unwind->personality_index = 4;
4909     }
4910
4911   /* Calculate unwinding opcodes, and emit to EXTAB if necessary.  */
4912   unwind->table_entry = NULL;
4913   if (unwind->personality_index == 3 || unwind->personality_index == 4)
4914     {
4915       if (cfa_offset >= MAX_COMPACT_SP_OFFSET)
4916         {
4917           as_bad (_("stack pointer offset too large for personality routine"));
4918           return;
4919         }
4920       if (reg_saved_mask
4921           || (unwind->personality_index == 3 && compact_mask != 0)
4922           || (unwind->personality_index == 4 && safe_mask != 0))
4923         {
4924           as_bad (_("stack frame layout does not match personality routine"));
4925           return;
4926         }
4927
4928       unwind->data = (1u << 31) | (unwind->personality_index << 24);
4929       if (unwind->cfa_reg == 15)
4930         unwind->data |= 0x7f << 17;
4931       else
4932         unwind->data |= cfa_offset << (17 - 3);
4933
4934       if (unwind->personality_index == 3)
4935         unwind->data |= safe_mask << 4;
4936       else
4937         unwind->data |= compact_mask << 4;
4938       unwind->data |= unwind->return_reg;
4939       unwind->data_bytes = 4;
4940     }
4941   else
4942     {
4943       if (unwind->personality_routine)
4944         {
4945           unwind->data = 0;
4946           unwind->data_bytes = 5;
4947           tic6x_flush_unwind_word (0);
4948           /* First word is personality routine.  */
4949           where = frag_now_fix () - 4;
4950           fix_new (frag_now, where, 4, unwind->personality_routine, 0, 1,
4951                    BFD_RELOC_C6000_PREL31);
4952         }
4953       else if (unwind->personality_index > 0)
4954         {
4955           unwind->data = 0x8000 | (unwind->personality_index << 8);
4956           unwind->data_bytes = 2;
4957         }
4958       else /* pr0 or undecided */
4959         {
4960           unwind->data = 0x80;
4961           unwind->data_bytes = 1;
4962         }
4963
4964       if (unwind->return_reg != UNWIND_B3)
4965         {
4966           tic6x_unwind_byte (UNWIND_OP_RET | unwind->return_reg);
4967         }
4968
4969       if (unwind->cfa_reg == 15)
4970         {
4971           tic6x_unwind_byte (UNWIND_OP_MV_FP);
4972         }
4973       else if (cfa_offset != 0)
4974         {
4975           cfa_offset >>= 3;
4976           if (cfa_offset > 0x80)
4977             {
4978               tic6x_unwind_byte (UNWIND_OP_ADD_SP2);
4979               tic6x_unwind_uleb (cfa_offset - 0x81);
4980             }
4981           else if (cfa_offset > 0x40)
4982             {
4983               tic6x_unwind_byte (UNWIND_OP_ADD_SP | 0x3f);
4984               tic6x_unwind_byte (UNWIND_OP_ADD_SP | (cfa_offset - 0x40));
4985             }
4986           else
4987             {
4988               tic6x_unwind_byte (UNWIND_OP_ADD_SP | (cfa_offset - 1));
4989             }
4990         }
4991
4992       if (safe_mask)
4993         tic6x_unwind_2byte (UNWIND_OP2_POP | unwind->safe_mask);
4994       else if (unwind->pop_rts)
4995         tic6x_unwind_byte (UNWIND_OP_POP_RTS);
4996       else if (compact_mask)
4997         tic6x_unwind_2byte (UNWIND_OP2_POP_COMPACT | unwind->compact_mask);
4998       else if (reg_saved_mask)
4999         {
5000           offsetT cur_offset;
5001           int val;
5002           int last_val;
5003
5004           tic6x_unwind_byte (UNWIND_OP_POP_REG | unwind->saved_reg_count);
5005           last_val = 0;
5006           for (cur_offset = 0; unwind->saved_reg_count > 0; cur_offset -= 4)
5007             {
5008               val = 0xf;
5009               for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5010                 {
5011                   if (!unwind->reg_saved[reg])
5012                     continue;
5013
5014                   if (unwind->reg_offset[reg] == cur_offset)
5015                     {
5016                       unwind->saved_reg_count--;
5017                       val = reg;
5018                       break;
5019                     }
5020                 }
5021               if ((cur_offset & 4) == 4)
5022                 tic6x_unwind_byte ((last_val << 4) | val);
5023               else
5024                 last_val = val;
5025             }
5026           if ((cur_offset & 4) == 4)
5027             tic6x_unwind_byte ((last_val << 4) | 0xf);
5028         }
5029
5030       /* Pad with RETURN opcodes.  */
5031       while ((unwind->data_bytes & 3) != 0)
5032         tic6x_unwind_byte (UNWIND_OP_RET | UNWIND_B3);
5033
5034       if (unwind->personality_index == -1 && unwind->personality_routine == NULL)
5035         unwind->personality_index = 0;
5036     }
5037
5038   /* Force creation of an EXTAB entry if an LSDA is required.  */
5039   if (need_extab && !unwind->table_entry)
5040     {
5041       if (unwind->data_bytes != 4)
5042         abort ();
5043
5044       tic6x_flush_unwind_word (unwind->data);
5045     }
5046   else if (unwind->table_entry && !need_extab)
5047     {
5048       /* Add an empty descriptor if there is no user-specified data.   */
5049       char *ptr = frag_more (4);
5050       md_number_to_chars (ptr, 0, 4);
5051     }
5052
5053   /* Fill in length of unwinding bytecode.  */
5054   if (unwind->table_entry)
5055     {
5056       valueT tmp;
5057       if (unwind->data_bytes > 0x400)
5058         as_bad (_("too many unwinding instructions"));
5059
5060       if (unwind->personality_index == -1)
5061         {
5062           tmp = md_chars_to_number (unwind->frag_start + 4, 4);
5063           tmp |= ((unwind->data_bytes - 8) >> 2) << 24;
5064           md_number_to_chars (unwind->frag_start + 4, tmp, 4);
5065         }
5066       else if (unwind->personality_index == 1 || unwind->personality_index == 2)
5067         {
5068           tmp = md_chars_to_number (unwind->frag_start, 4);
5069           tmp |= ((unwind->data_bytes - 4) >> 2) << 16;
5070           md_number_to_chars (unwind->frag_start, tmp, 4);
5071         }
5072     }
5073   tic6x_output_exidx_entry ();
5074 }
5075
5076 /* FIXME: This will get horribly confused if cfi directives are emitted for
5077    function epilogue.  */
5078 void
5079 tic6x_cfi_endproc (struct fde_entry *fde)
5080 {
5081   tic6x_unwind_info *unwind = tic6x_get_unwind ();
5082   struct cfi_insn_data *insn;
5083   int reg;
5084   unsigned safe_mask = 0;
5085   unsigned compact_mask = 0;
5086   unsigned reg_saved_mask = 0;
5087   offsetT cfa_offset = 0;
5088   offsetT save_offset = 0;
5089
5090   unwind->cfa_reg = 31;
5091   unwind->return_reg = UNWIND_B3;
5092   unwind->saved_reg_count = 0;
5093   unwind->pop_rts = FALSE;
5094
5095   unwind->saved_seg = now_seg;
5096   unwind->saved_subseg = now_subseg;
5097
5098   for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5099     unwind->reg_saved[reg] = FALSE;
5100
5101   /* Scan FDE instructions to build up stack frame layout.  */
5102   for (insn = fde->data; insn; insn = insn->next)
5103     {
5104       switch (insn->insn)
5105         {
5106         case DW_CFA_advance_loc:
5107           break;
5108
5109         case DW_CFA_def_cfa:
5110           unwind->cfa_reg = insn->u.ri.reg;
5111           cfa_offset = insn->u.ri.offset;
5112           break;
5113
5114         case DW_CFA_def_cfa_register:
5115           unwind->cfa_reg = insn->u.r;
5116           break;
5117
5118         case DW_CFA_def_cfa_offset:
5119           cfa_offset = insn->u.i;
5120           break;
5121
5122         case DW_CFA_undefined:
5123         case DW_CFA_same_value:
5124           reg = tic6x_unwind_reg_from_dwarf (insn->u.r);
5125           if (reg >= 0)
5126             unwind->reg_saved[reg] = FALSE;
5127           break;
5128
5129         case DW_CFA_offset:
5130           reg = tic6x_unwind_reg_from_dwarf (insn->u.ri.reg);
5131           if (reg < 0)
5132             {
5133               as_bad (_("unable to generate unwinding opcode for reg %d"),
5134                       insn->u.ri.reg);
5135               return;
5136             }
5137           unwind->reg_saved[reg] = TRUE;
5138           unwind->reg_offset[reg] = insn->u.ri.offset;
5139           if (insn->u.ri.reg == UNWIND_B3)
5140             unwind->return_reg = UNWIND_B3;
5141           break;
5142
5143         case DW_CFA_register:
5144           if (insn->u.rr.reg1 != 19)
5145             {
5146               as_bad (_("unable to generate unwinding opcode for reg %d"),
5147                       insn->u.rr.reg1);
5148               return;
5149             }
5150
5151           reg = tic6x_unwind_reg_from_dwarf (insn->u.rr.reg2);
5152           if (reg < 0)
5153             {
5154               as_bad (_("unable to generate unwinding opcode for reg %d"),
5155                       insn->u.rr.reg2);
5156               return;
5157             }
5158
5159           unwind->return_reg = reg;
5160           unwind->reg_saved[UNWIND_B3] = FALSE;
5161           if (unwind->reg_saved[reg])
5162             {
5163               as_bad (_("unable to restore return address from "
5164                         "previously restored reg"));
5165               return;
5166             }
5167           break;
5168
5169         case DW_CFA_restore:
5170         case DW_CFA_remember_state:
5171         case DW_CFA_restore_state:
5172         case DW_CFA_GNU_window_save:
5173         case CFI_escape:
5174         case CFI_val_encoded_addr:
5175           as_bad (_("unhandled CFA insn for unwinding (%d)"), insn->insn);
5176           break;
5177
5178         default:
5179           abort ();
5180         }
5181     }
5182
5183   if (unwind->cfa_reg != 15 && unwind->cfa_reg != 31)
5184     {
5185       as_bad (_("unable to generate unwinding opcode for frame pointer reg %d"),
5186               unwind->cfa_reg);
5187       return;
5188     }
5189
5190   if (unwind->cfa_reg == 15)
5191     {
5192       if (cfa_offset != 0)
5193         {
5194           as_bad (_("unable to generate unwinding opcode for "
5195                     "frame pointer offset"));
5196           return;
5197         }
5198     }
5199   else
5200     {
5201       if ((cfa_offset & 7) != 0)
5202         {
5203           as_bad (_("unwound stack pointer not doubleword aligned"));
5204           return;
5205         }
5206     }
5207
5208   for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5209     {
5210       if (unwind->reg_saved[reg])
5211         reg_saved_mask |= 1 << (TIC6X_NUM_UNWIND_REGS - (reg + 1));
5212     }
5213
5214   /* Check for standard "safe debug" frame layout */
5215   if (reg_saved_mask)
5216     {
5217       save_offset = 0;
5218       for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5219         {
5220           if (!unwind->reg_saved[reg])
5221             continue;
5222
5223           if (target_big_endian
5224               && reg < TIC6X_NUM_UNWIND_REGS - 1
5225               && unwind->reg_saved[reg + 1]
5226               && tic6x_unwind_frame_regs[reg]
5227                   == tic6x_unwind_frame_regs[reg + 1] + 1
5228               && (tic6x_unwind_frame_regs[reg] & 1) == 1
5229               && (save_offset & 4) == 4)
5230             {
5231               /* Swapped pair */
5232               if (save_offset != unwind->reg_offset[reg + 1]
5233                   || save_offset - 4 != unwind->reg_offset[reg])
5234                 break;
5235               save_offset -= 8;
5236               reg++;
5237             }
5238           else
5239             {
5240               if (save_offset != unwind->reg_offset[reg])
5241                 break;
5242               save_offset -= 4;
5243             }
5244         }
5245       if (reg == TIC6X_NUM_UNWIND_REGS)
5246         {
5247           safe_mask = reg_saved_mask;
5248           reg_saved_mask = 0;
5249         }
5250     }
5251
5252   /* Check for compact frame layout.  */
5253   if (reg_saved_mask)
5254     {
5255       save_offset = 0;
5256       for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5257         {
5258           int reg2;
5259
5260           if (!unwind->reg_saved[reg])
5261             continue;
5262
5263           if (reg < TIC6X_NUM_UNWIND_REGS - 1)
5264             {
5265               reg2 = reg + 1;
5266
5267               if (!unwind->reg_saved[reg2]
5268                   || tic6x_unwind_frame_regs[reg]
5269                       != tic6x_unwind_frame_regs[reg2] + 1
5270                   || (tic6x_unwind_frame_regs[reg2] & 1) != 0
5271                   || save_offset == 0)
5272                 reg2 = -1;
5273             }
5274           else
5275             reg2 = -1;
5276
5277           if (reg2 >= 0)
5278             {
5279               int high_offset;
5280               if (target_big_endian)
5281                 high_offset = 4; /* lower address = positive stack offset.  */
5282               else
5283                 high_offset = 0;
5284
5285               if (save_offset + 4 - high_offset != unwind->reg_offset[reg]
5286                   || save_offset + high_offset != unwind->reg_offset[reg2])
5287                 {
5288                   break;
5289                 }
5290               reg++;
5291             }
5292           else
5293             {
5294               if (save_offset != unwind->reg_offset[reg])
5295                 break;
5296             }
5297           save_offset -= 8;
5298         }
5299
5300       if (reg == TIC6X_NUM_UNWIND_REGS)
5301         {
5302           compact_mask = reg_saved_mask;
5303           reg_saved_mask = 0;
5304         }
5305     }
5306
5307   /* Check for __c6xabi_pop_rts format */
5308   if (reg_saved_mask == 0x17ff)
5309     {
5310       const int *pop_rts_offset = target_big_endian
5311                                 ? tic6x_pop_rts_offset_big
5312                                 : tic6x_pop_rts_offset_little;
5313
5314       save_offset = 0;
5315       for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5316         {
5317           if (reg == UNWIND_B15)
5318             continue;
5319
5320           if (unwind->reg_offset[reg] != pop_rts_offset[reg] * 4)
5321             break;
5322         }
5323
5324       if (reg == TIC6X_NUM_UNWIND_REGS)
5325         {
5326           unwind->pop_rts = TRUE;
5327           reg_saved_mask = 0;
5328         }
5329     }
5330   /* If all else fails then describe the frame manually.  */
5331   if (reg_saved_mask)
5332     {
5333       save_offset = 0;
5334
5335       for (reg = 0; reg < TIC6X_NUM_UNWIND_REGS; reg++)
5336         {
5337           if (!unwind->reg_saved[reg])
5338             continue;
5339
5340           unwind->saved_reg_count++;
5341           /* Encoding uses 4 bits per word, so size of unwinding opcode data
5342              limits the save area size.  The exact cap will be figured out
5343              later due to overflow, the 0x800 here is just a quick sanity
5344              check to weed out obviously excessive offsets.  */
5345           if (unwind->reg_offset[reg] > 0 || unwind->reg_offset[reg] < -0x800
5346               || (unwind->reg_offset[reg] & 3) != 0)
5347             {
5348               as_bad (_("stack frame layout too complex for unwinder"));
5349               return;
5350             }
5351
5352           if (unwind->reg_offset[reg] < save_offset)
5353             save_offset = unwind->reg_offset[reg] - 4;
5354         }
5355     }
5356
5357   /* Align to 8-byte boundary (stack grows towards negative offsets).  */
5358   save_offset &= ~7;
5359
5360   if (unwind->cfa_reg == 31 && !reg_saved_mask)
5361     {
5362       cfa_offset += save_offset;
5363       if (cfa_offset < 0)
5364         {
5365           as_bad (_("unwound frame has negative size"));
5366           return;
5367         }
5368     }
5369
5370   unwind->safe_mask = safe_mask;
5371   unwind->compact_mask = compact_mask;
5372   unwind->reg_saved_mask = reg_saved_mask;
5373   unwind->cfa_offset = cfa_offset;
5374   unwind->function_start = fde->start_address;
5375 }