1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001-2004 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
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 /*****************************************************************************/
42 #include "debugflag.h"
62 /*****************************************************************************/
63 /* Helper functions */
64 /*****************************************************************************/
68 static void CS_PrintFunctionHeader (const CodeSeg* S, FILE* F)
69 /* Print a comment with the function signature to the given file */
71 /* Get the associated function */
72 const SymEntry* Func = S->Func;
74 /* If this is a global code segment, do nothing */
77 "; ---------------------------------------------------------------\n"
79 PrintFuncSig (F, Func->Name, Func->Type);
82 "; ---------------------------------------------------------------\n"
89 static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E)
90 /* Move all labels from the label pool to the given entry and remove them
94 /* Transfer the labels if we have any */
96 unsigned LabelCount = CollCount (&S->Labels);
97 for (I = 0; I < LabelCount; ++I) {
100 CodeLabel* L = CollAt (&S->Labels, I);
102 /* Attach it to the entry */
103 CE_AttachLabel (E, L);
106 /* Delete the transfered labels */
107 CollDeleteAll (&S->Labels);
112 static void CS_MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
113 /* Move the labels of the code entry E to the label pool of the code segment */
115 unsigned LabelCount = CE_GetLabelCount (E);
116 while (LabelCount--) {
117 CodeLabel* L = CE_GetLabel (E, LabelCount);
119 CollAppend (&S->Labels, L);
121 CollDeleteAll (&E->Labels);
126 static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash)
127 /* Find the label with the given name. Return the label or NULL if not found */
129 /* Get the first hash chain entry */
130 CodeLabel* L = S->LabelHash[Hash];
132 /* Search the list */
134 if (strcmp (Name, L->Name) == 0) {
145 static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
146 /* Create a new label and insert it into the label hash table */
148 /* Create a new label */
149 CodeLabel* L = NewCodeLabel (Name, Hash);
151 /* Enter the label into the hash table */
152 L->Next = S->LabelHash[L->Hash];
153 S->LabelHash[L->Hash] = L;
155 /* Return the new label */
161 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
162 /* Remove the given code label from the hash list */
164 /* Get the first entry in the hash chain */
165 CodeLabel* List = S->LabelHash[L->Hash];
168 /* First, remove the label from the hash chain */
170 /* First entry in hash chain */
171 S->LabelHash[L->Hash] = L->Next;
173 /* Must search through the chain */
174 while (List->Next != L) {
175 /* If we've reached the end of the chain, something is *really* wrong */
176 CHECK (List->Next != 0);
180 /* The next entry is the one, we have been searching for */
181 List->Next = L->Next;
187 /*****************************************************************************/
188 /* Functions for parsing instructions */
189 /*****************************************************************************/
193 static const char* SkipSpace (const char* S)
194 /* Skip white space and return an updated pointer */
196 while (IsSpace (*S)) {
204 static const char* ReadToken (const char* L, const char* Term,
205 char* Buf, unsigned BufSize)
206 /* Read the next token into Buf, return the updated line pointer. The
207 * token is terminated by one of the characters given in term.
210 /* Read/copy the token */
212 unsigned ParenCount = 0;
213 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
216 } else if (I == BufSize-1) {
217 /* Cannot store this character, this is an input error (maybe
218 * identifier too long or similar).
220 Error ("ASM code error: syntax error");
225 } else if (*L == '(') {
231 /* Terminate the buffer contents */
234 /* Return the updated line pointer */
240 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
241 /* Parse an instruction nnd generate a code entry from it. If the line contains
242 * errors, output an error message and return NULL.
243 * For simplicity, we don't accept the broad range of input a "real" assembler
244 * does. The instruction and the argument are expected to be separated by
245 * white space, for example.
248 char Mnemo[IDENTSIZE+10];
250 am_t AM = 0; /* Initialize to keep gcc silent */
251 char Arg[IDENTSIZE+10];
256 /* Read the first token and skip white space after it */
257 L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo)));
259 /* Check if we have a label */
262 /* Skip the colon and following white space */
266 CS_AddLabel (S, Mnemo);
268 /* If we have reached end of line, bail out, otherwise a mnemonic
275 L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo)));
278 /* Try to find the opcode description for the mnemonic */
279 OPC = FindOP65 (Mnemo);
281 /* If we didn't find the opcode, print an error and bail out */
283 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
287 /* Get the addressing mode */
292 /* Implicit or accu */
293 if (OPC->Info & OF_NOIMP) {
302 StrCopy (Arg, sizeof (Arg), L+1);
308 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
310 /* Check for errors */
312 Error ("ASM code error: syntax error");
316 /* Check the different indirect modes */
318 /* Expect zp x indirect */
320 if (toupper (*L) != 'X') {
321 Error ("ASM code error: `X' expected");
326 Error ("ASM code error: `)' expected");
331 Error ("ASM code error: syntax error");
335 } else if (*L == ')') {
336 /* zp indirect or zp indirect, y */
340 if (toupper (*L) != 'Y') {
341 Error ("ASM code error: `Y' expected");
346 Error ("ASM code error: syntax error");
350 } else if (*L == '\0') {
353 Error ("ASM code error: syntax error");
369 /* Absolute, maybe indexed */
370 L = ReadToken (L, ",", Arg, sizeof (Arg));
372 /* Absolute, zeropage or branch */
373 if ((OPC->Info & OF_BRA) != 0) {
376 } else if (GetZPInfo(Arg) != 0) {
381 } else if (*L == ',') {
385 Error ("ASM code error: syntax error");
391 if (GetZPInfo(Arg) != 0) {
396 } else if (Reg == 'Y') {
399 Error ("ASM code error: syntax error");
403 Error ("ASM code error: syntax error");
412 /* If the instruction is a branch, check for the label and generate it
413 * if it does not exist. This may lead to unused labels (if the label
414 * is actually an external one) which are removed by the CS_MergeLabels
418 if (AM == AM65_BRA) {
420 /* Generate the hash over the label, then search for the label */
421 unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
422 Label = CS_FindLabel (S, Arg, Hash);
424 /* If we don't have the label, it's a forward ref - create it */
426 /* Generate a new label */
427 Label = CS_NewCodeLabel (S, Arg, Hash);
431 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
432 * structure and initialize it.
434 E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
436 /* Return the new code entry */
442 /*****************************************************************************/
444 /*****************************************************************************/
448 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
449 /* Create a new code segment, initialize and return it */
454 /* Allocate memory */
455 CodeSeg* S = xmalloc (sizeof (CodeSeg));
457 /* Initialize the fields */
458 S->SegName = xstrdup (SegName);
460 InitCollection (&S->Entries);
461 InitCollection (&S->Labels);
462 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
466 /* If we have a function given, get the return type of the function.
467 * Assume ANY return type besides void will use the A and X registers.
469 if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) {
470 if (SizeOf (RetType) == SizeOf (type_long)) {
471 S->ExitRegs = REG_EAX;
473 S->ExitRegs = REG_AX;
476 S->ExitRegs = REG_NONE;
479 /* Copy the global optimization settings */
480 S->Optimize = (unsigned char) IS_Get (&Optimize);
481 S->CodeSizeFactor = (unsigned) IS_Get (&CodeSizeFactor);
483 /* Return the new struct */
489 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E)
490 /* Add an entry to the given code segment */
492 /* Transfer the labels if we have any */
493 CS_MoveLabelsToEntry (S, E);
495 /* Add the entry to the list of code entries in this segment */
496 CollAppend (&S->Entries, E);
501 void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
502 /* Add a line to the given code segment */
506 char Token[IDENTSIZE+10];
508 /* Format the line */
510 xvsprintf (Buf, sizeof (Buf), Format, ap);
512 /* Skip whitespace */
515 /* Check which type of instruction we have */
516 E = 0; /* Assume no insn created */
520 /* Empty line, just ignore it */
524 /* Comment or hint, ignore it for now */
528 /* Control instruction */
529 ReadToken (L, " \t", Token, sizeof (Token));
530 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
534 E = ParseInsn (S, LI, L);
538 /* If we have a code entry, transfer the labels and insert it */
546 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...)
547 /* Add a line to the given code segment */
550 va_start (ap, Format);
551 CS_AddVLine (S, LI, Format, ap);
557 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
558 /* Insert the code entry at the index given. Following code entries will be
559 * moved to slots with higher indices.
562 /* Insert the entry into the collection */
563 CollInsert (&S->Entries, E, Index);
568 void CS_DelEntry (CodeSeg* S, unsigned Index)
569 /* Delete an entry from the code segment. This includes moving any associated
570 * labels, removing references to labels and even removing the referenced labels
571 * if the reference count drops to zero.
572 * Note: Labels are moved forward if possible, that is, they are moved to the
573 * next insn (not the preceeding one).
576 /* Get the code entry for the given index */
577 CodeEntry* E = CS_GetEntry (S, Index);
579 /* If the entry has a labels, we have to move this label to the next insn.
580 * If there is no next insn, move the label into the code segement label
581 * pool. The operation is further complicated by the fact that the next
582 * insn may already have a label. In that case change all reference to
583 * this label and delete the label instead of moving it.
585 unsigned Count = CE_GetLabelCount (E);
588 /* The instruction has labels attached. Check if there is a next
591 if (Index == CS_GetEntryCount (S)-1) {
593 /* No next instruction, move to the codeseg label pool */
594 CS_MoveLabelsToPool (S, E);
598 /* There is a next insn, get it */
599 CodeEntry* N = CS_GetEntry (S, Index+1);
601 /* Move labels to the next entry */
602 CS_MoveLabels (S, E, N);
607 /* If this insn references a label, remove the reference. And, if the
608 * the reference count for this label drops to zero, remove this label.
611 /* Remove the reference */
612 CS_RemoveLabelRef (S, E);
615 /* Delete the pointer to the insn */
616 CollDelete (&S->Entries, Index);
618 /* Delete the instruction itself */
624 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
625 /* Delete a range of code entries. This includes removing references to labels,
626 * labels attached to the entries and so on.
629 /* Start deleting the entries from the rear, because this involves less
633 CS_DelEntry (S, Start + Count);
639 void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos)
640 /* Move a range of entries from one position to another. Start is the index
641 * of the first entry to move, Count is the number of entries and NewPos is
642 * the index of the target entry. The entry with the index Start will later
643 * have the index NewPos. All entries with indices NewPos and above are
644 * moved to higher indices. If the code block is moved to the end of the
645 * current code, and if pending labels exist, these labels will get attached
646 * to the first instruction of the moved block (the first one after the
650 /* If NewPos is at the end of the code segment, move any labels from the
651 * label pool to the first instruction of the moved range.
653 if (NewPos == CS_GetEntryCount (S)) {
654 CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start));
657 /* Move the code block to the destination */
658 CollMoveMultiple (&S->Entries, Start, Count, NewPos);
663 struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index)
664 /* Get the code entry preceeding the one with the index Index. If there is no
665 * preceeding code entry, return NULL.
669 /* This is the first entry */
672 /* Previous entry available */
673 return CollAtUnchecked (&S->Entries, Index-1);
679 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
680 /* Get the code entry following the one with the index Index. If there is no
681 * following code entry, return NULL.
684 if (Index >= CollCount (&S->Entries)-1) {
685 /* This is the last entry */
688 /* Code entries left */
689 return CollAtUnchecked (&S->Entries, Index+1);
695 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
696 unsigned Start, unsigned Count)
697 /* Get Count code entries into List starting at index start. Return true if
698 * we got the lines, return false if not enough lines were available.
701 /* Check if enough entries are available */
702 if (Start + Count > CollCount (&S->Entries)) {
706 /* Copy the entries */
708 *List++ = CollAtUnchecked (&S->Entries, Start++);
711 /* We have the entries */
717 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
718 /* Return the index of a code entry */
720 int Index = CollIndex (&S->Entries, E);
727 int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count)
728 /* Return true if any of the code entries in the given range has a label
729 * attached. If the code segment does not span the given range, check the
730 * possible span instead.
733 unsigned EntryCount = CS_GetEntryCount(S);
735 /* Adjust count. We expect at least Start to be valid. */
736 CHECK (Start < EntryCount);
737 if (Start + Count > EntryCount) {
738 Count = EntryCount - Start;
741 /* Check each entry. Since we have validated the index above, we may
742 * use the unchecked access function in the loop which is faster.
745 const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++);
746 if (CE_HasLabel (E)) {
751 /* No label in the complete range */
757 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
758 /* Add a code label for the next instruction to follow */
760 /* Calculate the hash from the name */
761 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
763 /* Try to find the code label if it does already exist */
764 CodeLabel* L = CS_FindLabel (S, Name, Hash);
766 /* Did we find it? */
768 /* We found it - be sure it does not already have an owner */
770 Error ("ASM label `%s' is already defined", Name);
774 /* Not found - create a new one */
775 L = CS_NewCodeLabel (S, Name, Hash);
778 /* Safety. This call is quite costly, but safety is better */
779 if (CollIndex (&S->Labels, L) >= 0) {
780 Error ("ASM label `%s' is already defined", Name);
784 /* We do now have a valid label. Remember it for later */
785 CollAppend (&S->Labels, L);
787 /* Return the label */
793 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
794 /* If the code entry E does already have a label, return it. Otherwise
795 * create a new label, attach it to E and return it.
800 if (CE_HasLabel (E)) {
802 /* Get the label from this entry */
803 L = CE_GetLabel (E, 0);
808 const char* Name = LocalLabelName (GetLocalLabel ());
810 /* Generate the hash over the name */
811 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
813 /* Create a new label */
814 L = CS_NewCodeLabel (S, Name, Hash);
816 /* Attach this label to the code entry */
817 CE_AttachLabel (E, L);
821 /* Return the label */
827 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
828 /* Remove references from this label and delete it. */
832 /* First, remove the label from the hash chain */
833 CS_RemoveLabelFromHash (S, L);
835 /* Remove references from insns jumping to this label */
836 Count = CollCount (&L->JumpFrom);
837 for (I = 0; I < Count; ++I) {
838 /* Get the insn referencing this label */
839 CodeEntry* E = CollAt (&L->JumpFrom, I);
840 /* Remove the reference */
843 CollDeleteAll (&L->JumpFrom);
845 /* Remove the reference to the owning instruction if it has one. The
846 * function may be called for a label without an owner when deleting
847 * unfinished parts of the code. This is unfortunate since it allows
848 * errors to slip through.
851 CollDeleteItem (&L->Owner->Labels, L);
854 /* All references removed, delete the label itself */
860 void CS_MergeLabels (CodeSeg* S)
861 /* Merge code labels. That means: For each instruction, remove all labels but
862 * one and adjust references accordingly.
868 /* First, remove all labels from the label symbol table that don't have an
869 * owner (this means that they are actually external labels but we didn't
870 * know that previously since they may have also been forward references).
872 for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
874 /* Get the first label in this hash chain */
875 CodeLabel** L = &S->LabelHash[I];
877 if ((*L)->Owner == 0) {
879 /* The label does not have an owner, remove it from the chain */
883 /* Cleanup any entries jumping to this label */
884 for (J = 0; J < CL_GetRefCount (X); ++J) {
885 /* Get the entry referencing this label */
886 CodeEntry* E = CL_GetRef (X, J);
887 /* And remove the reference. Do NOT call CE_ClearJumpTo
888 * here, because this will also clear the label name,
889 * which is not what we want.
894 /* Print some debugging output */
896 printf ("Removing unused global label `%s'", X->Name);
899 /* And free the label */
902 /* Label is owned, point to next code label pointer */
908 /* Walk over all code entries */
909 for (I = 0; I < CS_GetEntryCount (S); ++I) {
914 /* Get a pointer to the next entry */
915 CodeEntry* E = CS_GetEntry (S, I);
917 /* If this entry has zero labels, continue with the next one */
918 unsigned LabelCount = CE_GetLabelCount (E);
919 if (LabelCount == 0) {
923 /* We have at least one label. Use the first one as reference label. */
924 RefLab = CE_GetLabel (E, 0);
926 /* Walk through the remaining labels and change references to these
927 * labels to a reference to the one and only label. Delete the labels
928 * that are no longer used. To increase performance, walk backwards
931 for (J = LabelCount-1; J >= 1; --J) {
933 /* Get the next label */
934 CodeLabel* L = CE_GetLabel (E, J);
936 /* Move all references from this label to the reference label */
937 CL_MoveRefs (L, RefLab);
939 /* Remove the label completely. */
943 /* The reference label is the only remaining label. Check if there
944 * are any references to this label, and delete it if this is not
947 if (CollCount (&RefLab->JumpFrom) == 0) {
948 /* Delete the label */
949 CS_DelLabel (S, RefLab);
956 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
957 /* Move all labels from Old to New. The routine will move the labels itself
958 * if New does not have any labels, and move references if there is at least
959 * a label for new. If references are moved, the old label is deleted
963 /* Get the number of labels to move */
964 unsigned OldLabelCount = CE_GetLabelCount (Old);
966 /* Does the new entry have itself a label? */
967 if (CE_HasLabel (New)) {
969 /* The new entry does already have a label - move references */
970 CodeLabel* NewLabel = CE_GetLabel (New, 0);
971 while (OldLabelCount--) {
973 /* Get the next label */
974 CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
976 /* Move references */
977 CL_MoveRefs (OldLabel, NewLabel);
979 /* Delete the label */
980 CS_DelLabel (S, OldLabel);
986 /* The new entry does not have a label, just move them */
987 while (OldLabelCount--) {
989 /* Move the label to the new entry */
990 CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
999 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
1000 /* Remove the reference between E and the label it jumps to. The reference
1001 * will be removed on both sides and E->JumpTo will be 0 after that. If
1002 * the reference was the only one for the label, the label will get
1006 /* Get a pointer to the label and make sure it exists */
1007 CodeLabel* L = E->JumpTo;
1010 /* Delete the entry from the label */
1011 CollDeleteItem (&L->JumpFrom, E);
1013 /* The entry jumps no longer to L */
1016 /* If there are no more references, delete the label */
1017 if (CollCount (&L->JumpFrom) == 0) {
1024 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
1025 /* Change the reference of E to L instead of the current one. If this
1026 * was the only reference to the old label, the old label will get
1030 /* Get the old label */
1031 CodeLabel* OldLabel = E->JumpTo;
1033 /* Be sure that code entry references a label */
1034 PRECONDITION (OldLabel != 0);
1036 /* Remove the reference to our label */
1037 CS_RemoveLabelRef (S, E);
1039 /* Use the new label */
1045 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
1046 /* Delete all entries including the given one */
1048 /* Get the number of entries in this segment */
1049 unsigned Count = CS_GetEntryCount (S);
1051 /* First pass: Delete all references to labels. If the reference count
1052 * for a label drops to zero, delete it.
1055 while (Last < C--) {
1057 /* Get the next entry */
1058 CodeEntry* E = CS_GetEntry (S, C);
1060 /* Check if this entry has a label reference */
1062 /* If the label is a label in the label pool and this is the last
1063 * reference to the label, remove the label from the pool.
1065 CodeLabel* L = E->JumpTo;
1066 int Index = CollIndex (&S->Labels, L);
1067 if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
1068 /* Delete it from the pool */
1069 CollDelete (&S->Labels, Index);
1072 /* Remove the reference to the label */
1073 CS_RemoveLabelRef (S, E);
1078 /* Second pass: Delete the instructions. If a label attached to an
1079 * instruction still has references, it must be references from outside
1080 * the deleted area. Don't delete the label in this case, just make it
1081 * ownerless and move it to the label pool.
1084 while (Last < C--) {
1086 /* Get the next entry */
1087 CodeEntry* E = CS_GetEntry (S, C);
1089 /* Check if this entry has a label attached */
1090 if (CE_HasLabel (E)) {
1091 /* Move the labels to the pool and clear the owner pointer */
1092 CS_MoveLabelsToPool (S, E);
1095 /* Delete the pointer to the entry */
1096 CollDelete (&S->Entries, C);
1098 /* Delete the entry itself */
1105 void CS_ResetMarks (CodeSeg* S, unsigned First, unsigned Last)
1106 /* Remove all user marks from the entries in the given range */
1108 while (First <= Last) {
1109 CE_ResetMark (CS_GetEntry (S, First++));
1115 int CS_IsBasicBlock (CodeSeg* S, unsigned First, unsigned Last)
1116 /* Check if the given code segment range is a basic block. That is, check if
1117 * First is the only entrance and Last is the only exit. This means that no
1118 * jump/branch inside the block may jump to an insn below First or after(!)
1119 * Last, and that no insn may jump into this block from the outside.
1124 /* Don't accept invalid ranges */
1125 CHECK (First <= Last);
1127 /* First pass: Walk over the range and remove all marks from the entries */
1128 CS_ResetMarks (S, First, Last);
1130 /* Second pass: Walk over the range checking all labels. Note: There may be
1131 * label on the first insn which is ok.
1136 /* Get the next entry */
1137 CodeEntry* E = CS_GetEntry (S, I);
1139 /* Check if this entry has one or more labels, if so, check which
1140 * entries jump to this label.
1142 unsigned LabelCount = CE_GetLabelCount (E);
1143 unsigned LabelIndex;
1144 for (LabelIndex = 0; LabelIndex < LabelCount; ++LabelIndex) {
1146 /* Get this label */
1147 CodeLabel* L = CE_GetLabel (E, LabelIndex);
1149 /* Walk over all entries that jump to this label. Check for each
1150 * of the entries if it is out of the range.
1152 unsigned RefCount = CL_GetRefCount (L);
1154 for (RefIndex = 0; RefIndex < RefCount; ++RefIndex) {
1156 /* Get the code entry that jumps here */
1157 CodeEntry* Ref = CL_GetRef (L, RefIndex);
1159 /* Walk over out complete range and check if we find the
1160 * refering entry. This is cheaper than using CS_GetEntryIndex,
1161 * because CS_GetEntryIndex will search the complete code
1162 * segment and not just our range.
1165 for (J = First; J <= Last; ++J) {
1166 if (Ref == CS_GetEntry (S, J)) {
1171 /* We did not find the entry. This means that the jump to
1172 * out code segment entry E came from outside the range,
1173 * which in turn means that the given range is not a basic
1176 CS_ResetMarks (S, First, Last);
1180 /* If we come here, we found the entry. Mark it, so we know
1181 * that the branch to the label is in range.
1191 /* Third pass: Walk again over the range and check all branches. If we
1192 * find a branch that is not marked, its target is not inside the range
1193 * (since we checked all the labels in the range before).
1198 /* Get the next entry */
1199 CodeEntry* E = CS_GetEntry (S, I);
1201 /* Check if this is a branch and if so, if it has a mark */
1202 if (E->Info & (OF_UBRA | OF_CBRA)) {
1203 if (!CE_HasMark (E)) {
1204 /* No mark means not a basic block. Before bailing out, be sure
1205 * to remove the marks from the remaining entries.
1207 CS_ResetMarks (S, I+1, Last);
1211 /* Remove the mark */
1219 /* Done - this is a basic block */
1225 void CS_OutputPrologue (const CodeSeg* S, FILE* F)
1226 /* If the given code segment is a code segment for a function, output the
1227 * assembler prologue into the file. That is: Output a comment header, switch
1228 * to the correct segment and enter the local function scope. If the code
1229 * segment is global, do nothing.
1232 /* Get the function associated with the code segment */
1233 SymEntry* Func = S->Func;
1235 /* If the code segment is associated with a function, print a function
1236 * header and enter a local scope. Be sure to switch to the correct
1237 * segment before outputing the function label.
1240 /* Get the function descriptor */
1241 const FuncDesc* D = GetFuncDesc (Func->Type);
1242 CS_PrintFunctionHeader (S, F);
1243 fprintf (F, ".segment\t\"%s\"\n\n.proc\t_%s", S->SegName, Func->Name);
1244 if (D->Flags & FD_NEAR) {
1245 fputs (": near", F);
1246 } else if (D->Flags & FD_FAR) {
1256 void CS_OutputEpilogue (const CodeSeg* S, FILE* F)
1257 /* If the given code segment is a code segment for a function, output the
1258 * assembler epilogue into the file. That is: Close the local function scope.
1262 fputs ("\n.endproc\n\n", F);
1268 void CS_Output (CodeSeg* S, FILE* F)
1269 /* Output the code segment data to a file */
1274 /* Get the number of entries in this segment */
1275 unsigned Count = CS_GetEntryCount (S);
1277 /* If the code segment is empty, bail out here */
1282 /* Generate register info */
1285 /* Output the segment directive */
1286 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
1288 /* Output all entries, prepended by the line information if it has changed */
1290 for (I = 0; I < Count; ++I) {
1291 /* Get the next entry */
1292 const CodeEntry* E = CollConstAt (&S->Entries, I);
1293 /* Check if the line info has changed. If so, output the source line
1294 * if the option is enabled and output debug line info if the debug
1295 * option is enabled.
1298 /* Line info has changed, remember the new line info */
1301 /* Add the source line as a comment. Beware: When line continuation
1302 * was used, the line may contain newlines.
1305 const char* L = LI->Line;
1318 /* Add line debug info */
1320 fprintf (F, "\t.dbg\tline, \"%s\", %u\n",
1321 GetInputName (LI), GetInputLine (LI));
1324 /* Output the code */
1328 /* If debug info is enabled, terminate the last line number information */
1330 fputs ("\t.dbg\tline\n", F);
1333 /* Free register info */
1339 void CS_FreeRegInfo (CodeSeg* S)
1340 /* Free register infos for all instructions */
1343 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1344 CE_FreeRegInfo (CS_GetEntry(S, I));
1350 void CS_GenRegInfo (CodeSeg* S)
1351 /* Generate register infos for all instructions */
1354 RegContents Regs; /* Initial register contents */
1355 RegContents* CurrentRegs; /* Current register contents */
1356 int WasJump; /* True if last insn was a jump */
1357 int Done; /* All runs done flag */
1359 /* Be sure to delete all register infos */
1362 /* We may need two runs to get back references right */
1365 /* Assume we're done after this run */
1368 /* On entry, the register contents are unknown */
1369 RC_Invalidate (&Regs);
1370 CurrentRegs = &Regs;
1372 /* Walk over all insns and note just the changes from one insn to the
1376 for (I = 0; I < CS_GetEntryCount (S); ++I) {
1380 /* Get the next instruction */
1381 CodeEntry* E = CollAtUnchecked (&S->Entries, I);
1383 /* If the instruction has a label, we need some special handling */
1384 unsigned LabelCount = CE_GetLabelCount (E);
1385 if (LabelCount > 0) {
1387 /* Loop over all entry points that jump here. If these entry
1388 * points already have register info, check if all values are
1389 * known and identical. If all values are identical, and the
1390 * preceeding instruction was not an unconditional branch, check
1391 * if the register value on exit of the preceeding instruction
1392 * is also identical. If all these values are identical, the
1393 * value of a register is known, otherwise it is unknown.
1395 CodeLabel* Label = CE_GetLabel (E, 0);
1398 /* Preceeding insn was an unconditional branch */
1399 CodeEntry* J = CL_GetRef(Label, 0);
1403 RC_Invalidate (&Regs);
1407 Regs = *CurrentRegs;
1411 while (Entry < CL_GetRefCount (Label)) {
1412 /* Get this entry */
1413 CodeEntry* J = CL_GetRef (Label, Entry);
1415 /* No register info for this entry. This means that the
1416 * instruction that jumps here is at higher addresses and
1417 * the jump is a backward jump. We need a second run to
1418 * get the register info right in this case. Until then,
1419 * assume unknown register contents.
1422 RC_Invalidate (&Regs);
1425 if (J->RI->Out2.RegA != Regs.RegA) {
1426 Regs.RegA = UNKNOWN_REGVAL;
1428 if (J->RI->Out2.RegX != Regs.RegX) {
1429 Regs.RegX = UNKNOWN_REGVAL;
1431 if (J->RI->Out2.RegY != Regs.RegY) {
1432 Regs.RegY = UNKNOWN_REGVAL;
1434 if (J->RI->Out2.SRegLo != Regs.SRegLo) {
1435 Regs.SRegLo = UNKNOWN_REGVAL;
1437 if (J->RI->Out2.SRegHi != Regs.SRegHi) {
1438 Regs.SRegHi = UNKNOWN_REGVAL;
1440 if (J->RI->Out2.Tmp1 != Regs.Tmp1) {
1441 Regs.Tmp1 = UNKNOWN_REGVAL;
1446 /* Use this register info */
1447 CurrentRegs = &Regs;
1451 /* Generate register info for this instruction */
1452 CE_GenRegInfo (E, CurrentRegs);
1454 /* Remember for the next insn if this insn was an uncondition branch */
1455 WasJump = (E->Info & OF_UBRA) != 0;
1457 /* Output registers for this insn are input for the next */
1458 CurrentRegs = &E->RI->Out;
1460 /* If this insn is a branch on zero flag, we may have more info on
1461 * register contents for one of both flow directions, but only if
1462 * there is a previous instruction.
1464 if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) {
1466 /* Get the branch condition */
1467 bc_t BC = GetBranchCond (E->OPC);
1469 /* Check the previous instruction */
1481 /* A is zero in one execution flow direction */
1483 E->RI->Out2.RegA = 0;
1485 E->RI->Out.RegA = 0;
1490 /* If this is an immidiate compare, the A register has
1491 * the value of the compare later.
1493 if (CE_KnownImm (P)) {
1495 E->RI->Out2.RegA = (unsigned char)P->Num;
1497 E->RI->Out.RegA = (unsigned char)P->Num;
1503 /* If this is an immidiate compare, the X register has
1504 * the value of the compare later.
1506 if (CE_KnownImm (P)) {
1508 E->RI->Out2.RegX = (unsigned char)P->Num;
1510 E->RI->Out.RegX = (unsigned char)P->Num;
1516 /* If this is an immidiate compare, the Y register has
1517 * the value of the compare later.
1519 if (CE_KnownImm (P)) {
1521 E->RI->Out2.RegY = (unsigned char)P->Num;
1523 E->RI->Out.RegY = (unsigned char)P->Num;
1532 /* X is zero in one execution flow direction */
1534 E->RI->Out2.RegX = 0;
1536 E->RI->Out.RegX = 0;
1544 /* X is zero in one execution flow direction */
1546 E->RI->Out2.RegY = 0;
1548 E->RI->Out.RegY = 0;
1554 /* If the branch is a beq, both A and X are zero at the
1555 * branch target, otherwise they are zero at the next
1559 E->RI->Out2.RegA = E->RI->Out2.RegX = 0;
1561 E->RI->Out.RegA = E->RI->Out.RegX = 0;
1567 /* If the branch is a beq, both A and Y are zero at the
1568 * branch target, otherwise they are zero at the next
1572 E->RI->Out2.RegA = E->RI->Out2.RegY = 0;
1574 E->RI->Out.RegA = E->RI->Out.RegY = 0;