1 /*****************************************************************************/
5 /* Optimize compares */
9 /* (C) 2001 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 /*****************************************************************************/
46 /*****************************************************************************/
48 /*****************************************************************************/
52 /* Defines for the conditions in a compare */
67 /* Table with the compare suffixes */
68 static const char CmpSuffixTab [][4] = {
69 "eq", "ne", "gt", "ge", "lt", "le", "ugt", "uge", "ult", "ule"
72 /* Table used to invert a condition, indexed by condition */
73 static const unsigned char CmpInvertTab [] = {
75 CMP_LE, CMP_LT, CMP_GE, CMP_GT,
76 CMP_ULE, CMP_ULT, CMP_UGE, CMP_UGT
79 /* Table to show which compares are signed (use the N flag) */
80 static const char CmpSignedTab [] = {
81 0, 0, 1, 1, 1, 1, 0, 0, 0, 0
86 /*****************************************************************************/
87 /* Helper functions */
88 /*****************************************************************************/
92 static cmp_t FindCmpCond (const char* Code, unsigned CodeLen)
93 /* Search for a compare condition by the given code using the given length */
98 for (I = 0; I < sizeof (CmpSuffixTab) / sizeof (CmpSuffixTab [0]); ++I) {
99 if (strncmp (Code, CmpSuffixTab [I], CodeLen) == 0) {
111 static cmp_t FindBoolCmpCond (const char* Name)
112 /* Map a condition suffix to a code. Return the code or CMP_INV on failure */
114 /* Check for the correct subroutine name */
115 if (strncmp (Name, "bool", 4) == 0) {
116 /* Name is ok, search for the code in the table */
117 return FindCmpCond (Name+4, strlen(Name)-4);
126 static cmp_t FindTosCmpCond (const char* Name)
127 /* Check if this is a call to one of the TOS compare functions (tosgtax).
128 * Return the condition code or CMP_INV on failure.
131 unsigned Len = strlen (Name);
133 /* Check for the correct subroutine name */
134 if (strncmp (Name, "tos", 3) == 0 && strcmp (Name+Len-2, "ax") == 0) {
135 /* Name is ok, search for the code in the table */
136 return FindCmpCond (Name+3, Len-3-2);
145 static void ReplaceCmp (CodeSeg* S, unsigned I, cmp_t Cond)
146 /* Helper function for the replacement of routines that return a boolean
147 * followed by a conditional jump. Instead of the boolean value, the condition
148 * codes are evaluated directly.
149 * I is the index of the conditional branch, the sequence is already checked
157 CodeEntry* E = CS_GetEntry (S, I);
159 /* Replace the conditional branch */
163 CE_ReplaceOPC (E, OP65_JEQ);
167 CE_ReplaceOPC (E, OP65_JNE);
176 if ((N = CS_GetNextEntry (S, I)) == 0) {
178 Internal ("Invalid program flow");
180 L = CS_GenLabel (S, N);
181 N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI);
182 CS_InsertEntry (S, N, I);
183 CE_ReplaceOPC (E, OP65_JPL);
187 CE_ReplaceOPC (E, OP65_JPL);
191 CE_ReplaceOPC (E, OP65_JMI);
199 CE_ReplaceOPC (E, OP65_JMI);
201 N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI);
202 CS_InsertEntry (S, N, I+1);
211 if ((N = CS_GetNextEntry (S, I)) == 0) {
213 Internal ("Invalid program flow");
215 L = CS_GenLabel (S, N);
216 N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI);
217 CS_InsertEntry (S, N, I);
218 CE_ReplaceOPC (E, OP65_JCS);
222 CE_ReplaceOPC (E, OP65_JCS);
226 CE_ReplaceOPC (E, OP65_JCC);
234 CE_ReplaceOPC (E, OP65_JCC);
236 N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI);
237 CS_InsertEntry (S, N, I+1);
241 Internal ("Unknown jump condition: %d", Cond);
249 static int IsImmCmp16 (CodeEntry** L)
250 /* Check if the instructions at L are an immidiate compare of a/x:
255 return (L[0]->OPC == OP65_CPX &&
256 L[0]->AM == AM65_IMM &&
257 (L[0]->Flags & CEF_NUMARG) != 0 &&
258 !CE_HasLabel (L[0]) &&
259 (L[1]->OPC == OP65_JNE || L[1]->OPC == OP65_BNE) &&
261 !CE_HasLabel (L[1]) &&
262 L[2]->OPC == OP65_CMP &&
263 L[2]->AM == AM65_IMM &&
264 (L[2]->Flags & CEF_NUMARG) != 0 &&
265 (L[3]->Info & OF_ZBRA) != 0 &&
267 (L[1]->JumpTo->Owner == L[3] || L[1]->JumpTo == L[3]->JumpTo));
272 static int GetCmpRegVal (const CodeEntry* E)
273 /* Return the register value for an immediate compare */
276 case OP65_CMP: return E->RI->In.RegA;
277 case OP65_CPX: return E->RI->In.RegX;
278 case OP65_CPY: return E->RI->In.RegY;
279 default: Internal ("Invalid opcode in GetCmpRegVal");
280 return 0; /* Not reached */
286 static int IsCmpToZero (const CodeEntry* E)
287 /* Check if the given instrcuction is a compare to zero instruction */
289 return (E->OPC == OP65_CMP &&
291 (E->Flags & CEF_NUMARG) != 0 &&
297 static int IsSpLoad (const CodeEntry* E)
298 /* Return true if this is the load of A from the stack */
300 return E->OPC == OP65_LDA && E->AM == AM65_ZP_INDY && strcmp (E->Arg, "sp") == 0;
305 static int IsLocalLoad16 (CodeSeg* S, unsigned Index,
306 CodeEntry** L, unsigned Count)
307 /* Check if a 16 bit load of a local variable follows:
315 * If so, read Count entries following the first ldy into L and return true
316 * if this is possible. Otherwise return false.
319 /* Be sure we read enough entries for the check */
322 /* Read the first entry */
323 L[0] = CS_GetEntry (S, Index);
325 /* Check for the sequence */
326 return (L[0]->OPC == OP65_LDY &&
327 CE_KnownImm (L[0]) &&
328 CS_GetEntries (S, L+1, Index+1, Count-1) &&
330 !CE_HasLabel (L[1]) &&
331 L[2]->OPC == OP65_TAX &&
332 !CE_HasLabel (L[2]) &&
333 L[3]->OPC == OP65_LDY &&
334 CE_KnownImm (L[3]) &&
335 L[3]->Num == L[0]->Num - 1 &&
336 !CE_HasLabel (L[3]) &&
338 !CE_HasLabel (L[4]));
343 /*****************************************************************************/
344 /* Remove calls to the bool transformer subroutines */
345 /*****************************************************************************/
349 unsigned OptBoolTrans (CodeSeg* S)
350 /* Try to remove the call to boolean transformer routines where the call is
354 unsigned Changes = 0;
356 /* Walk over the entries */
358 while (I < CS_GetEntryCount (S)) {
364 CodeEntry* E = CS_GetEntry (S, I);
366 /* Check for a boolean transformer */
367 if (E->OPC == OP65_JSR &&
368 (Cond = FindBoolCmpCond (E->Arg)) != CMP_INV &&
369 (N = CS_GetNextEntry (S, I)) != 0 &&
370 (N->Info & OF_ZBRA) != 0) {
372 /* Make the boolean transformer unnecessary by changing the
373 * the conditional jump to evaluate the condition flags that
374 * are set after the compare directly. Note: jeq jumps if
375 * the condition is not met, jne jumps if the condition is met.
376 * Invert the code if we jump on condition not met.
378 if (GetBranchCond (N->OPC) == BC_EQ) {
379 /* Jumps if condition false, invert condition */
380 Cond = CmpInvertTab [Cond];
383 /* Check if we can replace the code by something better */
384 ReplaceCmp (S, I+1, Cond);
386 /* Remove the call to the bool transformer */
389 /* Remember, we had changes */
399 /* Return the number of changes made */
405 /*****************************************************************************/
406 /* Optimizations for compares */
407 /*****************************************************************************/
411 unsigned OptCmp1 (CodeSeg* S)
412 /* Search for the sequence
424 unsigned Changes = 0;
426 /* Walk over the entries */
428 while (I < CS_GetEntryCount (S)) {
433 CodeEntry* E = CS_GetEntry (S, I);
435 /* Check for the sequence */
436 if (E->OPC == OP65_STX &&
437 CS_GetEntries (S, L, I+1, 2) &&
438 L[0]->OPC == OP65_STX &&
439 strcmp (L[0]->Arg, "tmp1") == 0 &&
440 !CE_HasLabel (L[0]) &&
441 L[1]->OPC == OP65_ORA &&
442 strcmp (L[1]->Arg, "tmp1") == 0 &&
443 !CE_HasLabel (L[1])) {
445 /* Remove the remaining instructions */
446 CS_DelEntries (S, I+1, 2);
448 /* Insert the ora instead */
449 CS_InsertEntry (S, NewCodeEntry (OP65_ORA, E->AM, E->Arg, 0, E->LI), I+1);
451 /* Remember, we had changes */
461 /* Return the number of changes made */
467 unsigned OptCmp2 (CodeSeg* S)
470 * lda/and/ora/eor ...
474 * lda/and/ora/eor ...
478 * and remove the cmp.
481 unsigned Changes = 0;
483 /* Walk over the entries */
485 while (I < CS_GetEntryCount (S)) {
490 CodeEntry* E = CS_GetEntry (S, I);
492 /* Check for the sequence */
493 if ((E->OPC == OP65_ADC ||
494 E->OPC == OP65_AND ||
495 E->OPC == OP65_DEA ||
496 E->OPC == OP65_EOR ||
497 E->OPC == OP65_INA ||
498 E->OPC == OP65_LDA ||
499 E->OPC == OP65_ORA ||
500 E->OPC == OP65_PLA ||
501 E->OPC == OP65_SBC ||
502 E->OPC == OP65_TXA ||
503 E->OPC == OP65_TYA) &&
504 CS_GetEntries (S, L, I+1, 2) &&
505 IsCmpToZero (L[0]) &&
506 !CE_HasLabel (L[0]) &&
507 ((L[1]->Info & OF_FBRA) != 0 ||
508 (L[1]->OPC == OP65_JSR &&
509 FindBoolCmpCond (L[1]->Arg) != CMP_INV)) &&
510 !CE_HasLabel (L[1])) {
512 /* Remove the compare */
513 CS_DelEntry (S, I+1);
515 /* Remember, we had changes */
525 /* Return the number of changes made */
531 unsigned OptCmp3 (CodeSeg* S)
541 * If a is zero, we may remove the compare. If a and b are both zero, we may
542 * replace it by the sequence
548 * L1 may be either the label at the branch instruction, or the target label
549 * of this instruction.
552 unsigned Changes = 0;
554 /* Walk over the entries */
556 while (I < CS_GetEntryCount (S)) {
561 CodeEntry* E = CS_GetEntry (S, I);
563 /* Check for the sequence */
564 if (E->OPC == OP65_LDA &&
565 CS_GetEntries (S, L, I+1, 5) &&
566 L[0]->OPC == OP65_LDX &&
567 !CE_HasLabel (L[0]) &&
570 if (L[1]->Num == 0 && L[3]->Num == 0) {
571 /* The value is zero, we may use the simple code version. */
572 CE_ReplaceOPC (L[0], OP65_ORA);
573 CS_DelEntries (S, I+2, 3);
575 /* Move the lda instruction after the first branch. This will
576 * improve speed, since the load is delayed after the first
579 CS_MoveEntry (S, I, I+4);
581 /* We will replace the ldx/cpx by lda/cmp */
582 CE_ReplaceOPC (L[0], OP65_LDA);
583 CE_ReplaceOPC (L[1], OP65_CMP);
585 /* Beware: If the first LDA instruction had a label, we have
586 * to move this label to the top of the sequence again.
588 if (CE_HasLabel (E)) {
589 CS_MoveLabels (S, E, L[0]);
602 /* Return the number of changes made */
608 unsigned OptCmp4 (CodeSeg* S)
609 /* Optimize compares of local variables:
622 unsigned Changes = 0;
624 /* Walk over the entries */
626 while (I < CS_GetEntryCount (S)) {
630 /* Check for the sequence */
631 if (IsLocalLoad16 (S, I, L, 9) && IsImmCmp16 (L+5)) {
633 if (L[5]->Num == 0 && L[7]->Num == 0) {
635 /* The value is zero, we may use the simple code version:
642 CE_ReplaceOPC (L[4], OP65_ORA);
643 CS_DelEntries (S, I+5, 3); /* cpx/bne/cmp */
644 CS_DelEntry (S, I+2); /* tax */
648 /* Change the code to just use the A register. Move the load
649 * of the low byte after the first branch if possible:
660 CS_DelEntry (S, I+2); /* tax */
661 CE_ReplaceOPC (L[5], OP65_CMP); /* cpx -> cmp */
662 CS_MoveEntry (S, I+4, I+2); /* cmp */
663 CS_MoveEntry (S, I+5, I+3); /* bne */
675 /* Return the number of changes made */
681 unsigned OptCmp5 (CodeSeg* S)
682 /* Search for calls to compare subroutines followed by a conditional branch
683 * and replace them by cheaper versions, since the branch means that the
684 * boolean value returned by these routines is not needed (we may also check
685 * that explicitly, but for the current code generator it is always true).
688 unsigned Changes = 0;
690 /* Walk over the entries */
692 while (I < CS_GetEntryCount (S)) {
698 CodeEntry* E = CS_GetEntry (S, I);
700 /* Check for the sequence */
701 if (E->OPC == OP65_JSR &&
702 (Cond = FindTosCmpCond (E->Arg)) != CMP_INV &&
703 (N = CS_GetNextEntry (S, I)) != 0 &&
704 (N->Info & OF_ZBRA) != 0 &&
707 /* The tos... functions will return a boolean value in a/x and
708 * the Z flag says if this value is zero or not. We will call
709 * a cheaper subroutine instead, one that does not return a
710 * boolean value but only valid flags. Note: jeq jumps if
711 * the condition is not met, jne jumps if the condition is met.
712 * Invert the code if we jump on condition not met.
714 if (GetBranchCond (N->OPC) == BC_EQ) {
715 /* Jumps if condition false, invert condition */
716 Cond = CmpInvertTab [Cond];
719 /* Replace the subroutine call. */
720 E = NewCodeEntry (OP65_JSR, AM65_ABS, "tosicmp", 0, E->LI);
721 CS_InsertEntry (S, E, I+1);
724 /* Replace the conditional branch */
725 ReplaceCmp (S, I+1, Cond);
727 /* Remember, we had changes */
737 /* Return the number of changes made */
743 unsigned OptCmp6 (CodeSeg* S)
744 /* Search for a sequence ldx/txa/branch and remove the txa if A is not
748 unsigned Changes = 0;
750 /* Walk over the entries */
752 while (I < CS_GetEntryCount (S)) {
757 CodeEntry* E = CS_GetEntry (S, I);
759 /* Check for the sequence */
760 if ((E->OPC == OP65_LDX) &&
761 CS_GetEntries (S, L, I+1, 2) &&
762 L[0]->OPC == OP65_TXA &&
763 !CE_HasLabel (L[0]) &&
764 (L[1]->Info & OF_FBRA) != 0 &&
765 !CE_HasLabel (L[1]) &&
766 !RegAUsed (S, I+3)) {
769 CS_DelEntry (S, I+1);
771 /* Remember, we had changes */
781 /* Return the number of changes made */
787 unsigned OptCmp7 (CodeSeg* S)
788 /* Check for register compares where the contents of the register and therefore
789 * the result of the compare is known.
792 unsigned Changes = 0;
795 /* Generate register info for this step */
798 /* Walk over the entries */
800 while (I < CS_GetEntryCount (S)) {
805 CodeEntry* E = CS_GetEntry (S, I);
807 /* Check for a compare against an immediate value */
808 if ((E->Info & OF_CMP) != 0 &&
809 (RegVal = GetCmpRegVal (E)) >= 0 &&
812 /* We are able to evaluate the compare at compile time. Check if
813 * one or more branches are ahead.
815 unsigned JumpsChanged = 0;
817 while ((N = CS_GetNextEntry (S, I)) != 0 && /* Followed by something.. */
818 (N->Info & OF_CBRA) != 0 && /* ..that is a cond branch.. */
819 !CE_HasLabel (N)) { /* ..and has no label */
821 /* Evaluate the branch condition */
823 switch (GetBranchCond (N->OPC)) {
825 Cond = ((unsigned char)RegVal) < ((unsigned char)E->Num);
829 Cond = ((unsigned char)RegVal) >= ((unsigned char)E->Num);
833 Cond = ((unsigned char)RegVal) == ((unsigned char)E->Num);
837 Cond = ((signed char)RegVal) < ((signed char)E->Num);
841 Cond = ((unsigned char)RegVal) != ((unsigned char)E->Num);
845 Cond = ((signed char)RegVal) >= ((signed char)E->Num);
850 /* Not set by the compare operation, bail out (Note:
851 * Just skipping anything here is rather stupid, but
852 * the sequence is never generated by the compiler,
853 * so it's quite safe to skip).
858 Internal ("Unknown branch condition");
862 /* If the condition is false, we may remove the jump. Otherwise
863 * the branch will always be taken, so we may replace it by a
864 * jump (and bail out).
867 CS_DelEntry (S, I+1);
869 CodeLabel* L = N->JumpTo;
870 const char* LabelName = L? L->Name : N->Arg;
871 CodeEntry* X = NewCodeEntry (OP65_JMP, AM65_BRA, LabelName, L, N->LI);
872 CS_InsertEntry (S, X, I+2);
873 CS_DelEntry (S, I+1);
876 /* Remember, we had changes */
881 /* If we have made changes above, we may also remove the compare */
894 /* Free register info */
897 /* Return the number of changes made */