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 (CodeSeg* S, 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 L[0]->AM == AM65_IMM &&
328 (L[0]->Flags & CEF_NUMARG) != 0 &&
329 CS_GetEntries (S, L+1, Index+1, Count-1) &&
331 !CE_HasLabel (L[1]) &&
332 L[2]->OPC == OP65_TAX &&
333 !CE_HasLabel (L[2]) &&
334 L[3]->OPC == OP65_DEY &&
335 !CE_HasLabel (L[3]) &&
337 !CE_HasLabel (L[4]));
342 /*****************************************************************************/
343 /* Remove calls to the bool transformer subroutines */
344 /*****************************************************************************/
348 unsigned OptBoolTrans (CodeSeg* S)
349 /* Try to remove the call to boolean transformer routines where the call is
353 unsigned Changes = 0;
355 /* Walk over the entries */
357 while (I < CS_GetEntryCount (S)) {
363 CodeEntry* E = CS_GetEntry (S, I);
365 /* Check for a boolean transformer */
366 if (E->OPC == OP65_JSR &&
367 (Cond = FindBoolCmpCond (E->Arg)) != CMP_INV &&
368 (N = CS_GetNextEntry (S, I)) != 0 &&
369 (N->Info & OF_ZBRA) != 0) {
371 /* Make the boolean transformer unnecessary by changing the
372 * the conditional jump to evaluate the condition flags that
373 * are set after the compare directly. Note: jeq jumps if
374 * the condition is not met, jne jumps if the condition is met.
375 * Invert the code if we jump on condition not met.
377 if (GetBranchCond (N->OPC) == BC_EQ) {
378 /* Jumps if condition false, invert condition */
379 Cond = CmpInvertTab [Cond];
382 /* Check if we can replace the code by something better */
383 ReplaceCmp (S, I+1, Cond);
385 /* Remove the call to the bool transformer */
388 /* Remember, we had changes */
398 /* Return the number of changes made */
404 /*****************************************************************************/
405 /* Optimizations for compares */
406 /*****************************************************************************/
410 unsigned OptCmp1 (CodeSeg* S)
411 /* Search for the sequence
423 unsigned Changes = 0;
425 /* Walk over the entries */
427 while (I < CS_GetEntryCount (S)) {
432 CodeEntry* E = CS_GetEntry (S, I);
434 /* Check for the sequence */
435 if (E->OPC == OP65_STX &&
436 CS_GetEntries (S, L, I+1, 2) &&
437 L[0]->OPC == OP65_STX &&
438 strcmp (L[0]->Arg, "tmp1") == 0 &&
439 !CE_HasLabel (L[0]) &&
440 L[1]->OPC == OP65_ORA &&
441 strcmp (L[1]->Arg, "tmp1") == 0 &&
442 !CE_HasLabel (L[1])) {
444 /* Remove the remaining instructions */
445 CS_DelEntries (S, I+1, 2);
447 /* Insert the ora instead */
448 CS_InsertEntry (S, NewCodeEntry (OP65_ORA, E->AM, E->Arg, 0, E->LI), I+1);
450 /* Remember, we had changes */
460 /* Return the number of changes made */
466 unsigned OptCmp2 (CodeSeg* S)
469 * lda/and/ora/eor ...
473 * lda/and/ora/eor ...
477 * and remove the cmp.
480 unsigned Changes = 0;
482 /* Walk over the entries */
484 while (I < CS_GetEntryCount (S)) {
489 CodeEntry* E = CS_GetEntry (S, I);
491 /* Check for the sequence */
492 if ((E->OPC == OP65_ADC ||
493 E->OPC == OP65_AND ||
494 E->OPC == OP65_DEA ||
495 E->OPC == OP65_EOR ||
496 E->OPC == OP65_INA ||
497 E->OPC == OP65_LDA ||
498 E->OPC == OP65_ORA ||
499 E->OPC == OP65_PLA ||
500 E->OPC == OP65_SBC ||
501 E->OPC == OP65_TXA ||
502 E->OPC == OP65_TYA) &&
503 CS_GetEntries (S, L, I+1, 2) &&
504 IsCmpToZero (L[0]) &&
505 !CE_HasLabel (L[0]) &&
506 ((L[1]->Info & OF_FBRA) != 0 ||
507 (L[1]->OPC == OP65_JSR &&
508 FindBoolCmpCond (L[1]->Arg) != CMP_INV)) &&
509 !CE_HasLabel (L[1])) {
511 /* Remove the compare */
512 CS_DelEntry (S, I+1);
514 /* Remember, we had changes */
524 /* Return the number of changes made */
530 unsigned OptCmp3 (CodeSeg* S)
540 * If a is zero, we may remove the compare. If a and b are both zero, we may
541 * replace it by the sequence
547 * L1 may be either the label at the branch instruction, or the target label
548 * of this instruction.
551 unsigned Changes = 0;
553 /* Walk over the entries */
555 while (I < CS_GetEntryCount (S)) {
560 CodeEntry* E = CS_GetEntry (S, I);
562 /* Check for the sequence */
563 if (E->OPC == OP65_LDA &&
564 CS_GetEntries (S, L, I+1, 5) &&
565 L[0]->OPC == OP65_LDX &&
566 !CE_HasLabel (L[0]) &&
567 IsImmCmp16 (S, L+1)) {
569 if (L[1]->Num == 0 && L[3]->Num == 0) {
570 /* The value is zero, we may use the simple code version. */
571 CE_ReplaceOPC (L[0], OP65_ORA);
572 CS_DelEntries (S, I+2, 3);
574 /* Move the lda instruction after the first branch. This will
575 * improve speed, since the load is delayed after the first
578 CS_MoveEntry (S, I, I+4);
580 /* We will replace the ldx/cpx by lda/cmp */
581 CE_ReplaceOPC (L[0], OP65_LDA);
582 CE_ReplaceOPC (L[1], OP65_CMP);
584 /* Beware: If the first LDA instruction had a label, we have
585 * to move this label to the top of the sequence again.
587 if (CE_HasLabel (E)) {
588 CS_MoveLabels (S, E, L[0]);
601 /* Return the number of changes made */
607 unsigned OptCmp4 (CodeSeg* S)
608 /* Optimize compares of local variables:
621 unsigned Changes = 0;
623 /* Walk over the entries */
625 while (I < CS_GetEntryCount (S)) {
629 /* Check for the sequence */
630 if (IsLocalLoad16 (S, I, L, 9) && IsImmCmp16 (S, L+5)) {
632 if (L[5]->Num == 0 && L[7]->Num == 0) {
634 /* The value is zero, we may use the simple code version:
641 CE_ReplaceOPC (L[4], OP65_ORA);
642 CS_DelEntries (S, I+5, 3); /* cpx/bne/cmp */
643 CS_DelEntry (S, I+2); /* tax */
647 /* Change the code to just use the A register. Move the load
648 * of the low byte after the first branch if possible:
659 CS_DelEntry (S, I+2); /* tax */
660 CE_ReplaceOPC (L[5], OP65_CMP); /* cpx -> cmp */
661 CS_MoveEntry (S, I+4, I+2); /* cmp */
662 CS_MoveEntry (S, I+5, I+3); /* bne */
674 /* Return the number of changes made */
680 unsigned OptCmp5 (CodeSeg* S)
681 /* Search for calls to compare subroutines followed by a conditional branch
682 * and replace them by cheaper versions, since the branch means that the
683 * boolean value returned by these routines is not needed (we may also check
684 * that explicitly, but for the current code generator it is always true).
687 unsigned Changes = 0;
689 /* Walk over the entries */
691 while (I < CS_GetEntryCount (S)) {
697 CodeEntry* E = CS_GetEntry (S, I);
699 /* Check for the sequence */
700 if (E->OPC == OP65_JSR &&
701 (Cond = FindTosCmpCond (E->Arg)) != CMP_INV &&
702 (N = CS_GetNextEntry (S, I)) != 0 &&
703 (N->Info & OF_ZBRA) != 0 &&
706 /* The tos... functions will return a boolean value in a/x and
707 * the Z flag says if this value is zero or not. We will call
708 * a cheaper subroutine instead, one that does not return a
709 * boolean value but only valid flags. Note: jeq jumps if
710 * the condition is not met, jne jumps if the condition is met.
711 * Invert the code if we jump on condition not met.
713 if (GetBranchCond (N->OPC) == BC_EQ) {
714 /* Jumps if condition false, invert condition */
715 Cond = CmpInvertTab [Cond];
718 /* Replace the subroutine call. */
719 E = NewCodeEntry (OP65_JSR, AM65_ABS, "tosicmp", 0, E->LI);
720 CS_InsertEntry (S, E, I+1);
723 /* Replace the conditional branch */
724 ReplaceCmp (S, I+1, Cond);
726 /* Remember, we had changes */
736 /* Return the number of changes made */
742 unsigned OptCmp6 (CodeSeg* S)
743 /* Search for a sequence ldx/txa/branch and remove the txa if A is not
747 unsigned Changes = 0;
749 /* Walk over the entries */
751 while (I < CS_GetEntryCount (S)) {
756 CodeEntry* E = CS_GetEntry (S, I);
758 /* Check for the sequence */
759 if ((E->OPC == OP65_LDX) &&
760 CS_GetEntries (S, L, I+1, 2) &&
761 L[0]->OPC == OP65_TXA &&
762 !CE_HasLabel (L[0]) &&
763 (L[1]->Info & OF_FBRA) != 0 &&
764 !CE_HasLabel (L[1]) &&
765 !RegAUsed (S, I+3)) {
768 CS_DelEntry (S, I+1);
770 /* Remember, we had changes */
780 /* Return the number of changes made */
786 unsigned OptCmp7 (CodeSeg* S)
787 /* Check for register compares where the contents of the register and therefore
788 * the result of the compare is known.
791 unsigned Changes = 0;
794 /* Generate register info for this step */
797 /* Walk over the entries */
799 while (I < CS_GetEntryCount (S)) {
804 CodeEntry* E = CS_GetEntry (S, I);
806 /* Check for a compare against an immediate value */
807 if ((E->Info & OF_CMP) != 0 &&
808 (RegVal = GetCmpRegVal (E)) >= 0 &&
811 /* We are able to evaluate the compare at compile time. Check if
812 * one or more branches are ahead.
814 unsigned JumpsChanged = 0;
816 while ((N = CS_GetNextEntry (S, I)) != 0 && /* Followed by something.. */
817 (N->Info & OF_CBRA) != 0 && /* ..that is a cond branch.. */
818 !CE_HasLabel (N)) { /* ..and has no label */
820 /* Evaluate the branch condition */
822 switch (GetBranchCond (N->OPC)) {
824 Cond = ((unsigned char)RegVal) < ((unsigned char)E->Num);
828 Cond = ((unsigned char)RegVal) >= ((unsigned char)E->Num);
832 Cond = ((unsigned char)RegVal) == ((unsigned char)E->Num);
836 Cond = ((signed char)RegVal) < ((signed char)E->Num);
840 Cond = ((unsigned char)RegVal) != ((unsigned char)E->Num);
844 Cond = ((signed char)RegVal) >= ((signed char)E->Num);
849 /* Not set by the compare operation, bail out (Note:
850 * Just skipping anything here is rather stupid, but
851 * the sequence is never generated by the compiler,
852 * so it's quite safe to skip).
857 Internal ("Unknown branch condition");
861 /* If the condition is false, we may remove the jump. Otherwise
862 * the branch will always be taken, so we may replace it by a
863 * jump (and bail out).
866 CS_DelEntry (S, I+1);
868 CodeLabel* L = N->JumpTo;
869 CodeEntry* X = NewCodeEntry (OP65_JMP, AM65_BRA, L->Name, L, N->LI);
870 CS_InsertEntry (S, X, I+2);
871 CS_DelEntry (S, I+1);
874 /* Remember, we had changes */
879 /* If we have made changes above, we may also remove the compare */
892 /* Free register info */
895 /* Return the number of changes made */