1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001-2002 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
60 /*****************************************************************************/
61 /* Helper functions */
62 /*****************************************************************************/
66 static void CS_PrintFunctionHeader (const CodeSeg* S, FILE* F)
67 /* Print a comment with the function signature to the given file */
69 /* Get the associated function */
70 const SymEntry* Func = S->Func;
72 /* If this is a global code segment, do nothing */
75 "; ---------------------------------------------------------------\n"
77 PrintFuncSig (F, Func->Name, Func->Type);
80 "; ---------------------------------------------------------------\n"
87 static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E)
88 /* Move all labels from the label pool to the given entry and remove them
92 /* Transfer the labels if we have any */
94 unsigned LabelCount = CollCount (&S->Labels);
95 for (I = 0; I < LabelCount; ++I) {
98 CodeLabel* L = CollAt (&S->Labels, I);
100 /* Attach it to the entry */
101 CE_AttachLabel (E, L);
104 /* Delete the transfered labels */
105 CollDeleteAll (&S->Labels);
110 static void CS_MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
111 /* Move the labels of the code entry E to the label pool of the code segment */
113 unsigned LabelCount = CE_GetLabelCount (E);
114 while (LabelCount--) {
115 CodeLabel* L = CE_GetLabel (E, LabelCount);
117 CollAppend (&S->Labels, L);
119 CollDeleteAll (&E->Labels);
124 static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash)
125 /* Find the label with the given name. Return the label or NULL if not found */
127 /* Get the first hash chain entry */
128 CodeLabel* L = S->LabelHash[Hash];
130 /* Search the list */
132 if (strcmp (Name, L->Name) == 0) {
143 static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
144 /* Create a new label and insert it into the label hash table */
146 /* Create a new label */
147 CodeLabel* L = NewCodeLabel (Name, Hash);
149 /* Enter the label into the hash table */
150 L->Next = S->LabelHash[L->Hash];
151 S->LabelHash[L->Hash] = L;
153 /* Return the new label */
159 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
160 /* Remove the given code label from the hash list */
162 /* Get the first entry in the hash chain */
163 CodeLabel* List = S->LabelHash[L->Hash];
166 /* First, remove the label from the hash chain */
168 /* First entry in hash chain */
169 S->LabelHash[L->Hash] = L->Next;
171 /* Must search through the chain */
172 while (List->Next != L) {
173 /* If we've reached the end of the chain, something is *really* wrong */
174 CHECK (List->Next != 0);
178 /* The next entry is the one, we have been searching for */
179 List->Next = L->Next;
185 static CodeLabel* CS_AddLabelInternal (CodeSeg* S, const char* Name,
186 void (*ErrorFunc) (const char*, ...))
187 /* Add a code label for the next instruction to follow */
189 /* Calculate the hash from the name */
190 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
192 /* Try to find the code label if it does already exist */
193 CodeLabel* L = CS_FindLabel (S, Name, Hash);
195 /* Did we find it? */
197 /* We found it - be sure it does not already have an owner */
199 ErrorFunc ("ASM label `%s' is already defined", Name);
202 /* Not found - create a new one */
203 L = CS_NewCodeLabel (S, Name, Hash);
206 /* Safety. This call is quite costly, but safety is better */
207 if (CollIndex (&S->Labels, L) >= 0) {
208 ErrorFunc ("ASM label `%s' is already defined", Name);
211 /* We do now have a valid label. Remember it for later */
212 CollAppend (&S->Labels, L);
214 /* Return the label */
220 /*****************************************************************************/
221 /* Functions for parsing instructions */
222 /*****************************************************************************/
226 static const char* SkipSpace (const char* S)
227 /* Skip white space and return an updated pointer */
229 while (IsSpace (*S)) {
237 static const char* ReadToken (const char* L, const char* Term,
238 char* Buf, unsigned BufSize)
239 /* Read the next token into Buf, return the updated line pointer. The
240 * token is terminated by one of the characters given in term.
243 /* Read/copy the token */
245 unsigned ParenCount = 0;
246 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
249 } else if (I == BufSize-1) {
250 /* Cannot store this character, this is an input error (maybe
251 * identifier too long or similar).
253 Error ("ASM code error: syntax error");
258 } else if (*L == '(') {
264 /* Terminate the buffer contents */
267 /* Return the updated line pointer */
273 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
274 /* Parse an instruction nnd generate a code entry from it. If the line contains
275 * errors, output an error message and return NULL.
276 * For simplicity, we don't accept the broad range of input a "real" assembler
277 * does. The instruction and the argument are expected to be separated by
278 * white space, for example.
281 char Mnemo[IDENTSIZE+10];
283 am_t AM = 0; /* Initialize to keep gcc silent */
284 char Arg[IDENTSIZE+10];
289 /* Read the first token and skip white space after it */
290 L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo)));
292 /* Check if we have a label */
295 /* Skip the colon and following white space */
299 CS_AddLabelInternal (S, Mnemo, Error);
301 /* If we have reached end of line, bail out, otherwise a mnemonic
308 L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo)));
311 /* Try to find the opcode description for the mnemonic */
312 OPC = FindOP65 (Mnemo);
314 /* If we didn't find the opcode, print an error and bail out */
316 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
320 /* Get the addressing mode */
331 StrCopy (Arg, sizeof (Arg), L+1);
337 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
339 /* Check for errors */
341 Error ("ASM code error: syntax error");
345 /* Check the different indirect modes */
347 /* Expect zp x indirect */
349 if (toupper (*L) != 'X') {
350 Error ("ASM code error: `X' expected");
355 Error ("ASM code error: `)' expected");
360 Error ("ASM code error: syntax error");
364 } else if (*L == ')') {
365 /* zp indirect or zp indirect, y */
369 if (toupper (*L) != 'Y') {
370 Error ("ASM code error: `Y' expected");
375 Error ("ASM code error: syntax error");
379 } else if (*L == '\0') {
382 Error ("ASM code error: syntax error");
398 /* Absolute, maybe indexed */
399 L = ReadToken (L, ",", Arg, sizeof (Arg));
401 /* Absolute, zeropage or branch */
402 if ((OPC->Info & OF_BRA) != 0) {
405 } else if (GetZPInfo(Arg) != 0) {
410 } else if (*L == ',') {
414 Error ("ASM code error: syntax error");
420 if (GetZPInfo(Arg) != 0) {
425 } else if (Reg == 'Y') {
428 Error ("ASM code error: syntax error");
432 Error ("ASM code error: syntax error");
441 /* If the instruction is a branch, check for the label and generate it
442 * if it does not exist. This may lead to unused labels (if the label
443 * is actually an external one) which are removed by the CS_MergeLabels
447 if (AM == AM65_BRA) {
449 /* Generate the hash over the label, then search for the label */
450 unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
451 Label = CS_FindLabel (S, Arg, Hash);
453 /* If we don't have the label, it's a forward ref - create it */
455 /* Generate a new label */
456 Label = CS_NewCodeLabel (S, Arg, Hash);
460 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
461 * structure and initialize it.
463 E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
465 /* Return the new code entry */
471 /*****************************************************************************/
473 /*****************************************************************************/
477 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
478 /* Create a new code segment, initialize and return it */
483 /* Allocate memory */
484 CodeSeg* S = xmalloc (sizeof (CodeSeg));
486 /* Initialize the fields */
487 S->SegName = xstrdup (SegName);
489 InitCollection (&S->Entries);
490 InitCollection (&S->Labels);
491 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
495 /* If we have a function given, get the return type of the function.
496 * Assume ANY return type besides void will use the A and X registers.
498 if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) {
499 if (SizeOf (RetType) == SizeOf (type_long)) {
500 S->ExitRegs = REG_EAX;
502 S->ExitRegs = REG_AX;
505 S->ExitRegs = REG_NONE;
508 /* Return the new struct */
514 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E)
515 /* Add an entry to the given code segment */
517 /* Transfer the labels if we have any */
518 CS_MoveLabelsToEntry (S, E);
520 /* Add the entry to the list of code entries in this segment */
521 CollAppend (&S->Entries, E);
526 void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
527 /* Add a line to the given code segment */
531 char Token[IDENTSIZE+10];
533 /* Format the line */
535 xvsprintf (Buf, sizeof (Buf), Format, ap);
537 /* Skip whitespace */
540 /* Check which type of instruction we have */
541 E = 0; /* Assume no insn created */
545 /* Empty line, just ignore it */
549 /* Comment or hint, ignore it for now */
553 /* Control instruction */
554 ReadToken (L, " \t", Token, sizeof (Token));
555 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
559 E = ParseInsn (S, LI, L);
563 /* If we have a code entry, transfer the labels and insert it */
571 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...)
572 /* Add a line to the given code segment */
575 va_start (ap, Format);
576 CS_AddVLine (S, LI, Format, ap);
582 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
583 /* Insert the code entry at the index given. Following code entries will be
584 * moved to slots with higher indices.
587 /* Insert the entry into the collection */
588 CollInsert (&S->Entries, E, Index);
593 void CS_DelEntry (CodeSeg* S, unsigned Index)
594 /* Delete an entry from the code segment. This includes moving any associated
595 * labels, removing references to labels and even removing the referenced labels
596 * if the reference count drops to zero.
599 /* Get the code entry for the given index */
600 CodeEntry* E = CS_GetEntry (S, Index);
602 /* If the entry has a labels, we have to move this label to the next insn.
603 * If there is no next insn, move the label into the code segement label
604 * pool. The operation is further complicated by the fact that the next
605 * insn may already have a label. In that case change all reference to
606 * this label and delete the label instead of moving it.
608 unsigned Count = CE_GetLabelCount (E);
611 /* The instruction has labels attached. Check if there is a next
614 if (Index == CS_GetEntryCount (S)-1) {
616 /* No next instruction, move to the codeseg label pool */
617 CS_MoveLabelsToPool (S, E);
621 /* There is a next insn, get it */
622 CodeEntry* N = CS_GetEntry (S, Index+1);
624 /* Move labels to the next entry */
625 CS_MoveLabels (S, E, N);
630 /* If this insn references a label, remove the reference. And, if the
631 * the reference count for this label drops to zero, remove this label.
634 /* Remove the reference */
635 CS_RemoveLabelRef (S, E);
638 /* Delete the pointer to the insn */
639 CollDelete (&S->Entries, Index);
641 /* Delete the instruction itself */
647 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
648 /* Delete a range of code entries. This includes removing references to labels,
649 * labels attached to the entries and so on.
652 /* Start deleting the entries from the rear, because this involves less
656 CS_DelEntry (S, Start + Count);
662 void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos)
663 /* Move a range of entries from one position to another. Start is the index
664 * of the first entry to move, Count is the number of entries and NewPos is
665 * the index of the target entry. The entry with the index Start will later
666 * have the index NewPos. All entries with indices NewPos and above are
667 * moved to higher indices. If the code block is moved to the end of the
668 * current code, and if pending labels exist, these labels will get attached
669 * to the first instruction of the moved block (the first one after the
673 /* If NewPos is at the end of the code segment, move any labels from the
674 * label pool to the first instruction of the moved range.
676 if (NewPos == CS_GetEntryCount (S)) {
677 CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start));
680 /* Move the code block to the destination */
681 CollMoveMultiple (&S->Entries, Start, Count, NewPos);
686 struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index)
687 /* Get the code entry preceeding the one with the index Index. If there is no
688 * preceeding code entry, return NULL.
692 /* This is the first entry */
695 /* Previous entry available */
696 return CollAtUnchecked (&S->Entries, Index-1);
702 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
703 /* Get the code entry following the one with the index Index. If there is no
704 * following code entry, return NULL.
707 if (Index >= CollCount (&S->Entries)-1) {
708 /* This is the last entry */
711 /* Code entries left */
712 return CollAtUnchecked (&S->Entries, Index+1);
718 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
719 unsigned Start, unsigned Count)
720 /* Get Count code entries into List starting at index start. Return true if
721 * we got the lines, return false if not enough lines were available.
724 /* Check if enough entries are available */
725 if (Start + Count > CollCount (&S->Entries)) {
729 /* Copy the entries */
731 *List++ = CollAtUnchecked (&S->Entries, Start++);
734 /* We have the entries */
740 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
741 /* Return the index of a code entry */
743 int Index = CollIndex (&S->Entries, E);
750 int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count)
751 /* Return true if any of the code entries in the given range has a label
752 * attached. If the code segment does not span the given range, check the
753 * possible span instead.
756 unsigned EntryCount = CS_GetEntryCount(S);
758 /* Adjust count. We expect at least Start to be valid. */
759 CHECK (Start < EntryCount);
760 if (Start + Count > EntryCount) {
761 Count = EntryCount - Start;
764 /* Check each entry. Since we have validated the index above, we may
765 * use the unchecked access function in the loop which is faster.
768 const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++);
769 if (CE_HasLabel (E)) {
774 /* No label in the complete range */
780 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
781 /* Add a code label for the next instruction to follow */
783 return CS_AddLabelInternal (S, Name, Internal);
788 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
789 /* If the code entry E does already have a label, return it. Otherwise
790 * create a new label, attach it to E and return it.
795 if (CE_HasLabel (E)) {
797 /* Get the label from this entry */
798 L = CE_GetLabel (E, 0);
803 const char* Name = LocalLabelName (GetLocalLabel ());
805 /* Generate the hash over the name */
806 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
808 /* Create a new label */
809 L = CS_NewCodeLabel (S, Name, Hash);
811 /* Attach this label to the code entry */
812 CE_AttachLabel (E, L);
816 /* Return the label */
822 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
823 /* Remove references from this label and delete it. */
827 /* First, remove the label from the hash chain */
828 CS_RemoveLabelFromHash (S, L);
830 /* Remove references from insns jumping to this label */
831 Count = CollCount (&L->JumpFrom);
832 for (I = 0; I < Count; ++I) {
833 /* Get the insn referencing this label */
834 CodeEntry* E = CollAt (&L->JumpFrom, I);
835 /* Remove the reference */
838 CollDeleteAll (&L->JumpFrom);
840 /* Remove the reference to the owning instruction if it has one. The
841 * function may be called for a label without an owner when deleting
842 * unfinished parts of the code. This is unfortunate since it allows
843 * errors to slip through.
846 CollDeleteItem (&L->Owner->Labels, L);
849 /* All references removed, delete the label itself */
855 void CS_MergeLabels (CodeSeg* S)
856 /* Merge code labels. That means: For each instruction, remove all labels but
857 * one and adjust references accordingly.
863 /* First, remove all labels from the label symbol table that don't have an
864 * owner (this means that they are actually external labels but we didn't
865 * know that previously since they may have also been forward references).
867 for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
869 /* Get the first label in this hash chain */
870 CodeLabel** L = &S->LabelHash[I];
872 if ((*L)->Owner == 0) {
874 /* The label does not have an owner, remove it from the chain */
878 /* Cleanup any entries jumping to this label */
879 for (J = 0; J < CL_GetRefCount (X); ++J) {
880 /* Get the entry referencing this label */
881 CodeEntry* E = CL_GetRef (X, J);
882 /* And remove the reference */
886 /* Print some debugging output */
888 printf ("Removing unused global label `%s'", X->Name);
891 /* And free the label */
894 /* Label is owned, point to next code label pointer */
900 /* Walk over all code entries */
901 for (I = 0; I < CS_GetEntryCount (S); ++I) {
906 /* Get a pointer to the next entry */
907 CodeEntry* E = CS_GetEntry (S, I);
909 /* If this entry has zero labels, continue with the next one */
910 unsigned LabelCount = CE_GetLabelCount (E);
911 if (LabelCount == 0) {
915 /* We have at least one label. Use the first one as reference label. */
916 RefLab = CE_GetLabel (E, 0);
918 /* Walk through the remaining labels and change references to these
919 * labels to a reference to the one and only label. Delete the labels
920 * that are no longer used. To increase performance, walk backwards
923 for (J = LabelCount-1; J >= 1; --J) {
925 /* Get the next label */
926 CodeLabel* L = CE_GetLabel (E, J);
928 /* Move all references from this label to the reference label */
929 CL_MoveRefs (L, RefLab);
931 /* Remove the label completely. */
935 /* The reference label is the only remaining label. Check if there
936 * are any references to this label, and delete it if this is not
939 if (CollCount (&RefLab->JumpFrom) == 0) {
940 /* Delete the label */
941 CS_DelLabel (S, RefLab);
948 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
949 /* Move all labels from Old to New. The routine will move the labels itself
950 * if New does not have any labels, and move references if there is at least
951 * a label for new. If references are moved, the old label is deleted
955 /* Get the number of labels to move */
956 unsigned OldLabelCount = CE_GetLabelCount (Old);
958 /* Does the new entry have itself a label? */
959 if (CE_HasLabel (New)) {
961 /* The new entry does already have a label - move references */
962 CodeLabel* NewLabel = CE_GetLabel (New, 0);
963 while (OldLabelCount--) {
965 /* Get the next label */
966 CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
968 /* Move references */
969 CL_MoveRefs (OldLabel, NewLabel);
971 /* Delete the label */
972 CS_DelLabel (S, OldLabel);
978 /* The new entry does not have a label, just move them */
979 while (OldLabelCount--) {
981 /* Move the label to the new entry */
982 CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
991 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
992 /* Remove the reference between E and the label it jumps to. The reference
993 * will be removed on both sides and E->JumpTo will be 0 after that. If
994 * the reference was the only one for the label, the label will get
998 /* Get a pointer to the label and make sure it exists */
999 CodeLabel* L = E->JumpTo;
1002 /* Delete the entry from the label */
1003 CollDeleteItem (&L->JumpFrom, E);
1005 /* The entry jumps no longer to L */
1008 /* If there are no more references, delete the label */
1009 if (CollCount (&L->JumpFrom) == 0) {
1016 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
1017 /* Change the reference of E to L instead of the current one. If this
1018 * was the only reference to the old label, the old label will get
1022 /* Get the old label */
1023 CodeLabel* OldLabel = E->JumpTo;
1025 /* Be sure that code entry references a label */
1026 PRECONDITION (OldLabel != 0);
1028 /* Remove the reference to our label */
1029 CS_RemoveLabelRef (S, E);
1031 /* Use the new label */
1037 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
1038 /* Delete all entries including the given one */
1040 /* Get the number of entries in this segment */
1041 unsigned Count = CS_GetEntryCount (S);
1043 /* First pass: Delete all references to labels. If the reference count
1044 * for a label drops to zero, delete it.
1047 while (Last < C--) {
1049 /* Get the next entry */
1050 CodeEntry* E = CS_GetEntry (S, C);
1052 /* Check if this entry has a label reference */
1054 /* If the label is a label in the label pool and this is the last
1055 * reference to the label, remove the label from the pool.
1057 CodeLabel* L = E->JumpTo;
1058 int Index = CollIndex (&S->Labels, L);
1059 if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
1060 /* Delete it from the pool */
1061 CollDelete (&S->Labels, Index);
1064 /* Remove the reference to the label */
1065 CS_RemoveLabelRef (S, E);
1070 /* Second pass: Delete the instructions. If a label attached to an
1071 * instruction still has references, it must be references from outside
1072 * the deleted area. Don't delete the label in this case, just make it
1073 * ownerless and move it to the label pool.
1076 while (Last < C--) {
1078 /* Get the next entry */
1079 CodeEntry* E = CS_GetEntry (S, C);
1081 /* Check if this entry has a label attached */
1082 if (CE_HasLabel (E)) {
1083 /* Move the labels to the pool and clear the owner pointer */
1084 CS_MoveLabelsToPool (S, E);
1087 /* Delete the pointer to the entry */
1088 CollDelete (&S->Entries, C);
1090 /* Delete the entry itself */
1097 void CS_OutputPrologue (const CodeSeg* S, FILE* F)
1098 /* If the given code segment is a code segment for a function, output the
1099 * assembler prologue into the file. That is: Output a comment header, switch
1100 * to the correct segment and enter the local function scope. If the code
1101 * segment is global, do nothing.
1104 /* Get the function associated with the code segment */
1105 SymEntry* Func = S->Func;
1107 /* If the code segment is associated with a function, print a function
1108 * header and enter a local scope. Be sure to switch to the correct
1109 * segment before outputing the function label.
1112 CS_PrintFunctionHeader (S, F);
1113 fprintf (F, ".segment\t\"%s\"\n\n.proc\t_%s\n\n", S->SegName, Func->Name);
1120 void CS_OutputEpilogue (const CodeSeg* S, FILE* F)
1121 /* If the given code segment is a code segment for a function, output the
1122 * assembler epilogue into the file. That is: Close the local function scope.
1126 fprintf (F, "\n.endproc\n\n");
1132 void CS_Output (const CodeSeg* S, FILE* F)
1133 /* Output the code segment data to a file */
1138 /* Get the number of entries in this segment */
1139 unsigned Count = CS_GetEntryCount (S);
1141 /* If the code segment is empty, bail out here */
1146 /* Output the segment directive */
1147 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
1149 /* Output all entries, prepended by the line information if it has changed */
1151 for (I = 0; I < Count; ++I) {
1152 /* Get the next entry */
1153 const CodeEntry* E = CollConstAt (&S->Entries, I);
1154 /* Check if the line info has changed. If so, output the source line
1155 * if the option is enabled and output debug line info if the debug
1156 * option is enabled.
1159 /* Line info has changed, remember the new line info */
1162 /* Add the source line as a comment */
1164 fprintf (F, ";\n; %s\n;\n", LI->Line);
1167 /* Add line debug info */
1169 fprintf (F, "\t.dbg\tline, \"%s\", %u\n",
1170 GetInputName (LI), GetInputLine (LI));
1173 /* Output the code */
1177 /* If debug info is enabled, terminate the last line number information */
1179 fprintf (F, "\t.dbg\tline\n");
1185 void CS_FreeRegInfo (CodeSeg* S)
1186 /* Free register infos for all instructions */
1189 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1190 CE_FreeRegInfo (CS_GetEntry(S, I));
1196 void CS_GenRegInfo (CodeSeg* S)
1197 /* Generate register infos for all instructions */
1200 RegContents Regs; /* Initial register contents */
1201 RegContents* CurrentRegs; /* Current register contents */
1202 int WasJump; /* True if last insn was a jump */
1203 int Done; /* All runs done flag */
1205 /* Be sure to delete all register infos */
1208 /* We may need two runs to get back references right */
1211 /* Assume we're done after this run */
1214 /* On entry, the register contents are unknown */
1215 RC_Invalidate (&Regs);
1216 CurrentRegs = &Regs;
1218 /* Walk over all insns and note just the changes from one insn to the
1222 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1226 /* Get the next instruction */
1227 CodeEntry* E = CollAtUnchecked (&S->Entries, I);
1229 /* If the instruction has a label, we need some special handling */
1230 unsigned LabelCount = CE_GetLabelCount (E);
1231 if (LabelCount > 0) {
1233 /* Loop over all entry points that jump here. If these entry
1234 * points already have register info, check if all values are
1235 * known and identical. If all values are identical, and the
1236 * preceeding instruction was not an unconditional branch, check
1237 * if the register value on exit of the preceeding instruction
1238 * is also identical. If all these values are identical, the
1239 * value of a register is known, otherwise it is unknown.
1241 CodeLabel* Label = CE_GetLabel (E, 0);
1244 /* Preceeding insn was an unconditional branch */
1245 CodeEntry* J = CL_GetRef(Label, 0);
1249 RC_Invalidate (&Regs);
1253 Regs = *CurrentRegs;
1257 while (Entry < CL_GetRefCount (Label)) {
1258 /* Get this entry */
1259 CodeEntry* J = CL_GetRef (Label, Entry);
1261 /* No register info for this entry. This means that the
1262 * instruction that jumps here is at higher addresses and
1263 * the jump is a backward jump. We need a second run to
1264 * get the register info right in this case. Until then,
1265 * assume unknown register contents.
1268 RC_Invalidate (&Regs);
1271 if (J->RI->Out2.RegA != Regs.RegA) {
1274 if (J->RI->Out2.RegX != Regs.RegX) {
1277 if (J->RI->Out2.RegY != Regs.RegY) {
1280 if (J->RI->Out2.SRegLo != Regs.SRegLo) {
1283 if (J->RI->Out2.SRegHi != Regs.SRegHi) {
1289 /* Use this register info */
1290 CurrentRegs = &Regs;
1294 /* Generate register info for this instruction */
1295 CE_GenRegInfo (E, CurrentRegs);
1297 /* Remember for the next insn if this insn was an uncondition branch */
1298 WasJump = (E->Info & OF_UBRA) != 0;
1300 /* Output registers for this insn are input for the next */
1301 CurrentRegs = &E->RI->Out;
1303 /* If this insn is a branch on zero flag, we may have more info on
1304 * register contents for one of both flow directions, but only if
1305 * there is a previous instruction.
1307 if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) {
1309 /* Get the branch condition */
1310 bc_t BC = GetBranchCond (E->OPC);
1312 /* Check the previous instruction */
1324 /* A is zero in one execution flow direction */
1326 E->RI->Out2.RegA = 0;
1328 E->RI->Out.RegA = 0;
1333 /* If this is an immidiate compare, the A register has
1334 * the value of the compare later.
1336 if (CE_KnownImm (P)) {
1338 E->RI->Out2.RegA = (unsigned char)P->Num;
1340 E->RI->Out.RegA = (unsigned char)P->Num;
1346 /* If this is an immidiate compare, the X register has
1347 * the value of the compare later.
1349 if (CE_KnownImm (P)) {
1351 E->RI->Out2.RegX = (unsigned char)P->Num;
1353 E->RI->Out.RegX = (unsigned char)P->Num;
1359 /* If this is an immidiate compare, the Y register has
1360 * the value of the compare later.
1362 if (CE_KnownImm (P)) {
1364 E->RI->Out2.RegY = (unsigned char)P->Num;
1366 E->RI->Out.RegY = (unsigned char)P->Num;
1375 /* X is zero in one execution flow direction */
1377 E->RI->Out2.RegX = 0;
1379 E->RI->Out.RegX = 0;
1387 /* X is zero in one execution flow direction */
1389 E->RI->Out2.RegY = 0;
1391 E->RI->Out.RegY = 0;
1397 /* If the branch is a beq, both A and X are zero at the
1398 * branch target, otherwise they are zero at the next
1402 E->RI->Out2.RegA = E->RI->Out2.RegX = 0;
1404 E->RI->Out.RegA = E->RI->Out.RegX = 0;
1410 /* If the branch is a beq, both A and Y are zero at the
1411 * branch target, otherwise they are zero at the next
1415 E->RI->Out2.RegA = E->RI->Out2.RegY = 0;
1417 E->RI->Out.RegA = E->RI->Out.RegY = 0;