1 /*-------------------------------------------------------------------------
3 pcode.c - post code generation
5 Written By - Scott Dattalo scott@dattalo.com
6 Ported to PIC16 By - Martin Dubuc m.dubuc@rogers.com
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 -------------------------------------------------------------------------*/
25 #include "common.h" // Include everything in the SDCC src directory
31 #include "pcodeflow.h"
35 extern char *pic16_aopGet (struct asmop *aop, int offset, bool bit16, bool dname);
37 #if defined(__BORLANDC__) || defined(_MSC_VER)
38 #define STRCASECMP stricmp
41 #define STRCASECMP strcasecmp
44 #define DUMP_DF_GRAPHS 0
46 /****************************************************************/
47 /****************************************************************/
49 static peepCommand peepCommands[] = {
51 {NOTBITSKIP, "_NOTBITSKIP_"},
52 {BITSKIP, "_BITSKIP_"},
53 {INVERTBITSKIP, "_INVERTBITSKIP_"},
60 // Eventually this will go into device dependent files:
61 pCodeOpReg pic16_pc_status = {{PO_STATUS, "STATUS"}, -1, NULL,0,NULL};
62 pCodeOpReg pic16_pc_intcon = {{PO_INTCON, "INTCON"}, -1, NULL,0,NULL};
63 pCodeOpReg pic16_pc_pcl = {{PO_PCL, "PCL"}, -1, NULL,0,NULL};
64 pCodeOpReg pic16_pc_pclath = {{PO_PCLATH, "PCLATH"}, -1, NULL,0,NULL};
65 pCodeOpReg pic16_pc_pclatu = {{PO_PCLATU, "PCLATU"}, -1, NULL,0,NULL}; // patch 14
66 pCodeOpReg pic16_pc_wreg = {{PO_WREG, "WREG"}, -1, NULL,0,NULL};
67 pCodeOpReg pic16_pc_bsr = {{PO_BSR, "BSR"}, -1, NULL,0,NULL};
69 pCodeOpReg pic16_pc_tosl = {{PO_SFR_REGISTER, "TOSL"}, -1, NULL,0,NULL}; // patch 14
70 pCodeOpReg pic16_pc_tosh = {{PO_SFR_REGISTER, "TOSH"}, -1, NULL,0,NULL}; //
71 pCodeOpReg pic16_pc_tosu = {{PO_SFR_REGISTER, "TOSU"}, -1, NULL,0,NULL}; // patch 14
73 pCodeOpReg pic16_pc_tblptrl = {{PO_SFR_REGISTER, "TBLPTRL"}, -1, NULL,0,NULL}; // patch 15
74 pCodeOpReg pic16_pc_tblptrh = {{PO_SFR_REGISTER, "TBLPTRH"}, -1, NULL,0,NULL}; //
75 pCodeOpReg pic16_pc_tblptru = {{PO_SFR_REGISTER, "TBLPTRU"}, -1, NULL,0,NULL}; //
76 pCodeOpReg pic16_pc_tablat = {{PO_SFR_REGISTER, "TABLAT"}, -1, NULL,0,NULL}; // patch 15
78 //pCodeOpReg pic16_pc_fsr0 = {{PO_FSR0, "FSR0"}, -1, NULL,0,NULL}; //deprecated !
80 pCodeOpReg pic16_pc_fsr0l = {{PO_FSR0, "FSR0L"}, -1, NULL, 0, NULL};
81 pCodeOpReg pic16_pc_fsr0h = {{PO_FSR0, "FSR0H"}, -1, NULL, 0, NULL};
82 pCodeOpReg pic16_pc_fsr1l = {{PO_FSR0, "FSR1L"}, -1, NULL, 0, NULL};
83 pCodeOpReg pic16_pc_fsr1h = {{PO_FSR0, "FSR1H"}, -1, NULL, 0, NULL};
84 pCodeOpReg pic16_pc_fsr2l = {{PO_FSR0, "FSR2L"}, -1, NULL, 0, NULL};
85 pCodeOpReg pic16_pc_fsr2h = {{PO_FSR0, "FSR2H"}, -1, NULL, 0, NULL};
87 pCodeOpReg pic16_pc_indf0 = {{PO_INDF0, "INDF0"}, -1, NULL,0,NULL};
88 pCodeOpReg pic16_pc_postinc0 = {{PO_INDF0, "POSTINC0"}, -1, NULL, 0, NULL};
89 pCodeOpReg pic16_pc_postdec0 = {{PO_INDF0, "POSTDEC0"}, -1, NULL, 0, NULL};
90 pCodeOpReg pic16_pc_preinc0 = {{PO_INDF0, "PREINC0"}, -1, NULL, 0, NULL};
91 pCodeOpReg pic16_pc_plusw0 = {{PO_INDF0, "PLUSW0"}, -1, NULL, 0, NULL};
93 pCodeOpReg pic16_pc_indf1 = {{PO_INDF0, "INDF1"}, -1, NULL,0,NULL};
94 pCodeOpReg pic16_pc_postinc1 = {{PO_INDF0, "POSTINC1"}, -1, NULL, 0, NULL};
95 pCodeOpReg pic16_pc_postdec1 = {{PO_INDF0, "POSTDEC1"}, -1, NULL, 0, NULL};
96 pCodeOpReg pic16_pc_preinc1 = {{PO_INDF0, "PREINC1"}, -1, NULL, 0, NULL};
97 pCodeOpReg pic16_pc_plusw1 = {{PO_INDF0, "PLUSW1"}, -1, NULL, 0, NULL};
99 pCodeOpReg pic16_pc_indf2 = {{PO_INDF0, "INDF2"}, -1, NULL,0,NULL};
100 pCodeOpReg pic16_pc_postinc2 = {{PO_INDF0, "POSTINC2"}, -1, NULL, 0, NULL};
101 pCodeOpReg pic16_pc_postdec2 = {{PO_INDF0, "POSTDEC2"}, -1, NULL, 0, NULL};
102 pCodeOpReg pic16_pc_preinc2 = {{PO_INDF0, "PREINC2"}, -1, NULL, 0, NULL};
103 pCodeOpReg pic16_pc_plusw2 = {{PO_INDF0, "PLUSW2"}, -1, NULL, 0, NULL};
105 pCodeOpReg pic16_pc_prodl = {{PO_PRODL, "PRODL"}, -1, NULL, 0, NULL};
106 pCodeOpReg pic16_pc_prodh = {{PO_PRODH, "PRODH"}, -1, NULL, 0, NULL};
108 /* EEPROM registers */
109 pCodeOpReg pic16_pc_eecon1 = {{PO_SFR_REGISTER, "EECON1"}, -1, NULL, 0, NULL};
110 pCodeOpReg pic16_pc_eecon2 = {{PO_SFR_REGISTER, "EECON2"}, -1, NULL, 0, NULL};
111 pCodeOpReg pic16_pc_eedata = {{PO_SFR_REGISTER, "EEDATA"}, -1, NULL, 0, NULL};
112 pCodeOpReg pic16_pc_eeadr = {{PO_SFR_REGISTER, "EEADR"}, -1, NULL, 0, NULL};
114 pCodeOpReg pic16_pc_kzero = {{PO_GPR_REGISTER, "KZ"}, -1, NULL,0,NULL};
115 pCodeOpReg pic16_pc_wsave = {{PO_GPR_REGISTER, "WSAVE"}, -1, NULL,0,NULL};
116 pCodeOpReg pic16_pc_ssave = {{PO_GPR_REGISTER, "SSAVE"}, -1, NULL,0,NULL};
118 pCodeOpReg *pic16_stackpnt_lo;
119 pCodeOpReg *pic16_stackpnt_hi;
120 pCodeOpReg *pic16_stack_postinc;
121 pCodeOpReg *pic16_stack_postdec;
122 pCodeOpReg *pic16_stack_preinc;
123 pCodeOpReg *pic16_stack_plusw;
125 pCodeOpReg *pic16_framepnt_lo;
126 pCodeOpReg *pic16_framepnt_hi;
127 pCodeOpReg *pic16_frame_postinc;
128 pCodeOpReg *pic16_frame_postdec;
129 pCodeOpReg *pic16_frame_preinc;
130 pCodeOpReg *pic16_frame_plusw;
132 pCodeOpReg pic16_pc_gpsimio = {{PO_GPR_REGISTER, "GPSIMIO"}, -1, NULL, 0, NULL};
133 pCodeOpReg pic16_pc_gpsimio2 = {{PO_GPR_REGISTER, "GPSIMIO2"}, -1, NULL, 0, NULL};
135 char *OPT_TYPE_STR[] = { "begin", "end", "jumptable_begin", "jumptable_end" };
136 char *LR_TYPE_STR[] = { "entry begin", "entry end", "exit begin", "exit end" };
139 static int mnemonics_initialized = 0;
142 static hTab *pic16MnemonicsHash = NULL;
143 static hTab *pic16pCodePeepCommandsHash = NULL;
145 static pFile *the_pFile = NULL;
146 static pBlock *pb_dead_pcodes = NULL;
148 /* Hardcoded flags to change the behavior of the PIC port */
149 static int peepOptimizing = 1; /* run the peephole optimizer if nonzero */
150 static int functionInlining = 1; /* inline functions if nonzero */
151 int pic16_debug_verbose = 0; /* Set true to inundate .asm file */
153 int pic16_pcode_verbose = 0;
155 //static int GpCodeSequenceNumber = 1;
156 static int GpcFlowSeq = 1;
158 extern void pic16_RemoveUnusedRegisters(void);
159 extern void pic16_RegsUnMapLiveRanges(void);
160 extern void pic16_BuildFlowTree(pBlock *pb);
161 extern void pic16_pCodeRegOptimizeRegUsage(int level);
162 extern int pic16_picIsInitialized(void);
163 extern void SAFE_snprintf(char **str, size_t *size, const char *format, ...);
164 extern int mnem2key(unsigned char const *mnem);
166 /****************************************************************/
167 /* Forward declarations */
168 /****************************************************************/
170 void pic16_unlinkpCode(pCode *pc);
172 static void genericAnalyze(pCode *pc);
173 static void AnalyzeGOTO(pCode *pc);
174 static void AnalyzeSKIP(pCode *pc);
175 static void AnalyzeRETURN(pCode *pc);
178 static void genericDestruct(pCode *pc);
179 static void genericPrint(FILE *of,pCode *pc);
181 static void pCodePrintLabel(FILE *of, pCode *pc);
182 static void pCodePrintFunction(FILE *of, pCode *pc);
183 static void pCodeOpPrint(FILE *of, pCodeOp *pcop);
184 static char *pic16_get_op_from_instruction( pCodeInstruction *pcc);
185 char *pic16_get_op(pCodeOp *pcop,char *buff,size_t buf_size);
186 int pCodePeepMatchLine(pCodePeep *peepBlock, pCode *pcs, pCode *pcd);
187 int pic16_pCodePeepMatchRule(pCode *pc);
188 static void pBlockStats(FILE *of, pBlock *pb);
189 static pBlock *newpBlock(void);
190 extern void pic16_pCodeInsertAfter(pCode *pc1, pCode *pc2);
191 extern pCodeOp *pic16_popCopyReg(pCodeOpReg *pc);
192 pCodeOp *pic16_popCopyGPR2Bit(pCodeOp *pc, int bitval);
193 void pic16_pCodeRegMapLiveRanges(pBlock *pb);
194 void OptimizeLocalRegs(void);
195 pCodeOp *pic16_popGet2p(pCodeOp *src, pCodeOp *dst);
197 char *dumpPicOptype(PIC_OPTYPE type);
199 pCodeOp *pic16_popGetLit2(int, pCodeOp *);
200 pCodeOp *pic16_popGetLit(int);
201 pCodeOp *pic16_popGetWithString(char *);
202 extern int inWparamList(char *s);
204 /** data flow optimization helpers **/
205 #if defined (DUMP_DF_GRAPHS) && DUMP_DF_GRAPHS > 0
206 static void pic16_vcg_dump (FILE *of, pBlock *pb);
207 static void pic16_vcg_dump_default (pBlock *pb);
209 static int pic16_pCodeIsAlive (pCode *pc);
210 static void pic16_df_stats ();
211 static void pic16_createDF (pBlock *pb);
212 static int pic16_removeUnusedRegistersDF ();
213 static void pic16_destructDF (pBlock *pb);
214 static void releaseStack ();
216 /****************************************************************/
217 /* PIC Instructions */
218 /****************************************************************/
220 pCodeInstruction pic16_pciADDWF = {
221 {PC_OPCODE, NULL, NULL, 0, NULL,
235 1,0, // dest, bit instruction
237 0, // literal operand
239 0, // fast call/return mode select bit
240 0, // second memory operand
241 0, // second literal operand
243 (PCC_W | PCC_REGISTER), // inCond
244 (PCC_REGISTER | PCC_STATUS), // outCond
248 pCodeInstruction pic16_pciADDFW = {
249 {PC_OPCODE, NULL, NULL, 0, NULL,
263 0,0, // dest, bit instruction
265 0, // literal operand
267 0, // fast call/return mode select bit
268 0, // second memory operand
269 0, // second literal operand
271 (PCC_W | PCC_REGISTER), // inCond
272 (PCC_W | PCC_STATUS), // outCond
276 pCodeInstruction pic16_pciADDWFC = { // mdubuc - New
277 {PC_OPCODE, NULL, NULL, 0, NULL,
291 1,0, // dest, bit instruction
293 0, // literal operand
295 0, // fast call/return mode select bit
296 0, // second memory operand
297 0, // second literal operand
299 (PCC_W | PCC_REGISTER | PCC_C), // inCond
300 (PCC_REGISTER | PCC_STATUS), // outCond
304 pCodeInstruction pic16_pciADDFWC = {
305 {PC_OPCODE, NULL, NULL, 0, NULL,
319 0,0, // dest, bit instruction
321 0, // literal operand
323 0, // fast call/return mode select bit
324 0, // second memory operand
325 0, // second literal operand
327 (PCC_W | PCC_REGISTER | PCC_C), // inCond
328 (PCC_W | PCC_STATUS), // outCond
332 pCodeInstruction pic16_pciADDLW = {
333 {PC_OPCODE, NULL, NULL, 0, NULL,
347 0,0, // dest, bit instruction
349 1, // literal operand
351 0, // fast call/return mode select bit
352 0, // second memory operand
353 0, // second literal operand
355 (PCC_W | PCC_LITERAL), // inCond
356 (PCC_W | PCC_STATUS), // outCond
360 pCodeInstruction pic16_pciANDLW = {
361 {PC_OPCODE, NULL, NULL, 0, NULL,
375 0,0, // dest, bit instruction
377 1, // literal operand
379 0, // fast call/return mode select bit
380 0, // second memory operand
381 0, // second literal operand
383 (PCC_W | PCC_LITERAL), // inCond
384 (PCC_W | PCC_Z | PCC_N), // outCond
388 pCodeInstruction pic16_pciANDWF = {
389 {PC_OPCODE, NULL, NULL, 0, NULL,
403 1,0, // dest, bit instruction
405 0, // literal operand
407 0, // fast call/return mode select bit
408 0, // second memory operand
409 0, // second literal operand
411 (PCC_W | PCC_REGISTER), // inCond
412 (PCC_REGISTER | PCC_Z | PCC_N), // outCond
416 pCodeInstruction pic16_pciANDFW = {
417 {PC_OPCODE, NULL, NULL, 0, NULL,
431 0,0, // dest, bit instruction
433 0, // literal operand
435 0, // fast call/return mode select bit
436 0, // second memory operand
437 0, // second literal operand
439 (PCC_W | PCC_REGISTER), // inCond
440 (PCC_W | PCC_Z | PCC_N) // outCond
443 pCodeInstruction pic16_pciBC = { // mdubuc - New
444 {PC_OPCODE, NULL, NULL, 0, NULL,
458 0,0, // dest, bit instruction
460 0, // literal operand
462 0, // fast call/return mode select bit
463 0, // second memory operand
464 0, // second literal operand
466 (PCC_REL_ADDR | PCC_C), // inCond
471 pCodeInstruction pic16_pciBCF = {
472 {PC_OPCODE, NULL, NULL, 0, NULL,
486 1,1, // dest, bit instruction
488 0, // literal operand
490 0, // fast call/return mode select bit
491 0, // second memory operand
492 0, // second literal operand
494 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
495 PCC_REGISTER, // outCond
499 pCodeInstruction pic16_pciBN = { // mdubuc - New
500 {PC_OPCODE, NULL, NULL, 0, NULL,
514 0,0, // dest, bit instruction
516 0, // literal operand
518 0, // fast call/return mode select bit
519 0, // second memory operand
520 0, // second literal operand
522 (PCC_REL_ADDR | PCC_N), // inCond
523 PCC_NONE , // outCond
527 pCodeInstruction pic16_pciBNC = { // mdubuc - New
528 {PC_OPCODE, NULL, NULL, 0, NULL,
542 0,0, // dest, bit instruction
544 0, // literal operand
546 0, // fast call/return mode select bit
547 0, // second memory operand
548 0, // second literal operand
550 (PCC_REL_ADDR | PCC_C), // inCond
551 PCC_NONE , // outCond
555 pCodeInstruction pic16_pciBNN = { // mdubuc - New
556 {PC_OPCODE, NULL, NULL, 0, NULL,
570 0,0, // dest, bit instruction
572 0, // literal operand
574 0, // fast call/return mode select bit
575 0, // second memory operand
576 0, // second literal operand
578 (PCC_REL_ADDR | PCC_N), // inCond
579 PCC_NONE , // outCond
583 pCodeInstruction pic16_pciBNOV = { // mdubuc - New
584 {PC_OPCODE, NULL, NULL, 0, NULL,
598 0,0, // dest, bit instruction
600 0, // literal operand
602 0, // fast call/return mode select bit
603 0, // second memory operand
604 0, // second literal operand
606 (PCC_REL_ADDR | PCC_OV), // inCond
607 PCC_NONE , // outCond
611 pCodeInstruction pic16_pciBNZ = { // mdubuc - New
612 {PC_OPCODE, NULL, NULL, 0, NULL,
626 0,0, // dest, bit instruction
628 0, // literal operand
630 0, // fast call/return mode select bit
631 0, // second memory operand
632 0, // second literal operand
634 (PCC_REL_ADDR | PCC_Z), // inCond
635 PCC_NONE , // outCond
639 pCodeInstruction pic16_pciBOV = { // mdubuc - New
640 {PC_OPCODE, NULL, NULL, 0, NULL,
654 0,0, // dest, bit instruction
656 0, // literal operand
658 0, // fast call/return mode select bit
659 0, // second memory operand
660 0, // second literal operand
662 (PCC_REL_ADDR | PCC_OV), // inCond
663 PCC_NONE , // outCond
667 pCodeInstruction pic16_pciBRA = { // mdubuc - New
668 {PC_OPCODE, NULL, NULL, 0, NULL,
682 0,0, // dest, bit instruction
684 0, // literal operand
686 0, // fast call/return mode select bit
687 0, // second memory operand
688 0, // second literal operand
690 PCC_REL_ADDR, // inCond
691 PCC_NONE , // outCond
695 pCodeInstruction pic16_pciBSF = {
696 {PC_OPCODE, NULL, NULL, 0, NULL,
710 1,1, // dest, bit instruction
712 0, // literal operand
714 0, // fast call/return mode select bit
715 0, // second memory operand
716 0, // second literal operand
718 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
719 (PCC_REGISTER | PCC_EXAMINE_PCOP), // outCond
723 pCodeInstruction pic16_pciBTFSC = {
724 {PC_OPCODE, NULL, NULL, 0, NULL,
738 0,1, // dest, bit instruction
740 0, // literal operand
742 0, // fast call/return mode select bit
743 0, // second memory operand
744 0, // second literal operand
746 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
747 PCC_EXAMINE_PCOP, // outCond
751 pCodeInstruction pic16_pciBTFSS = {
752 {PC_OPCODE, NULL, NULL, 0, NULL,
766 0,1, // dest, bit instruction
768 0, // literal operand
770 0, // fast call/return mode select bit
771 0, // second memory operand
772 0, // second literal operand
774 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
775 PCC_EXAMINE_PCOP, // outCond
779 pCodeInstruction pic16_pciBTG = { // mdubuc - New
780 {PC_OPCODE, NULL, NULL, 0, NULL,
794 0,1, // dest, bit instruction
796 0, // literal operand
798 0, // fast call/return mode select bit
799 0, // second memory operand
800 0, // second literal operand
802 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
803 (PCC_REGISTER | PCC_EXAMINE_PCOP), // outCond
807 pCodeInstruction pic16_pciBZ = { // mdubuc - New
808 {PC_OPCODE, NULL, NULL, 0, NULL,
822 0,0, // dest, bit instruction
824 0, // literal operand
826 0, // fast call/return mode select bit
827 0, // second memory operand
828 0, // second literal operand
830 (PCC_REL_ADDR | PCC_Z), // inCond
835 pCodeInstruction pic16_pciCALL = {
836 {PC_OPCODE, NULL, NULL, 0, NULL,
850 0,0, // dest, bit instruction
852 0, // literal operand
854 1, // fast call/return mode select bit
855 0, // second memory operand
856 0, // second literal operand
863 pCodeInstruction pic16_pciCOMF = {
864 {PC_OPCODE, NULL, NULL, 0, NULL,
878 1,0, // dest, bit instruction
880 0, // literal operand
882 0, // fast call/return mode select bit
883 0, // second memory operand
884 0, // second literal operand
886 PCC_REGISTER, // inCond
887 (PCC_REGISTER | PCC_Z | PCC_N) , // outCond
891 pCodeInstruction pic16_pciCOMFW = {
892 {PC_OPCODE, NULL, NULL, 0, NULL,
906 0,0, // dest, bit instruction
908 0, // literal operand
910 0, // fast call/return mode select bit
911 0, // second memory operand
912 0, // second literal operand
914 PCC_REGISTER, // inCond
915 (PCC_W | PCC_Z | PCC_N) , // outCond
919 pCodeInstruction pic16_pciCLRF = {
920 {PC_OPCODE, NULL, NULL, 0, NULL,
934 0,0, // dest, bit instruction
936 0, // literal operand
938 0, // fast call/return mode select bit
939 0, // second memory operand
940 0, // second literal operand
943 (PCC_REGISTER | PCC_Z), // outCond
947 pCodeInstruction pic16_pciCLRWDT = {
948 {PC_OPCODE, NULL, NULL, 0, NULL,
962 0,0, // dest, bit instruction
964 0, // literal operand
966 0, // fast call/return mode select bit
967 0, // second memory operand
968 0, // second literal operand
971 PCC_NONE , // outCond
975 pCodeInstruction pic16_pciCPFSEQ = { // mdubuc - New
976 {PC_OPCODE, NULL, NULL, 0, NULL,
990 0,0, // dest, bit instruction
992 0, // literal operand
994 0, // fast call/return mode select bit
995 0, // second memory operand
996 0, // second literal operand
998 (PCC_W | PCC_REGISTER), // inCond
999 PCC_NONE , // outCond
1003 pCodeInstruction pic16_pciCPFSGT = { // mdubuc - New
1004 {PC_OPCODE, NULL, NULL, 0, NULL,
1011 NULL, // from branch
1018 0,0, // dest, bit instruction
1019 1,1, // branch, skip
1020 0, // literal operand
1021 1, // RAM access bit
1022 0, // fast call/return mode select bit
1023 0, // second memory operand
1024 0, // second literal operand
1026 (PCC_W | PCC_REGISTER), // inCond
1027 PCC_NONE , // outCond
1031 pCodeInstruction pic16_pciCPFSLT = { // mdubuc - New
1032 {PC_OPCODE, NULL, NULL, 0, NULL,
1039 NULL, // from branch
1046 1,0, // dest, bit instruction
1047 1,1, // branch, skip
1048 0, // literal operand
1049 1, // RAM access bit
1050 0, // fast call/return mode select bit
1051 0, // second memory operand
1052 0, // second literal operand
1054 (PCC_W | PCC_REGISTER), // inCond
1055 PCC_NONE , // outCond
1059 pCodeInstruction pic16_pciDAW = {
1060 {PC_OPCODE, NULL, NULL, 0, NULL,
1067 NULL, // from branch
1074 0,0, // dest, bit instruction
1075 0,0, // branch, skip
1076 0, // literal operand
1077 0, // RAM access bit
1078 0, // fast call/return mode select bit
1079 0, // second memory operand
1080 0, // second literal operand
1083 (PCC_W | PCC_C), // outCond
1087 pCodeInstruction pic16_pciDCFSNZ = { // mdubuc - New
1088 {PC_OPCODE, NULL, NULL, 0, NULL,
1095 NULL, // from branch
1102 1,0, // dest, bit instruction
1103 1,1, // branch, skip
1104 0, // literal operand
1105 1, // RAM access bit
1106 0, // fast call/return mode select bit
1107 0, // second memory operand
1108 0, // second literal operand
1110 PCC_REGISTER, // inCond
1111 PCC_REGISTER , // outCond
1115 pCodeInstruction pic16_pciDCFSNZW = { // mdubuc - New
1116 {PC_OPCODE, NULL, NULL, 0, NULL,
1123 NULL, // from branch
1130 0,0, // dest, bit instruction
1131 1,1, // branch, skip
1132 0, // literal operand
1133 1, // RAM access bit
1134 0, // fast call/return mode select bit
1135 0, // second memory operand
1136 0, // second literal operand
1138 PCC_REGISTER, // inCond
1143 pCodeInstruction pic16_pciDECF = {
1144 {PC_OPCODE, NULL, NULL, 0, NULL,
1151 NULL, // from branch
1158 1,0, // dest, bit instruction
1159 0,0, // branch, skip
1160 0, // literal operand
1161 1, // RAM access bit
1162 0, // fast call/return mode select bit
1163 0, // second memory operand
1164 0, // second literal operand
1166 PCC_REGISTER, // inCond
1167 (PCC_REGISTER | PCC_STATUS) , // outCond
1171 pCodeInstruction pic16_pciDECFW = {
1172 {PC_OPCODE, NULL, NULL, 0, NULL,
1179 NULL, // from branch
1186 0,0, // dest, bit instruction
1187 0,0, // branch, skip
1188 0, // literal operand
1189 1, // RAM access bit
1190 0, // fast call/return mode select bit
1191 0, // second memory operand
1192 0, // second literal operand
1194 PCC_REGISTER, // inCond
1195 (PCC_W | PCC_STATUS) , // outCond
1199 pCodeInstruction pic16_pciDECFSZ = {
1200 {PC_OPCODE, NULL, NULL, 0, NULL,
1207 NULL, // from branch
1214 1,0, // dest, bit instruction
1215 1,1, // branch, skip
1216 0, // literal operand
1217 1, // RAM access bit
1218 0, // fast call/return mode select bit
1219 0, // second memory operand
1220 0, // second literal operand
1222 PCC_REGISTER, // inCond
1223 PCC_REGISTER , // outCond
1227 pCodeInstruction pic16_pciDECFSZW = {
1228 {PC_OPCODE, NULL, NULL, 0, NULL,
1235 NULL, // from branch
1242 0,0, // dest, bit instruction
1243 1,1, // branch, skip
1244 0, // literal operand
1245 1, // RAM access bit
1246 0, // fast call/return mode select bit
1247 0, // second memory operand
1248 0, // second literal operand
1250 PCC_REGISTER, // inCond
1255 pCodeInstruction pic16_pciGOTO = {
1256 {PC_OPCODE, NULL, NULL, 0, NULL,
1263 NULL, // from branch
1270 0,0, // dest, bit instruction
1271 1,0, // branch, skip
1272 0, // literal operand
1273 0, // RAM access bit
1274 0, // fast call/return mode select bit
1275 0, // second memory operand
1276 0, // second literal operand
1278 PCC_REL_ADDR, // inCond
1279 PCC_NONE , // outCond
1283 pCodeInstruction pic16_pciINCF = {
1284 {PC_OPCODE, NULL, NULL, 0, NULL,
1291 NULL, // from branch
1298 1,0, // dest, bit instruction
1299 0,0, // branch, skip
1300 0, // literal operand
1301 1, // RAM access bit
1302 0, // fast call/return mode select bit
1303 0, // second memory operand
1304 0, // second literal operand
1306 PCC_REGISTER, // inCond
1307 (PCC_REGISTER | PCC_STATUS), // outCond
1311 pCodeInstruction pic16_pciINCFW = {
1312 {PC_OPCODE, NULL, NULL, 0, NULL,
1319 NULL, // from branch
1326 0,0, // dest, bit instruction
1327 0,0, // branch, skip
1328 0, // literal operand
1329 1, // RAM access bit
1330 0, // fast call/return mode select bit
1331 0, // second memory operand
1332 0, // second literal operand
1334 PCC_REGISTER, // inCond
1335 (PCC_W | PCC_STATUS) , // outCond
1339 pCodeInstruction pic16_pciINCFSZ = {
1340 {PC_OPCODE, NULL, NULL, 0, NULL,
1347 NULL, // from branch
1354 1,0, // dest, bit instruction
1355 1,1, // branch, skip
1356 0, // literal operand
1357 1, // RAM access bit
1358 0, // fast call/return mode select bit
1359 0, // second memory operand
1360 0, // second literal operand
1362 PCC_REGISTER, // inCond
1363 PCC_REGISTER , // outCond
1367 pCodeInstruction pic16_pciINCFSZW = {
1368 {PC_OPCODE, NULL, NULL, 0, NULL,
1375 NULL, // from branch
1382 0,0, // dest, bit instruction
1383 1,1, // branch, skip
1384 0, // literal operand
1385 1, // RAM access bit
1386 0, // fast call/return mode select bit
1387 0, // second memory operand
1388 0, // second literal operand
1390 PCC_REGISTER, // inCond
1395 pCodeInstruction pic16_pciINFSNZ = { // mdubuc - New
1396 {PC_OPCODE, NULL, NULL, 0, NULL,
1403 NULL, // from branch
1410 1,0, // dest, bit instruction
1411 1,1, // branch, skip
1412 0, // literal operand
1413 1, // RAM access bit
1414 0, // fast call/return mode select bit
1415 0, // second memory operand
1416 0, // second literal operand
1418 PCC_REGISTER, // inCond
1419 PCC_REGISTER , // outCond
1423 pCodeInstruction pic16_pciINFSNZW = { // vrokas - New
1424 {PC_OPCODE, NULL, NULL, 0, NULL,
1431 NULL, // from branch
1438 0,0, // dest, bit instruction
1439 1,1, // branch, skip
1440 0, // literal operand
1441 1, // RAM access bit
1442 0, // fast call/return mode select bit
1443 0, // second memory operand
1444 0, // second literal operand
1446 PCC_REGISTER, // inCond
1451 pCodeInstruction pic16_pciIORWF = {
1452 {PC_OPCODE, NULL, NULL, 0, NULL,
1459 NULL, // from branch
1466 1,0, // dest, bit instruction
1467 0,0, // branch, skip
1468 0, // literal operand
1469 1, // RAM access bit
1470 0, // fast call/return mode select bit
1471 0, // second memory operand
1472 0, // second literal operand
1474 (PCC_W | PCC_REGISTER), // inCond
1475 (PCC_REGISTER | PCC_Z | PCC_N), // outCond
1479 pCodeInstruction pic16_pciIORFW = {
1480 {PC_OPCODE, NULL, NULL, 0, NULL,
1487 NULL, // from branch
1494 0,0, // dest, bit instruction
1495 0,0, // branch, skip
1496 0, // literal operand
1497 1, // RAM access bit
1498 0, // fast call/return mode select bit
1499 0, // second memory operand
1500 0, // second literal operand
1502 (PCC_W | PCC_REGISTER), // inCond
1503 (PCC_W | PCC_Z | PCC_N), // outCond
1507 pCodeInstruction pic16_pciIORLW = {
1508 {PC_OPCODE, NULL, NULL, 0, NULL,
1515 NULL, // from branch
1522 0,0, // dest, bit instruction
1523 0,0, // branch, skip
1524 1, // literal operand
1525 0, // RAM access bit
1526 0, // fast call/return mode select bit
1527 0, // second memory operand
1528 0, // second literal operand
1530 (PCC_W | PCC_LITERAL), // inCond
1531 (PCC_W | PCC_Z | PCC_N), // outCond
1535 pCodeInstruction pic16_pciLFSR = { // mdubuc - New
1536 {PC_OPCODE, NULL, NULL, 0, NULL,
1543 NULL, // from branch
1550 0,0, // dest, bit instruction
1551 0,0, // branch, skip
1552 1, // literal operand
1553 0, // RAM access bit
1554 0, // fast call/return mode select bit
1555 0, // second memory operand
1556 1, // second literal operand
1558 PCC_LITERAL, // inCond
1559 PCC_NONE, // outCond
1563 pCodeInstruction pic16_pciMOVF = {
1564 {PC_OPCODE, NULL, NULL, 0, NULL,
1571 NULL, // from branch
1578 1,0, // dest, bit instruction
1579 0,0, // branch, skip
1580 0, // literal operand
1581 1, // RAM access bit
1582 0, // fast call/return mode select bit
1583 0, // second memory operand
1584 0, // second literal operand
1586 PCC_REGISTER, // inCond
1587 (PCC_Z | PCC_N), // outCond
1591 pCodeInstruction pic16_pciMOVFW = {
1592 {PC_OPCODE, NULL, NULL, 0, NULL,
1599 NULL, // from branch
1606 0,0, // dest, bit instruction
1607 0,0, // branch, skip
1608 0, // literal operand
1609 1, // RAM access bit
1610 0, // fast call/return mode select bit
1611 0, // second memory operand
1612 0, // second literal operand
1614 PCC_REGISTER, // inCond
1615 (PCC_W | PCC_N | PCC_Z), // outCond
1619 pCodeInstruction pic16_pciMOVFF = { // mdubuc - New
1620 {PC_OPCODE, NULL, NULL, 0, NULL,
1627 NULL, // from branch
1634 0,0, // dest, bit instruction
1635 0,0, // branch, skip
1636 0, // literal operand
1637 0, // RAM access bit
1638 0, // fast call/return mode select bit
1639 1, // second memory operand
1640 0, // second literal operand
1642 PCC_REGISTER, // inCond
1643 PCC_REGISTER2, // outCond
1647 pCodeInstruction pic16_pciMOVLB = { // mdubuc - New
1648 {PC_OPCODE, NULL, NULL, 0, NULL,
1654 NULL, // from branch
1661 0,0, // dest, bit instruction
1662 0,0, // branch, skip
1663 1, // literal operand
1664 0, // RAM access bit
1665 0, // fast call/return mode select bit
1666 0, // second memory operand
1667 0, // second literal operand
1669 (PCC_NONE | PCC_LITERAL), // inCond
1670 PCC_REGISTER, // outCond - BSR
1674 pCodeInstruction pic16_pciMOVLW = {
1675 {PC_OPCODE, NULL, NULL, 0, NULL,
1681 NULL, // from branch
1688 0,0, // dest, bit instruction
1689 0,0, // branch, skip
1690 1, // literal operand
1691 0, // RAM access bit
1692 0, // fast call/return mode select bit
1693 0, // second memory operand
1694 0, // second literal operand
1696 (PCC_NONE | PCC_LITERAL), // inCond
1701 pCodeInstruction pic16_pciMOVWF = {
1702 {PC_OPCODE, NULL, NULL, 0, NULL,
1709 NULL, // from branch
1716 0,0, // dest, bit instruction
1717 0,0, // branch, skip
1718 0, // literal operand
1719 1, // RAM access bit
1720 0, // fast call/return mode select bit
1721 0, // second memory operand
1722 0, // second literal operand
1725 PCC_REGISTER, // outCond
1729 pCodeInstruction pic16_pciMULLW = { // mdubuc - New
1730 {PC_OPCODE, NULL, NULL, 0, NULL,
1736 NULL, // from branch
1743 0,0, // dest, bit instruction
1744 0,0, // branch, skip
1745 1, // literal operand
1746 0, // RAM access bit
1747 0, // fast call/return mode select bit
1748 0, // second memory operand
1749 0, // second literal operand
1751 (PCC_W | PCC_LITERAL), // inCond
1752 PCC_NONE, // outCond - PROD
1756 pCodeInstruction pic16_pciMULWF = { // mdubuc - New
1757 {PC_OPCODE, NULL, NULL, 0, NULL,
1763 NULL, // from branch
1770 0,0, // dest, bit instruction
1771 0,0, // branch, skip
1772 0, // literal operand
1773 1, // RAM access bit
1774 0, // fast call/return mode select bit
1775 0, // second memory operand
1776 0, // second literal operand
1778 (PCC_W | PCC_REGISTER), // inCond
1779 PCC_REGISTER, // outCond - PROD
1783 pCodeInstruction pic16_pciNEGF = { // mdubuc - New
1784 {PC_OPCODE, NULL, NULL, 0, NULL,
1790 NULL, // from branch
1797 0,0, // dest, bit instruction
1798 0,0, // branch, skip
1799 0, // literal operand
1800 1, // RAM access bit
1801 0, // fast call/return mode select bit
1802 0, // second memory operand
1803 0, // second literal operand
1805 PCC_REGISTER, // inCond
1806 (PCC_REGISTER | PCC_STATUS), // outCond
1810 pCodeInstruction pic16_pciNOP = {
1811 {PC_OPCODE, NULL, NULL, 0, NULL,
1817 NULL, // from branch
1824 0,0, // dest, bit instruction
1825 0,0, // branch, skip
1826 0, // literal operand
1827 0, // RAM access bit
1828 0, // fast call/return mode select bit
1829 0, // second memory operand
1830 0, // second literal operand
1833 PCC_NONE, // outCond
1837 pCodeInstruction pic16_pciPOP = { // mdubuc - New
1838 {PC_OPCODE, NULL, NULL, 0, NULL,
1844 NULL, // from branch
1851 0,0, // dest, bit instruction
1852 0,0, // branch, skip
1853 0, // literal operand
1854 0, // RAM access bit
1855 0, // fast call/return mode select bit
1856 0, // second memory operand
1857 0, // second literal operand
1860 PCC_NONE , // outCond
1864 pCodeInstruction pic16_pciPUSH = {
1865 {PC_OPCODE, NULL, NULL, 0, NULL,
1871 NULL, // from branch
1878 0,0, // dest, bit instruction
1879 0,0, // branch, skip
1880 0, // literal operand
1881 0, // RAM access bit
1882 0, // fast call/return mode select bit
1883 0, // second memory operand
1884 0, // second literal operand
1887 PCC_NONE , // outCond
1891 pCodeInstruction pic16_pciRCALL = { // mdubuc - New
1892 {PC_OPCODE, NULL, NULL, 0, NULL,
1898 NULL, // from branch
1905 0,0, // dest, bit instruction
1906 1,0, // branch, skip
1907 0, // literal operand
1908 0, // RAM access bit
1909 0, // fast call/return mode select bit
1910 0, // second memory operand
1911 0, // second literal operand
1913 PCC_REL_ADDR, // inCond
1914 PCC_NONE , // outCond
1918 pCodeInstruction pic16_pciRETFIE = {
1919 {PC_OPCODE, NULL, NULL, 0, NULL,
1926 NULL, // from branch
1933 0,0, // dest, bit instruction
1934 1,0, // branch, skip
1935 0, // literal operand
1936 0, // RAM access bit
1937 1, // fast call/return mode select bit
1938 0, // second memory operand
1939 0, // second literal operand
1942 PCC_NONE, // outCond (not true... affects the GIE bit too)
1946 pCodeInstruction pic16_pciRETLW = {
1947 {PC_OPCODE, NULL, NULL, 0, NULL,
1954 NULL, // from branch
1961 0,0, // dest, bit instruction
1962 1,0, // branch, skip
1963 1, // literal operand
1964 0, // RAM access bit
1965 0, // fast call/return mode select bit
1966 0, // second memory operand
1967 0, // second literal operand
1969 PCC_LITERAL, // inCond
1974 pCodeInstruction pic16_pciRETURN = {
1975 {PC_OPCODE, NULL, NULL, 0, NULL,
1982 NULL, // from branch
1989 0,0, // dest, bit instruction
1990 1,0, // branch, skip
1991 0, // literal operand
1992 0, // RAM access bit
1993 1, // fast call/return mode select bit
1994 0, // second memory operand
1995 0, // second literal operand
1998 PCC_NONE, // outCond
2001 pCodeInstruction pic16_pciRLCF = { // mdubuc - New
2002 {PC_OPCODE, NULL, NULL, 0, NULL,
2009 NULL, // from branch
2016 1,0, // dest, bit instruction
2017 0,0, // branch, skip
2018 0, // literal operand
2019 1, // RAM access bit
2020 0, // fast call/return mode select bit
2021 0, // second memory operand
2022 0, // second literal operand
2024 (PCC_C | PCC_REGISTER), // inCond
2025 (PCC_REGISTER | PCC_C | PCC_Z | PCC_N), // outCond
2029 pCodeInstruction pic16_pciRLCFW = { // mdubuc - New
2030 {PC_OPCODE, NULL, NULL, 0, NULL,
2037 NULL, // from branch
2044 0,0, // dest, bit instruction
2045 0,0, // branch, skip
2046 0, // literal operand
2047 1, // RAM access bit
2048 0, // fast call/return mode select bit
2049 0, // second memory operand
2050 0, // second literal operand
2052 (PCC_C | PCC_REGISTER), // inCond
2053 (PCC_W | PCC_C | PCC_Z | PCC_N), // outCond
2057 pCodeInstruction pic16_pciRLNCF = { // mdubuc - New
2058 {PC_OPCODE, NULL, NULL, 0, NULL,
2065 NULL, // from branch
2072 1,0, // dest, bit instruction
2073 0,0, // branch, skip
2074 0, // literal operand
2075 1, // RAM access bit
2076 0, // fast call/return mode select bit
2077 0, // second memory operand
2078 0, // second literal operand
2080 PCC_REGISTER, // inCond
2081 (PCC_REGISTER | PCC_Z | PCC_N), // outCond
2084 pCodeInstruction pic16_pciRLNCFW = { // mdubuc - New
2085 {PC_OPCODE, NULL, NULL, 0, NULL,
2092 NULL, // from branch
2099 0,0, // dest, bit instruction
2100 0,0, // branch, skip
2101 0, // literal operand
2102 1, // RAM access bit
2103 0, // fast call/return mode select bit
2104 0, // second memory operand
2105 0, // second literal operand
2107 PCC_REGISTER, // inCond
2108 (PCC_W | PCC_Z | PCC_N), // outCond
2111 pCodeInstruction pic16_pciRRCF = { // mdubuc - New
2112 {PC_OPCODE, NULL, NULL, 0, NULL,
2119 NULL, // from branch
2126 1,0, // dest, bit instruction
2127 0,0, // branch, skip
2128 0, // literal operand
2129 1, // RAM access bit
2130 0, // fast call/return mode select bit
2131 0, // second memory operand
2132 0, // second literal operand
2134 (PCC_C | PCC_REGISTER), // inCond
2135 (PCC_REGISTER | PCC_C | PCC_Z | PCC_N), // outCond
2138 pCodeInstruction pic16_pciRRCFW = { // mdubuc - New
2139 {PC_OPCODE, NULL, NULL, 0, NULL,
2146 NULL, // from branch
2153 0,0, // dest, bit instruction
2154 0,0, // branch, skip
2155 0, // literal operand
2156 1, // RAM access bit
2157 0, // fast call/return mode select bit
2158 0, // second memory operand
2159 0, // second literal operand
2161 (PCC_C | PCC_REGISTER), // inCond
2162 (PCC_W | PCC_C | PCC_Z | PCC_N), // outCond
2165 pCodeInstruction pic16_pciRRNCF = { // mdubuc - New
2166 {PC_OPCODE, NULL, NULL, 0, NULL,
2173 NULL, // from branch
2180 1,0, // dest, bit instruction
2181 0,0, // branch, skip
2182 0, // literal operand
2183 1, // RAM access bit
2184 0, // fast call/return mode select bit
2185 0, // second memory operand
2186 0, // second literal operand
2188 PCC_REGISTER, // inCond
2189 (PCC_REGISTER | PCC_Z | PCC_N), // outCond
2193 pCodeInstruction pic16_pciRRNCFW = { // mdubuc - New
2194 {PC_OPCODE, NULL, NULL, 0, NULL,
2201 NULL, // from branch
2208 0,0, // dest, bit instruction
2209 0,0, // branch, skip
2210 0, // literal operand
2211 1, // RAM access bit
2212 0, // fast call/return mode select bit
2213 0, // second memory operand
2214 0, // second literal operand
2216 PCC_REGISTER, // inCond
2217 (PCC_W | PCC_Z | PCC_N), // outCond
2221 pCodeInstruction pic16_pciSETF = { // mdubuc - New
2222 {PC_OPCODE, NULL, NULL, 0, NULL,
2229 NULL, // from branch
2236 0,0, // dest, bit instruction
2237 0,0, // branch, skip
2238 0, // literal operand
2239 1, // RAM access bit
2240 0, // fast call/return mode select bit
2241 0, // second memory operand
2242 0, // second literal operand
2245 PCC_REGISTER , // outCond
2249 pCodeInstruction pic16_pciSUBLW = {
2250 {PC_OPCODE, NULL, NULL, 0, NULL,
2257 NULL, // from branch
2264 0,0, // dest, bit instruction
2265 0,0, // branch, skip
2266 1, // literal operand
2267 0, // RAM access bit
2268 0, // fast call/return mode select bit
2269 0, // second memory operand
2270 0, // second literal operand
2272 (PCC_W | PCC_LITERAL), // inCond
2273 (PCC_W | PCC_STATUS), // outCond
2277 pCodeInstruction pic16_pciSUBFWB = {
2278 {PC_OPCODE, NULL, NULL, 0, NULL,
2285 NULL, // from branch
2292 1,0, // dest, bit instruction
2293 0,0, // branch, skip
2294 0, // literal operand
2295 1, // RAM access bit
2296 0, // fast call/return mode select bit
2297 0, // second memory operand
2298 0, // second literal operand
2300 (PCC_W | PCC_REGISTER | PCC_C), // inCond
2301 (PCC_W | PCC_STATUS), // outCond
2305 pCodeInstruction pic16_pciSUBWF = {
2306 {PC_OPCODE, NULL, NULL, 0, NULL,
2313 NULL, // from branch
2320 1,0, // dest, bit instruction
2321 0,0, // branch, skip
2322 0, // literal operand
2323 1, // RAM access bit
2324 0, // fast call/return mode select bit
2325 0, // second memory operand
2326 0, // second literal operand
2328 (PCC_W | PCC_REGISTER), // inCond
2329 (PCC_REGISTER | PCC_STATUS), // outCond
2333 pCodeInstruction pic16_pciSUBFW = {
2334 {PC_OPCODE, NULL, NULL, 0, NULL,
2341 NULL, // from branch
2348 0,0, // dest, bit instruction
2349 0,0, // branch, skip
2350 0, // literal operand
2351 1, // RAM access bit
2352 0, // fast call/return mode select bit
2353 0, // second memory operand
2354 0, // second literal operand
2356 (PCC_W | PCC_REGISTER), // inCond
2357 (PCC_W | PCC_STATUS), // outCond
2361 pCodeInstruction pic16_pciSUBFWB_D1 = { // mdubuc - New
2362 {PC_OPCODE, NULL, NULL, 0, NULL,
2369 NULL, // from branch
2376 1,0, // dest, bit instruction
2377 0,0, // branch, skip
2378 0, // literal operand
2379 1, // RAM access bit
2380 0, // fast call/return mode select bit
2381 0, // second memory operand
2382 0, // second literal operand
2384 (PCC_W | PCC_REGISTER | PCC_C), // inCond
2385 (PCC_REGISTER | PCC_STATUS), // outCond
2389 pCodeInstruction pic16_pciSUBFWB_D0 = { // mdubuc - New
2390 {PC_OPCODE, NULL, NULL, 0, NULL,
2397 NULL, // from branch
2404 0,0, // dest, bit instruction
2405 0,0, // branch, skip
2406 0, // literal operand
2407 1, // RAM access bit
2408 0, // fast call/return mode select bit
2409 0, // second memory operand
2410 0, // second literal operand
2412 (PCC_W | PCC_REGISTER | PCC_C), // inCond
2413 (PCC_W | PCC_STATUS), // outCond
2417 pCodeInstruction pic16_pciSUBWFB_D1 = { // mdubuc - New
2418 {PC_OPCODE, NULL, NULL, 0, NULL,
2425 NULL, // from branch
2432 1,0, // dest, bit instruction
2433 0,0, // branch, skip
2434 0, // literal operand
2435 1, // RAM access bit
2436 0, // fast call/return mode select bit
2437 0, // second memory operand
2438 0, // second literal operand
2440 (PCC_W | PCC_REGISTER | PCC_C), // inCond
2441 (PCC_REGISTER | PCC_STATUS), // outCond
2445 pCodeInstruction pic16_pciSUBWFB_D0 = { // mdubuc - New
2446 {PC_OPCODE, NULL, NULL, 0, NULL,
2453 NULL, // from branch
2460 0,0, // dest, bit instruction
2461 0,0, // branch, skip
2462 0, // literal operand
2463 1, // RAM access bit
2464 0, // fast call/return mode select bit
2465 0, // second memory operand
2466 0, // second literal operand
2468 (PCC_W | PCC_REGISTER | PCC_C), // inCond
2469 (PCC_W | PCC_STATUS), // outCond
2473 pCodeInstruction pic16_pciSWAPF = {
2474 {PC_OPCODE, NULL, NULL, 0, NULL,
2481 NULL, // from branch
2488 1,0, // dest, bit instruction
2489 0,0, // branch, skip
2490 0, // literal operand
2491 1, // RAM access bit
2492 0, // fast call/return mode select bit
2493 0, // second memory operand
2494 0, // second literal operand
2496 (PCC_REGISTER), // inCond
2497 (PCC_REGISTER), // outCond
2501 pCodeInstruction pic16_pciSWAPFW = {
2502 {PC_OPCODE, NULL, NULL, 0, NULL,
2509 NULL, // from branch
2516 0,0, // dest, bit instruction
2517 0,0, // branch, skip
2518 0, // literal operand
2519 1, // RAM access bit
2520 0, // fast call/return mode select bit
2521 0, // second memory operand
2522 0, // second literal operand
2524 (PCC_REGISTER), // inCond
2529 pCodeInstruction pic16_pciTBLRD = { // patch 15
2530 {PC_OPCODE, NULL, NULL, 0, NULL,
2536 NULL, // from branch
2543 0,0, // dest, bit instruction
2544 0,0, // branch, skip
2545 0, // literal operand
2546 0, // RAM access bit
2547 0, // fast call/return mode select bit
2548 0, // second memory operand
2549 0, // second literal operand
2552 PCC_NONE , // outCond
2556 pCodeInstruction pic16_pciTBLRD_POSTINC = { // patch 15
2557 {PC_OPCODE, NULL, NULL, 0, NULL,
2563 NULL, // from branch
2570 0,0, // dest, bit instruction
2571 0,0, // branch, skip
2572 0, // literal operand
2573 0, // RAM access bit
2574 0, // fast call/return mode select bit
2575 0, // second memory operand
2576 0, // second literal operand
2579 PCC_NONE , // outCond
2583 pCodeInstruction pic16_pciTBLRD_POSTDEC = { // patch 15
2584 {PC_OPCODE, NULL, NULL, 0, NULL,
2590 NULL, // from branch
2597 0,0, // dest, bit instruction
2598 0,0, // branch, skip
2599 0, // literal operand
2600 0, // RAM access bit
2601 0, // fast call/return mode select bit
2602 0, // second memory operand
2603 0, // second literal operand
2606 PCC_NONE , // outCond
2610 pCodeInstruction pic16_pciTBLRD_PREINC = { // patch 15
2611 {PC_OPCODE, NULL, NULL, 0, NULL,
2617 NULL, // from branch
2624 0,0, // dest, bit instruction
2625 0,0, // branch, skip
2626 0, // literal operand
2627 0, // RAM access bit
2628 0, // fast call/return mode select bit
2629 0, // second memory operand
2630 0, // second literal operand
2633 PCC_NONE , // outCond
2637 pCodeInstruction pic16_pciTBLWT = { // patch 15
2638 {PC_OPCODE, NULL, NULL, 0, NULL,
2644 NULL, // from branch
2651 0,0, // dest, bit instruction
2652 0,0, // branch, skip
2653 0, // literal operand
2654 0, // RAM access bit
2655 0, // fast call/return mode select bit
2656 0, // second memory operand
2657 0, // second literal operand
2660 PCC_NONE , // outCond
2664 pCodeInstruction pic16_pciTBLWT_POSTINC = { // patch 15
2665 {PC_OPCODE, NULL, NULL, 0, NULL,
2671 NULL, // from branch
2678 0,0, // dest, bit instruction
2679 0,0, // branch, skip
2680 0, // literal operand
2681 0, // RAM access bit
2682 0, // fast call/return mode select bit
2683 0, // second memory operand
2684 0, // second literal operand
2687 PCC_NONE , // outCond
2691 pCodeInstruction pic16_pciTBLWT_POSTDEC = { // patch 15
2692 {PC_OPCODE, NULL, NULL, 0, NULL,
2698 NULL, // from branch
2705 0,0, // dest, bit instruction
2706 0,0, // branch, skip
2707 0, // literal operand
2708 0, // RAM access bit
2709 0, // fast call/return mode select bit
2710 0, // second memory operand
2711 0, // second literal operand
2714 PCC_NONE , // outCond
2718 pCodeInstruction pic16_pciTBLWT_PREINC = { // patch 15
2719 {PC_OPCODE, NULL, NULL, 0, NULL,
2725 NULL, // from branch
2732 0,0, // dest, bit instruction
2733 0,0, // branch, skip
2734 0, // literal operand
2735 0, // RAM access bit
2736 0, // fast call/return mode select bit
2737 0, // second memory operand
2738 0, // second literal operand
2741 PCC_NONE , // outCond
2745 pCodeInstruction pic16_pciTSTFSZ = { // mdubuc - New
2746 {PC_OPCODE, NULL, NULL, 0, NULL,
2753 NULL, // from branch
2760 0,0, // dest, bit instruction
2761 1,1, // branch, skip
2762 0, // literal operand
2763 1, // RAM access bit
2764 0, // fast call/return mode select bit
2765 0, // second memory operand
2766 0, // second literal operand
2768 PCC_REGISTER, // inCond
2769 PCC_NONE, // outCond
2773 pCodeInstruction pic16_pciXORWF = {
2774 {PC_OPCODE, NULL, NULL, 0, NULL,
2781 NULL, // from branch
2788 1,0, // dest, bit instruction
2789 0,0, // branch, skip
2790 0, // literal operand
2791 1, // RAM access bit
2792 0, // fast call/return mode select bit
2793 0, // second memory operand
2794 0, // second literal operand
2796 (PCC_W | PCC_REGISTER), // inCond
2797 (PCC_REGISTER | PCC_Z | PCC_N), // outCond
2801 pCodeInstruction pic16_pciXORFW = {
2802 {PC_OPCODE, NULL, NULL, 0, NULL,
2809 NULL, // from branch
2816 0,0, // dest, bit instruction
2817 0,0, // branch, skip
2818 0, // literal operand
2819 1, // RAM access bit
2820 0, // fast call/return mode select bit
2821 0, // second memory operand
2822 0, // second literal operand
2824 (PCC_W | PCC_REGISTER), // inCond
2825 (PCC_W | PCC_Z | PCC_N), // outCond
2829 pCodeInstruction pic16_pciXORLW = {
2830 {PC_OPCODE, NULL, NULL, 0, NULL,
2837 NULL, // from branch
2844 0,0, // dest, bit instruction
2845 0,0, // branch, skip
2846 1, // literal operand
2847 1, // RAM access bit
2848 0, // fast call/return mode select bit
2849 0, // second memory operand
2850 0, // second literal operand
2852 (PCC_W | PCC_LITERAL), // inCond
2853 (PCC_W | PCC_Z | PCC_N), // outCond
2858 pCodeInstruction pic16_pciBANKSEL = {
2859 {PC_OPCODE, NULL, NULL, 0, NULL,
2865 NULL, // from branch
2872 0,0, // dest, bit instruction
2873 0,0, // branch, skip
2874 0, // literal operand
2875 0, // RAM access bit
2876 0, // fast call/return mode select bit
2877 0, // second memory operand
2878 0, // second literal operand
2881 PCC_NONE, // outCond
2886 #define MAX_PIC16MNEMONICS 100
2887 pCodeInstruction *pic16Mnemonics[MAX_PIC16MNEMONICS];
2889 //#define USE_VSNPRINTF
2892 #ifdef USE_VSNPRINTF
2893 // Alas, vsnprintf is not ANSI standard, and does not exist
2894 // on Solaris (and probably other non-Gnu flavored Unixes).
2896 /*-----------------------------------------------------------------*/
2897 /* SAFE_snprintf - like snprintf except the string pointer is */
2898 /* after the string has been printed to. This is */
2899 /* useful for printing to string as though if it */
2900 /* were a stream. */
2901 /*-----------------------------------------------------------------*/
2902 void SAFE_snprintf(char **str, size_t *size, const char *format, ...)
2910 va_start(val, format);
2912 vsnprintf(*str, *size, format, val);
2918 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
2919 fprintf(stderr,"len = %d is > str size %d\n",len,*size);
2928 // This version is *not* safe, despite the name.
2930 void SAFE_snprintf(char **str, size_t *size, const char *format, ...)
2934 static char buffer[1024]; /* grossly conservative, but still not inherently safe */
2939 va_start(val, format);
2941 vsprintf(buffer, format, val);
2944 len = strlen(buffer);
2946 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
2947 fprintf(stderr,"len = %d is > str size %d\n",len, (int) *size);
2950 strcpy(*str, buffer);
2956 #endif // USE_VSNPRINTF
2959 extern set *externs;
2960 extern void pic16_initStack(int base_address, int size);
2961 extern regs *pic16_allocProcessorRegister(int rIdx, char * name, short po_type, int alias);
2962 extern regs *pic16_allocInternalRegister(int rIdx, char * name, short po_type, int alias);
2963 extern void pic16_init_pic(char *);
2965 void pic16_pCodeInitRegisters(void)
2967 static int initialized=0;
2974 // pic16_initStack(0xfff, 8);
2975 pic16_init_pic(port->processor);
2977 pic16_pc_status.r = pic16_allocProcessorRegister(IDX_STATUS,"STATUS", PO_STATUS, 0x80);
2978 pic16_pc_pcl.r = pic16_allocProcessorRegister(IDX_PCL,"PCL", PO_PCL, 0x80);
2979 pic16_pc_pclath.r = pic16_allocProcessorRegister(IDX_PCLATH,"PCLATH", PO_PCLATH, 0x80);
2980 pic16_pc_pclatu.r = pic16_allocProcessorRegister(IDX_PCLATU,"PCLATU", PO_PCLATU, 0x80);
2981 pic16_pc_intcon.r = pic16_allocProcessorRegister(IDX_INTCON,"INTCON", PO_INTCON, 0x80);
2982 pic16_pc_wreg.r = pic16_allocProcessorRegister(IDX_WREG,"WREG", PO_WREG, 0x80);
2983 pic16_pc_bsr.r = pic16_allocProcessorRegister(IDX_BSR,"BSR", PO_BSR, 0x80);
2985 pic16_pc_tosl.r = pic16_allocProcessorRegister(IDX_TOSL,"TOSL", PO_SFR_REGISTER, 0x80);
2986 pic16_pc_tosh.r = pic16_allocProcessorRegister(IDX_TOSH,"TOSH", PO_SFR_REGISTER, 0x80);
2987 pic16_pc_tosu.r = pic16_allocProcessorRegister(IDX_TOSU,"TOSU", PO_SFR_REGISTER, 0x80);
2989 pic16_pc_tblptrl.r = pic16_allocProcessorRegister(IDX_TBLPTRL,"TBLPTRL", PO_SFR_REGISTER, 0x80);
2990 pic16_pc_tblptrh.r = pic16_allocProcessorRegister(IDX_TBLPTRH,"TBLPTRH", PO_SFR_REGISTER, 0x80);
2991 pic16_pc_tblptru.r = pic16_allocProcessorRegister(IDX_TBLPTRU,"TBLPTRU", PO_SFR_REGISTER, 0x80);
2992 pic16_pc_tablat.r = pic16_allocProcessorRegister(IDX_TABLAT,"TABLAT", PO_SFR_REGISTER, 0x80);
2994 pic16_pc_fsr0l.r = pic16_allocProcessorRegister(IDX_FSR0L, "FSR0L", PO_FSR0, 0x80);
2995 pic16_pc_fsr0h.r = pic16_allocProcessorRegister(IDX_FSR0H, "FSR0H", PO_FSR0, 0x80);
2996 pic16_pc_fsr1l.r = pic16_allocProcessorRegister(IDX_FSR1L, "FSR1L", PO_FSR0, 0x80);
2997 pic16_pc_fsr1h.r = pic16_allocProcessorRegister(IDX_FSR1H, "FSR1H", PO_FSR0, 0x80);
2998 pic16_pc_fsr2l.r = pic16_allocProcessorRegister(IDX_FSR2L, "FSR2L", PO_FSR0, 0x80);
2999 pic16_pc_fsr2h.r = pic16_allocProcessorRegister(IDX_FSR2H, "FSR2H", PO_FSR0, 0x80);
3001 pic16_stackpnt_lo = &pic16_pc_fsr1l;
3002 pic16_stackpnt_hi = &pic16_pc_fsr1h;
3003 pic16_stack_postdec = &pic16_pc_postdec1;
3004 pic16_stack_postinc = &pic16_pc_postinc1;
3005 pic16_stack_preinc = &pic16_pc_preinc1;
3006 pic16_stack_plusw = &pic16_pc_plusw1;
3008 pic16_framepnt_lo = &pic16_pc_fsr2l;
3009 pic16_framepnt_hi = &pic16_pc_fsr2h;
3010 pic16_frame_postdec = &pic16_pc_postdec2;
3011 pic16_frame_postinc = &pic16_pc_postinc2;
3012 pic16_frame_preinc = &pic16_pc_preinc2;
3013 pic16_frame_plusw = &pic16_pc_plusw2;
3015 pic16_pc_indf0.r = pic16_allocProcessorRegister(IDX_INDF0,"INDF0", PO_INDF0, 0x80);
3016 pic16_pc_postinc0.r = pic16_allocProcessorRegister(IDX_POSTINC0, "POSTINC0", PO_INDF0, 0x80);
3017 pic16_pc_postdec0.r = pic16_allocProcessorRegister(IDX_POSTDEC0, "POSTDEC0", PO_INDF0, 0x80);
3018 pic16_pc_preinc0.r = pic16_allocProcessorRegister(IDX_PREINC0, "PREINC0", PO_INDF0, 0x80);
3019 pic16_pc_plusw0.r = pic16_allocProcessorRegister(IDX_PLUSW0, "PLUSW0", PO_INDF0, 0x80);
3021 pic16_pc_indf1.r = pic16_allocProcessorRegister(IDX_INDF1,"INDF1", PO_INDF0, 0x80);
3022 pic16_pc_postinc1.r = pic16_allocProcessorRegister(IDX_POSTINC1, "POSTINC1", PO_INDF0, 0x80);
3023 pic16_pc_postdec1.r = pic16_allocProcessorRegister(IDX_POSTDEC1, "POSTDEC1", PO_INDF0, 0x80);
3024 pic16_pc_preinc1.r = pic16_allocProcessorRegister(IDX_PREINC1, "PREINC1", PO_INDF0, 0x80);
3025 pic16_pc_plusw1.r = pic16_allocProcessorRegister(IDX_PLUSW1, "PLUSW1", PO_INDF0, 0x80);
3027 pic16_pc_indf2.r = pic16_allocProcessorRegister(IDX_INDF2,"INDF2", PO_INDF0, 0x80);
3028 pic16_pc_postinc2.r = pic16_allocProcessorRegister(IDX_POSTINC2, "POSTINC2", PO_INDF0, 0x80);
3029 pic16_pc_postdec2.r = pic16_allocProcessorRegister(IDX_POSTDEC2, "POSTDEC2", PO_INDF0, 0x80);
3030 pic16_pc_preinc2.r = pic16_allocProcessorRegister(IDX_PREINC2, "PREINC2", PO_INDF0, 0x80);
3031 pic16_pc_plusw2.r = pic16_allocProcessorRegister(IDX_PLUSW2, "PLUSW2", PO_INDF0, 0x80);
3033 pic16_pc_prodl.r = pic16_allocProcessorRegister(IDX_PRODL, "PRODL", PO_PRODL, 0x80);
3034 pic16_pc_prodh.r = pic16_allocProcessorRegister(IDX_PRODH, "PRODH", PO_PRODH, 0x80);
3037 pic16_pc_eecon1.r = pic16_allocProcessorRegister(IDX_EECON1, "EECON1", PO_SFR_REGISTER, 0x80);
3038 pic16_pc_eecon2.r = pic16_allocProcessorRegister(IDX_EECON2, "EECON2", PO_SFR_REGISTER, 0x80);
3039 pic16_pc_eedata.r = pic16_allocProcessorRegister(IDX_EEDATA, "EEDATA", PO_SFR_REGISTER, 0x80);
3040 pic16_pc_eeadr.r = pic16_allocProcessorRegister(IDX_EEADR, "EEADR", PO_SFR_REGISTER, 0x80);
3043 pic16_pc_status.rIdx = IDX_STATUS;
3044 pic16_pc_intcon.rIdx = IDX_INTCON;
3045 pic16_pc_pcl.rIdx = IDX_PCL;
3046 pic16_pc_pclath.rIdx = IDX_PCLATH;
3047 pic16_pc_pclatu.rIdx = IDX_PCLATU;
3048 pic16_pc_wreg.rIdx = IDX_WREG;
3049 pic16_pc_bsr.rIdx = IDX_BSR;
3051 pic16_pc_tosl.rIdx = IDX_TOSL;
3052 pic16_pc_tosh.rIdx = IDX_TOSH;
3053 pic16_pc_tosu.rIdx = IDX_TOSU;
3055 pic16_pc_tblptrl.rIdx = IDX_TBLPTRL;
3056 pic16_pc_tblptrh.rIdx = IDX_TBLPTRH;
3057 pic16_pc_tblptru.rIdx = IDX_TBLPTRU;
3058 pic16_pc_tablat.rIdx = IDX_TABLAT;
3060 pic16_pc_fsr0l.rIdx = IDX_FSR0L;
3061 pic16_pc_fsr0h.rIdx = IDX_FSR0H;
3062 pic16_pc_fsr1l.rIdx = IDX_FSR1L;
3063 pic16_pc_fsr1h.rIdx = IDX_FSR1H;
3064 pic16_pc_fsr2l.rIdx = IDX_FSR2L;
3065 pic16_pc_fsr2h.rIdx = IDX_FSR2H;
3066 pic16_pc_indf0.rIdx = IDX_INDF0;
3067 pic16_pc_postinc0.rIdx = IDX_POSTINC0;
3068 pic16_pc_postdec0.rIdx = IDX_POSTDEC0;
3069 pic16_pc_preinc0.rIdx = IDX_PREINC0;
3070 pic16_pc_plusw0.rIdx = IDX_PLUSW0;
3071 pic16_pc_indf1.rIdx = IDX_INDF1;
3072 pic16_pc_postinc1.rIdx = IDX_POSTINC1;
3073 pic16_pc_postdec1.rIdx = IDX_POSTDEC1;
3074 pic16_pc_preinc1.rIdx = IDX_PREINC1;
3075 pic16_pc_plusw1.rIdx = IDX_PLUSW1;
3076 pic16_pc_indf2.rIdx = IDX_INDF2;
3077 pic16_pc_postinc2.rIdx = IDX_POSTINC2;
3078 pic16_pc_postdec2.rIdx = IDX_POSTDEC2;
3079 pic16_pc_preinc2.rIdx = IDX_PREINC2;
3080 pic16_pc_plusw2.rIdx = IDX_PLUSW2;
3081 pic16_pc_prodl.rIdx = IDX_PRODL;
3082 pic16_pc_prodh.rIdx = IDX_PRODH;
3084 pic16_pc_kzero.r = pic16_allocInternalRegister(IDX_KZ,"KZ",PO_GPR_REGISTER,0);
3085 pic16_pc_ssave.r = pic16_allocInternalRegister(IDX_SSAVE,"SSAVE", PO_GPR_REGISTER, 0);
3086 pic16_pc_wsave.r = pic16_allocInternalRegister(IDX_WSAVE,"WSAVE", PO_GPR_REGISTER, 0);
3088 pic16_pc_kzero.rIdx = IDX_KZ;
3089 pic16_pc_wsave.rIdx = IDX_WSAVE;
3090 pic16_pc_ssave.rIdx = IDX_SSAVE;
3092 pic16_pc_eecon1.rIdx = IDX_EECON1;
3093 pic16_pc_eecon2.rIdx = IDX_EECON2;
3094 pic16_pc_eedata.rIdx = IDX_EEDATA;
3095 pic16_pc_eeadr.rIdx = IDX_EEADR;
3098 pic16_pc_gpsimio.r = pic16_allocProcessorRegister(IDX_GPSIMIO, "GPSIMIO", PO_GPR_REGISTER, 0x80);
3099 pic16_pc_gpsimio2.r = pic16_allocProcessorRegister(IDX_GPSIMIO2, "GPSIMIO2", PO_GPR_REGISTER, 0x80);
3101 pic16_pc_gpsimio.rIdx = IDX_GPSIMIO;
3102 pic16_pc_gpsimio2.rIdx = IDX_GPSIMIO2;
3104 /* probably should put this in a separate initialization routine */
3105 pb_dead_pcodes = newpBlock();
3110 /*-----------------------------------------------------------------*/
3111 /* mnem2key - convert a pic mnemonic into a hash key */
3112 /* (BTW - this spreads the mnemonics quite well) */
3114 /*-----------------------------------------------------------------*/
3116 int mnem2key(unsigned char const *mnem)
3125 key += toupper(*mnem++) +1;
3129 return (key & 0x1f);
3134 void pic16initMnemonics(void)
3139 pCodeInstruction *pci;
3141 if(mnemonics_initialized)
3144 // NULL out the array before making the assignments
3145 // since we check the array contents below this initialization.
3147 for (i = 0; i < MAX_PIC16MNEMONICS; i++) {
3148 pic16Mnemonics[i] = NULL;
3151 pic16Mnemonics[POC_ADDLW] = &pic16_pciADDLW;
3152 pic16Mnemonics[POC_ADDWF] = &pic16_pciADDWF;
3153 pic16Mnemonics[POC_ADDFW] = &pic16_pciADDFW;
3154 pic16Mnemonics[POC_ADDWFC] = &pic16_pciADDWFC;
3155 pic16Mnemonics[POC_ADDFWC] = &pic16_pciADDFWC;
3156 pic16Mnemonics[POC_ANDLW] = &pic16_pciANDLW;
3157 pic16Mnemonics[POC_ANDWF] = &pic16_pciANDWF;
3158 pic16Mnemonics[POC_ANDFW] = &pic16_pciANDFW;
3159 pic16Mnemonics[POC_BC] = &pic16_pciBC;
3160 pic16Mnemonics[POC_BCF] = &pic16_pciBCF;
3161 pic16Mnemonics[POC_BN] = &pic16_pciBN;
3162 pic16Mnemonics[POC_BNC] = &pic16_pciBNC;
3163 pic16Mnemonics[POC_BNN] = &pic16_pciBNN;
3164 pic16Mnemonics[POC_BNOV] = &pic16_pciBNOV;
3165 pic16Mnemonics[POC_BNZ] = &pic16_pciBNZ;
3166 pic16Mnemonics[POC_BOV] = &pic16_pciBOV;
3167 pic16Mnemonics[POC_BRA] = &pic16_pciBRA;
3168 pic16Mnemonics[POC_BSF] = &pic16_pciBSF;
3169 pic16Mnemonics[POC_BTFSC] = &pic16_pciBTFSC;
3170 pic16Mnemonics[POC_BTFSS] = &pic16_pciBTFSS;
3171 pic16Mnemonics[POC_BTG] = &pic16_pciBTG;
3172 pic16Mnemonics[POC_BZ] = &pic16_pciBZ;
3173 pic16Mnemonics[POC_CALL] = &pic16_pciCALL;
3174 pic16Mnemonics[POC_CLRF] = &pic16_pciCLRF;
3175 pic16Mnemonics[POC_CLRWDT] = &pic16_pciCLRWDT;
3176 pic16Mnemonics[POC_COMF] = &pic16_pciCOMF;
3177 pic16Mnemonics[POC_COMFW] = &pic16_pciCOMFW;
3178 pic16Mnemonics[POC_CPFSEQ] = &pic16_pciCPFSEQ;
3179 pic16Mnemonics[POC_CPFSGT] = &pic16_pciCPFSGT;
3180 pic16Mnemonics[POC_CPFSLT] = &pic16_pciCPFSLT;
3181 pic16Mnemonics[POC_DAW] = &pic16_pciDAW;
3182 pic16Mnemonics[POC_DCFSNZ] = &pic16_pciDCFSNZ;
3183 pic16Mnemonics[POC_DECF] = &pic16_pciDECF;
3184 pic16Mnemonics[POC_DECFW] = &pic16_pciDECFW;
3185 pic16Mnemonics[POC_DECFSZ] = &pic16_pciDECFSZ;
3186 pic16Mnemonics[POC_DECFSZW] = &pic16_pciDECFSZW;
3187 pic16Mnemonics[POC_GOTO] = &pic16_pciGOTO;
3188 pic16Mnemonics[POC_INCF] = &pic16_pciINCF;
3189 pic16Mnemonics[POC_INCFW] = &pic16_pciINCFW;
3190 pic16Mnemonics[POC_INCFSZ] = &pic16_pciINCFSZ;
3191 pic16Mnemonics[POC_INCFSZW] = &pic16_pciINCFSZW;
3192 pic16Mnemonics[POC_INFSNZ] = &pic16_pciINFSNZ;
3193 pic16Mnemonics[POC_INFSNZW] = &pic16_pciINFSNZW;
3194 pic16Mnemonics[POC_IORWF] = &pic16_pciIORWF;
3195 pic16Mnemonics[POC_IORFW] = &pic16_pciIORFW;
3196 pic16Mnemonics[POC_IORLW] = &pic16_pciIORLW;
3197 pic16Mnemonics[POC_LFSR] = &pic16_pciLFSR;
3198 pic16Mnemonics[POC_MOVF] = &pic16_pciMOVF;
3199 pic16Mnemonics[POC_MOVFW] = &pic16_pciMOVFW;
3200 pic16Mnemonics[POC_MOVFF] = &pic16_pciMOVFF;
3201 pic16Mnemonics[POC_MOVLB] = &pic16_pciMOVLB;
3202 pic16Mnemonics[POC_MOVLW] = &pic16_pciMOVLW;
3203 pic16Mnemonics[POC_MOVWF] = &pic16_pciMOVWF;
3204 pic16Mnemonics[POC_MULLW] = &pic16_pciMULLW;
3205 pic16Mnemonics[POC_MULWF] = &pic16_pciMULWF;
3206 pic16Mnemonics[POC_NEGF] = &pic16_pciNEGF;
3207 pic16Mnemonics[POC_NOP] = &pic16_pciNOP;
3208 pic16Mnemonics[POC_POP] = &pic16_pciPOP;
3209 pic16Mnemonics[POC_PUSH] = &pic16_pciPUSH;
3210 pic16Mnemonics[POC_RCALL] = &pic16_pciRCALL;
3211 pic16Mnemonics[POC_RETFIE] = &pic16_pciRETFIE;
3212 pic16Mnemonics[POC_RETLW] = &pic16_pciRETLW;
3213 pic16Mnemonics[POC_RETURN] = &pic16_pciRETURN;
3214 pic16Mnemonics[POC_RLCF] = &pic16_pciRLCF;
3215 pic16Mnemonics[POC_RLCFW] = &pic16_pciRLCFW;
3216 pic16Mnemonics[POC_RLNCF] = &pic16_pciRLNCF;
3217 pic16Mnemonics[POC_RLNCFW] = &pic16_pciRLNCFW;
3218 pic16Mnemonics[POC_RRCF] = &pic16_pciRRCF;
3219 pic16Mnemonics[POC_RRCFW] = &pic16_pciRRCFW;
3220 pic16Mnemonics[POC_RRNCF] = &pic16_pciRRNCF;
3221 pic16Mnemonics[POC_RRNCFW] = &pic16_pciRRNCFW;
3222 pic16Mnemonics[POC_SETF] = &pic16_pciSETF;
3223 pic16Mnemonics[POC_SUBLW] = &pic16_pciSUBLW;
3224 pic16Mnemonics[POC_SUBWF] = &pic16_pciSUBWF;
3225 pic16Mnemonics[POC_SUBFW] = &pic16_pciSUBFW;
3226 pic16Mnemonics[POC_SUBWFB_D0] = &pic16_pciSUBWFB_D0;
3227 pic16Mnemonics[POC_SUBWFB_D1] = &pic16_pciSUBWFB_D1;
3228 pic16Mnemonics[POC_SUBFWB_D0] = &pic16_pciSUBFWB_D0;
3229 pic16Mnemonics[POC_SUBFWB_D1] = &pic16_pciSUBFWB_D1;
3230 pic16Mnemonics[POC_SWAPF] = &pic16_pciSWAPF;
3231 pic16Mnemonics[POC_SWAPFW] = &pic16_pciSWAPFW;
3232 pic16Mnemonics[POC_TBLRD] = &pic16_pciTBLRD;
3233 pic16Mnemonics[POC_TBLRD_POSTINC] = &pic16_pciTBLRD_POSTINC;
3234 pic16Mnemonics[POC_TBLRD_POSTDEC] = &pic16_pciTBLRD_POSTDEC;
3235 pic16Mnemonics[POC_TBLRD_PREINC] = &pic16_pciTBLRD_PREINC;
3236 pic16Mnemonics[POC_TBLWT] = &pic16_pciTBLWT;
3237 pic16Mnemonics[POC_TBLWT_POSTINC] = &pic16_pciTBLWT_POSTINC;
3238 pic16Mnemonics[POC_TBLWT_POSTDEC] = &pic16_pciTBLWT_POSTDEC;
3239 pic16Mnemonics[POC_TBLWT_PREINC] = &pic16_pciTBLWT_PREINC;
3240 pic16Mnemonics[POC_TSTFSZ] = &pic16_pciTSTFSZ;
3241 pic16Mnemonics[POC_XORLW] = &pic16_pciXORLW;
3242 pic16Mnemonics[POC_XORWF] = &pic16_pciXORWF;
3243 pic16Mnemonics[POC_XORFW] = &pic16_pciXORFW;
3244 pic16Mnemonics[POC_BANKSEL] = &pic16_pciBANKSEL;
3246 for(i=0; i<MAX_PIC16MNEMONICS; i++)
3247 if(pic16Mnemonics[i])
3248 hTabAddItem(&pic16MnemonicsHash, mnem2key((const unsigned char *)pic16Mnemonics[i]->mnemonic), pic16Mnemonics[i]);
3249 pci = hTabFirstItem(pic16MnemonicsHash, &key);
3252 DFPRINTF((stderr, "element %d key %d, mnem %s\n",i++,key,pci->mnemonic));
3253 pci = hTabNextItem(pic16MnemonicsHash, &key);
3256 mnemonics_initialized = 1;
3259 int pic16_getpCodePeepCommand(char *cmd);
3261 int pic16_getpCode(char *mnem,unsigned dest)
3264 pCodeInstruction *pci;
3265 int key = mnem2key((unsigned char *)mnem);
3267 if(!mnemonics_initialized)
3268 pic16initMnemonics();
3270 pci = hTabFirstItemWK(pic16MnemonicsHash, key);
3274 if(STRCASECMP(pci->mnemonic, mnem) == 0) {
3275 if((pci->num_ops <= 1)
3276 || (pci->isModReg == dest)
3278 || (pci->num_ops <= 2 && pci->isAccess)
3279 || (pci->num_ops <= 2 && pci->isFastCall)
3280 || (pci->num_ops <= 2 && pci->is2MemOp)
3281 || (pci->num_ops <= 2 && pci->is2LitOp) )
3285 pci = hTabNextItemWK (pic16MnemonicsHash);
3292 /*-----------------------------------------------------------------*
3293 * pic16initpCodePeepCommands
3295 *-----------------------------------------------------------------*/
3296 void pic16initpCodePeepCommands(void)
3304 hTabAddItem(&pic16pCodePeepCommandsHash,
3305 mnem2key((const unsigned char *)peepCommands[i].cmd), &peepCommands[i]);
3307 } while (peepCommands[i].cmd);
3309 pcmd = hTabFirstItem(pic16pCodePeepCommandsHash, &key);
3312 //fprintf(stderr, "peep command %s key %d\n",pcmd->cmd,pcmd->id);
3313 pcmd = hTabNextItem(pic16pCodePeepCommandsHash, &key);
3318 /*-----------------------------------------------------------------
3321 *-----------------------------------------------------------------*/
3323 int pic16_getpCodePeepCommand(char *cmd)
3327 int key = mnem2key((unsigned char *)cmd);
3330 pcmd = hTabFirstItemWK(pic16pCodePeepCommandsHash, key);
3333 // fprintf(stderr," comparing %s to %s\n",pcmd->cmd,cmd);
3334 if(STRCASECMP(pcmd->cmd, cmd) == 0) {
3338 pcmd = hTabNextItemWK (pic16pCodePeepCommandsHash);
3345 static char getpBlock_dbName(pBlock *pb)
3351 return pb->cmemmap->dbName;
3355 void pic16_pBlockConvert2ISR(pBlock *pb)
3359 if(pb->cmemmap)pb->cmemmap = NULL;
3363 if(pic16_pcode_verbose)
3364 fprintf(stderr, "%s:%d converting to 'I'interrupt pBlock\n", __FILE__, __LINE__);
3367 void pic16_pBlockConvert2Absolute(pBlock *pb)
3370 if(pb->cmemmap)pb->cmemmap = NULL;
3374 if(pic16_pcode_verbose)
3375 fprintf(stderr, "%s:%d converting to 'A'bsolute pBlock\n", __FILE__, __LINE__);
3378 /*-----------------------------------------------------------------*/
3379 /* pic16_movepBlock2Head - given the dbname of a pBlock, move all */
3380 /* instances to the front of the doubly linked */
3381 /* list of pBlocks */
3382 /*-----------------------------------------------------------------*/
3384 void pic16_movepBlock2Head(char dbName)
3389 /* this can happen in sources without code,
3390 * only variable definitions */
3391 if(!the_pFile)return;
3393 pb = the_pFile->pbHead;
3397 if(getpBlock_dbName(pb) == dbName) {
3398 pBlock *pbn = pb->next;
3399 pb->next = the_pFile->pbHead;
3400 the_pFile->pbHead->prev = pb;
3401 the_pFile->pbHead = pb;
3404 pb->prev->next = pbn;
3406 // If the pBlock that we just moved was the last
3407 // one in the link of all of the pBlocks, then we
3408 // need to point the tail to the block just before
3409 // the one we moved.
3410 // Note: if pb->next is NULL, then pb must have
3411 // been the last pBlock in the chain.
3414 pbn->prev = pb->prev;
3416 the_pFile->pbTail = pb->prev;
3427 void pic16_copypCode(FILE *of, char dbName)
3431 if(!of || !the_pFile)
3434 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
3435 if(getpBlock_dbName(pb) == dbName) {
3436 // fprintf(stderr, "%s:%d: output of pb= 0x%p\n", __FILE__, __LINE__, pb);
3438 pic16_printpBlock(of,pb);
3443 void pic16_pcode_test(void)
3446 DFPRINTF((stderr,"pcode is alive!\n"));
3456 /* create the file name */
3457 strcpy(buffer,dstFileName);
3458 strcat(buffer,".p");
3460 if( !(pFile = fopen(buffer, "w" ))) {
3461 werror(E_FILE_OPEN_ERR,buffer);
3465 fprintf(pFile,"pcode dump\n\n");
3467 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
3468 fprintf(pFile,"\n\tNew pBlock\n\n");
3470 fprintf(pFile,"%s",pb->cmemmap->sname);
3472 fprintf(pFile,"internal pblock");
3474 fprintf(pFile,", dbName =%c\n",getpBlock_dbName(pb));
3475 pic16_printpBlock(pFile,pb);
3481 unsigned long pic16_countInstructions(void)
3485 unsigned long isize=0;
3487 if(!the_pFile)return -1;
3489 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
3490 for(pc = pb->pcHead; pc; pc = pc->next) {
3491 if(isPCI(pc) || isPCAD(pc))isize += PCI(pc)->isize;
3498 /*-----------------------------------------------------------------*/
3499 /* int RegCond(pCodeOp *pcop) - if pcop points to the STATUS reg- */
3500 /* ister, RegCond will return the bit being referenced. */
3502 /* fixme - why not just OR in the pcop bit field */
3503 /*-----------------------------------------------------------------*/
3505 static int RegCond(pCodeOp *pcop)
3511 if(!pcop->name)return 0;
3513 if(pcop->type == PO_GPR_BIT && !strcmp(pcop->name, pic16_pc_status.pcop.name)) {
3514 switch(PCORB(pcop)->bit) {
3528 /*-----------------------------------------------------------------*/
3529 /* pic16_newpCode - create and return a newly initialized pCode */
3531 /* fixme - rename this */
3533 /* The purpose of this routine is to create a new Instruction */
3534 /* pCode. This is called by gen.c while the assembly code is being */
3538 /* PIC_OPCODE op - the assembly instruction we wish to create. */
3539 /* (note that the op is analogous to but not the */
3540 /* same thing as the opcode of the instruction.) */
3541 /* pCdoeOp *pcop - pointer to the operand of the instruction. */
3544 /* a pointer to the new malloc'd pCode is returned. */
3548 /*-----------------------------------------------------------------*/
3549 pCode *pic16_newpCode (PIC_OPCODE op, pCodeOp *pcop)
3551 pCodeInstruction *pci ;
3553 if(!mnemonics_initialized)
3554 pic16initMnemonics();
3556 pci = Safe_calloc(1, sizeof(pCodeInstruction));
3558 if((op>=0) && (op < MAX_PIC16MNEMONICS) && pic16Mnemonics[op]) {
3559 memcpy(pci, pic16Mnemonics[op], sizeof(pCodeInstruction));
3562 if(pci->inCond & PCC_EXAMINE_PCOP)
3563 pci->inCond |= RegCond(pcop);
3565 if(pci->outCond & PCC_EXAMINE_PCOP)
3566 pci->outCond |= RegCond(pcop);
3568 pci->pc.prev = pci->pc.next = NULL;
3569 return (pCode *)pci;
3572 fprintf(stderr, "pCode mnemonic error %s,%d\n",__FUNCTION__,__LINE__);
3578 /*-----------------------------------------------------------------*/
3579 /* pic16_newpCodeWild - create a "wild" as in wild card pCode */
3581 /* Wild pcodes are used during the peep hole optimizer to serve */
3582 /* as place holders for any instruction. When a snippet of code is */
3583 /* compared to a peep hole rule, the wild card opcode will match */
3584 /* any instruction. However, the optional operand and label are */
3585 /* additional qualifiers that must also be matched before the */
3586 /* line (of assembly code) is declared matched. Note that the */
3587 /* operand may be wild too. */
3589 /* Note, a wild instruction is specified just like a wild var: */
3590 /* %4 ; A wild instruction, */
3591 /* See the peeph.def file for additional examples */
3593 /*-----------------------------------------------------------------*/
3595 pCode *pic16_newpCodeWild(int pCodeID, pCodeOp *optional_operand, pCodeOp *optional_label)
3600 pcw = Safe_calloc(1,sizeof(pCodeWild));
3602 pcw->pci.pc.type = PC_WILD;
3603 pcw->pci.pc.prev = pcw->pci.pc.next = NULL;
3604 pcw->pci.from = pcw->pci.to = pcw->pci.label = NULL;
3605 pcw->pci.pc.pb = NULL;
3607 // pcw->pci.pc.analyze = genericAnalyze;
3608 pcw->pci.pc.destruct = genericDestruct;
3609 pcw->pci.pc.print = genericPrint;
3611 pcw->id = pCodeID; // this is the 'n' in %n
3612 pcw->operand = optional_operand;
3613 pcw->label = optional_label;
3615 pcw->mustBeBitSkipInst = 0;
3616 pcw->mustNotBeBitSkipInst = 0;
3617 pcw->invertBitSkipInst = 0;
3619 return ( (pCode *)pcw);
3623 /*-----------------------------------------------------------------*/
3624 /* newPcodeInlineP - create a new pCode from a char string */
3625 /*-----------------------------------------------------------------*/
3628 pCode *pic16_newpCodeInlineP(char *cP)
3633 pcc = Safe_calloc(1,sizeof(pCodeComment));
3635 pcc->pc.type = PC_INLINE;
3636 pcc->pc.prev = pcc->pc.next = NULL;
3637 //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
3640 // pcc->pc.analyze = genericAnalyze;
3641 pcc->pc.destruct = genericDestruct;
3642 pcc->pc.print = genericPrint;
3645 pcc->comment = Safe_strdup(cP);
3647 pcc->comment = NULL;
3649 return ( (pCode *)pcc);
3653 /*-----------------------------------------------------------------*/
3654 /* newPcodeCharP - create a new pCode from a char string */
3655 /*-----------------------------------------------------------------*/
3657 pCode *pic16_newpCodeCharP(char *cP)
3662 pcc = Safe_calloc(1,sizeof(pCodeComment));
3664 pcc->pc.type = PC_COMMENT;
3665 pcc->pc.prev = pcc->pc.next = NULL;
3666 //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
3669 // pcc->pc.analyze = genericAnalyze;
3670 pcc->pc.destruct = genericDestruct;
3671 pcc->pc.print = genericPrint;
3674 pcc->comment = Safe_strdup(cP);
3676 pcc->comment = NULL;
3678 return ( (pCode *)pcc);
3682 /*-----------------------------------------------------------------*/
3683 /* pic16_newpCodeFunction - */
3684 /*-----------------------------------------------------------------*/
3687 pCode *pic16_newpCodeFunction(char *mod,char *f)
3691 pcf = Safe_calloc(1,sizeof(pCodeFunction));
3693 pcf->pc.type = PC_FUNCTION;
3694 pcf->pc.prev = pcf->pc.next = NULL;
3695 //pcf->pc.from = pcf->pc.to = pcf->pc.label = NULL;
3698 // pcf->pc.analyze = genericAnalyze;
3699 pcf->pc.destruct = genericDestruct;
3700 pcf->pc.print = pCodePrintFunction;
3706 pcf->modname = Safe_calloc(1,strlen(mod)+1);
3707 strcpy(pcf->modname,mod);
3709 pcf->modname = NULL;
3712 pcf->fname = Safe_calloc(1,strlen(f)+1);
3713 strcpy(pcf->fname,f);
3717 pcf->stackusage = 0;
3719 return ( (pCode *)pcf);
3722 /*-----------------------------------------------------------------*/
3723 /* pic16_newpCodeFlow */
3724 /*-----------------------------------------------------------------*/
3725 static void destructpCodeFlow(pCode *pc)
3727 if(!pc || !isPCFL(pc))
3734 pic16_unlinkpCode(pc);
3736 deleteSet(&PCFL(pc)->registers);
3737 deleteSet(&PCFL(pc)->from);
3738 deleteSet(&PCFL(pc)->to);
3740 /* Instead of deleting the memory used by this pCode, mark
3741 * the object as bad so that if there's a pointer to this pCode
3742 * dangling around somewhere then (hopefully) when the type is
3743 * checked we'll catch it.
3747 pic16_addpCode2pBlock(pb_dead_pcodes, pc);
3753 pCode *pic16_newpCodeFlow(void )
3757 //_ALLOC(pcflow,sizeof(pCodeFlow));
3758 pcflow = Safe_calloc(1,sizeof(pCodeFlow));
3760 pcflow->pc.type = PC_FLOW;
3761 pcflow->pc.prev = pcflow->pc.next = NULL;
3762 pcflow->pc.pb = NULL;
3764 // pcflow->pc.analyze = genericAnalyze;
3765 pcflow->pc.destruct = destructpCodeFlow;
3766 pcflow->pc.print = genericPrint;
3768 pcflow->pc.seq = GpcFlowSeq++;
3770 pcflow->from = pcflow->to = NULL;
3772 pcflow->inCond = PCC_NONE;
3773 pcflow->outCond = PCC_NONE;
3775 pcflow->firstBank = -1;
3776 pcflow->lastBank = -1;
3778 pcflow->FromConflicts = 0;
3779 pcflow->ToConflicts = 0;
3783 pcflow->registers = newSet();
3785 return ( (pCode *)pcflow);
3789 /*-----------------------------------------------------------------*/
3790 /*-----------------------------------------------------------------*/
3791 pCodeFlowLink *pic16_newpCodeFlowLink(pCodeFlow *pcflow)
3793 pCodeFlowLink *pcflowLink;
3795 pcflowLink = Safe_calloc(1,sizeof(pCodeFlowLink));
3797 pcflowLink->pcflow = pcflow;
3798 pcflowLink->bank_conflict = 0;
3803 /*-----------------------------------------------------------------*/
3804 /* pic16_newpCodeCSource - create a new pCode Source Symbol */
3805 /*-----------------------------------------------------------------*/
3807 pCode *pic16_newpCodeCSource(int ln, char *f, char *l)
3812 pccs = Safe_calloc(1,sizeof(pCodeCSource));
3814 pccs->pc.type = PC_CSOURCE;
3815 pccs->pc.prev = pccs->pc.next = NULL;
3818 pccs->pc.destruct = genericDestruct;
3819 pccs->pc.print = genericPrint;
3821 pccs->line_number = ln;
3823 pccs->line = Safe_strdup(l);
3828 pccs->file_name = Safe_strdup(f);
3830 pccs->file_name = NULL;
3832 return ( (pCode *)pccs);
3837 /*******************************************************************/
3838 /* pic16_newpCodeAsmDir - create a new pCode Assembler Directive */
3839 /* added by VR 6-Jun-2003 */
3840 /*******************************************************************/
3842 pCode *pic16_newpCodeAsmDir(char *asdir, char *argfmt, ...)
3849 pcad = Safe_calloc(1, sizeof(pCodeAsmDir));
3850 pcad->pci.pc.type = PC_ASMDIR;
3851 pcad->pci.pc.prev = pcad->pci.pc.next = NULL;
3852 pcad->pci.pc.pb = NULL;
3853 pcad->pci.isize = 2;
3854 pcad->pci.pc.destruct = genericDestruct;
3855 pcad->pci.pc.print = genericPrint;
3857 if(asdir && *asdir) {
3859 while(isspace((unsigned char)*asdir))asdir++; // strip any white space from the beginning
3861 pcad->directive = Safe_strdup( asdir );
3864 va_start(ap, argfmt);
3866 memset(buffer, 0, sizeof(buffer));
3867 if(argfmt && *argfmt)
3868 vsprintf(buffer, argfmt, ap);
3872 while(isspace((unsigned char)*lbp))lbp++;
3875 pcad->arg = Safe_strdup( lbp );
3877 return ((pCode *)pcad);
3880 /*-----------------------------------------------------------------*/
3881 /* pCodeLabelDestruct - free memory used by a label. */
3882 /*-----------------------------------------------------------------*/
3883 static void pCodeLabelDestruct(pCode *pc)
3889 // if((pc->type == PC_LABEL) && PCL(pc)->label)
3890 // Safe_free(PCL(pc)->label);
3892 /* Instead of deleting the memory used by this pCode, mark
3893 * the object as bad so that if there's a pointer to this pCode
3894 * dangling around somewhere then (hopefully) when the type is
3895 * checked we'll catch it.
3899 pic16_addpCode2pBlock(pb_dead_pcodes, pc);
3905 pCode *pic16_newpCodeLabel(char *name, int key)
3911 pcl = Safe_calloc(1,sizeof(pCodeLabel) );
3913 pcl->pc.type = PC_LABEL;
3914 pcl->pc.prev = pcl->pc.next = NULL;
3915 //pcl->pc.from = pcl->pc.to = pcl->pc.label = NULL;
3918 // pcl->pc.analyze = genericAnalyze;
3919 pcl->pc.destruct = pCodeLabelDestruct;
3920 pcl->pc.print = pCodePrintLabel;
3927 sprintf(s,"_%05d_DS_",key);
3932 pcl->label = Safe_strdup(s);
3934 // if(pic16_pcode_verbose)
3935 // fprintf(stderr, "%s:%d label name: %s\n", __FILE__, __LINE__, pcl->label);
3938 return ( (pCode *)pcl);
3942 pCode *pic16_newpCodeLabelFORCE(char *name, int key)
3944 pCodeLabel *pcl = (pCodeLabel *)pic16_newpCodeLabel(name, key);
3948 return ( (pCode *)pcl );
3951 pCode *pic16_newpCodeInfo(INFO_TYPE type, pCodeOp *pcop)
3955 pci = Safe_calloc(1, sizeof(pCodeInfo));
3956 pci->pci.pc.type = PC_INFO;
3957 pci->pci.pc.prev = pci->pci.pc.next = NULL;
3958 pci->pci.pc.pb = NULL;
3959 pci->pci.label = NULL;
3961 pci->pci.pc.destruct = genericDestruct;
3962 pci->pci.pc.print = genericPrint;
3967 return ((pCode *)pci);
3971 /*-----------------------------------------------------------------*/
3972 /* newpBlock - create and return a pointer to a new pBlock */
3973 /*-----------------------------------------------------------------*/
3974 static pBlock *newpBlock(void)
3979 PpB = Safe_calloc(1,sizeof(pBlock) );
3980 PpB->next = PpB->prev = NULL;
3982 PpB->function_entries = PpB->function_exits = PpB->function_calls = NULL;
3983 PpB->tregisters = NULL;
3985 PpB->FlowTree = NULL;
3991 /*-----------------------------------------------------------------*/
3992 /* pic16_newpCodeChain - create a new chain of pCodes */
3993 /*-----------------------------------------------------------------*
3995 * This function will create a new pBlock and the pointer to the
3996 * pCode that is passed in will be the first pCode in the block.
3997 *-----------------------------------------------------------------*/
4000 pBlock *pic16_newpCodeChain(memmap *cm,char c, pCode *pc)
4003 pBlock *pB = newpBlock();
4005 pB->pcHead = pB->pcTail = pc;
4014 /*-----------------------------------------------------------------*/
4015 /* pic16_newpCodeOpLabel - Create a new label given the key */
4016 /* Note, a negative key means that the label is part of wild card */
4017 /* (and hence a wild card label) used in the pCodePeep */
4018 /* optimizations). */
4019 /*-----------------------------------------------------------------*/
4021 pCodeOp *pic16_newpCodeOpLabel(char *name, int key)
4024 static int label_key=-1;
4028 pcop = Safe_calloc(1,sizeof(pCodeOpLabel) );
4029 pcop->type = PO_LABEL;
4034 sprintf(s=buffer,"_%05d_DS_",key);
4036 s = name, key = label_key--;
4039 pcop->name = Safe_strdup(s);
4041 ((pCodeOpLabel *)pcop)->key = key;
4043 //fprintf(stderr,"pic16_newpCodeOpLabel: key=%d, name=%s\n",key,((s)?s:""));
4047 /*-----------------------------------------------------------------*/
4048 /*-----------------------------------------------------------------*/
4049 pCodeOp *pic16_newpCodeOpLit(int lit)
4055 pcop = Safe_calloc(1,sizeof(pCodeOpLit) );
4056 pcop->type = PO_LITERAL;
4060 sprintf(s,"0x%02hhx", (unsigned char)lit);
4062 // sprintf(s, "%i", lit);
4065 pcop->name = Safe_strdup(s);
4067 ((pCodeOpLit *)pcop)->lit = lit;
4072 /* Allow for 12 bit literals, required for LFSR */
4073 pCodeOp *pic16_newpCodeOpLit12(int lit)
4079 pcop = Safe_calloc(1,sizeof(pCodeOpLit) );
4080 pcop->type = PO_LITERAL;
4084 sprintf(s,"0x%03x", ((unsigned int)lit) & 0x0fff);
4086 // sprintf(s, "%i", lit);
4089 pcop->name = Safe_strdup(s);
4091 ((pCodeOpLit *)pcop)->lit = lit;
4096 /*-----------------------------------------------------------------*/
4097 /*-----------------------------------------------------------------*/
4098 pCodeOp *pic16_newpCodeOpLit2(int lit, pCodeOp *arg2)
4100 char *s = buffer, tbuf[256], *tb=tbuf;
4104 tb = pic16_get_op(arg2, NULL, 0);
4105 pcop = Safe_calloc(1,sizeof(pCodeOpLit2) );
4106 pcop->type = PO_LITERAL;
4110 sprintf(s,"0x%02x, %s", (unsigned char)lit, tb);
4112 pcop->name = Safe_strdup(s);
4115 ((pCodeOpLit2 *)pcop)->lit = lit;
4116 ((pCodeOpLit2 *)pcop)->arg2 = arg2;
4121 /*-----------------------------------------------------------------*/
4122 /*-----------------------------------------------------------------*/
4123 pCodeOp *pic16_newpCodeOpImmd(char *name, int offset, int index, int code_space)
4127 pcop = Safe_calloc(1,sizeof(pCodeOpImmd) );
4128 pcop->type = PO_IMMEDIATE;
4130 regs *r = pic16_dirregWithName(name);
4131 pcop->name = Safe_strdup(name);
4135 // fprintf(stderr, "%s:%d %s reg %s exists (r: %p)\n",__FILE__, __LINE__, __FUNCTION__, name, r);
4136 PCOI(pcop)->rIdx = r->rIdx;
4138 // fprintf(stderr, "%s:%d %s reg %s doesn't exist\n", __FILE__, __LINE__, __FUNCTION__, name);
4139 PCOI(pcop)->rIdx = -1;
4141 // fprintf(stderr,"%s %s %d\n",__FUNCTION__,name,offset);
4146 PCOI(pcop)->index = index;
4147 PCOI(pcop)->offset = offset;
4148 PCOI(pcop)->_const = code_space;
4153 /*-----------------------------------------------------------------*/
4154 /*-----------------------------------------------------------------*/
4155 pCodeOp *pic16_newpCodeOpWild(int id, pCodeWildBlock *pcwb, pCodeOp *subtype)
4161 if(!pcwb || !subtype) {
4162 fprintf(stderr, "Wild opcode declaration error: %s-%d\n",__FILE__,__LINE__);
4166 pcop = Safe_calloc(1,sizeof(pCodeOpWild));
4167 pcop->type = PO_WILD;
4168 sprintf(s,"%%%d",id);
4169 pcop->name = Safe_strdup(s);
4171 PCOW(pcop)->id = id;
4172 PCOW(pcop)->pcwb = pcwb;
4173 PCOW(pcop)->subtype = subtype;
4174 PCOW(pcop)->matched = NULL;
4176 PCOW(pcop)->pcop2 = NULL;
4181 /*-----------------------------------------------------------------*/
4182 /*-----------------------------------------------------------------*/
4183 pCodeOp *pic16_newpCodeOpWild2(int id, int id2, pCodeWildBlock *pcwb, pCodeOp *subtype, pCodeOp *subtype2)
4189 if(!pcwb || !subtype || !subtype2) {
4190 fprintf(stderr, "Wild opcode declaration error: %s-%d\n",__FILE__,__LINE__);
4194 pcop = Safe_calloc(1,sizeof(pCodeOpWild));
4195 pcop->type = PO_WILD;
4196 sprintf(s,"%%%d",id);
4197 pcop->name = Safe_strdup(s);
4199 PCOW(pcop)->id = id;
4200 PCOW(pcop)->pcwb = pcwb;
4201 PCOW(pcop)->subtype = subtype;
4202 PCOW(pcop)->matched = NULL;
4204 PCOW(pcop)->pcop2 = Safe_calloc(1, sizeof(pCodeOpWild));
4206 if(!subtype2->name) {
4207 PCOW(pcop)->pcop2 = Safe_calloc(1, sizeof(pCodeOpWild));
4208 PCOW2(pcop)->pcop.type = PO_WILD;
4209 sprintf(s, "%%%d", id2);
4210 PCOW2(pcop)->pcop.name = Safe_strdup(s);
4211 PCOW2(pcop)->id = id2;
4212 PCOW2(pcop)->subtype = subtype2;
4214 // fprintf(stderr, "%s:%d %s [wild,wild] for name: %s (%d)\tname2: %s (%d)\n", __FILE__, __LINE__, __FUNCTION__,
4215 // pcop->name, id, PCOW2(pcop)->pcop.name, id2);
4217 PCOW2(pcop)->pcop2 = pic16_pCodeOpCopy( subtype2 );
4219 // fprintf(stderr, "%s:%d %s [wild,str] for name: %s (%d)\tname2: %s (%d)\n", __FILE__, __LINE__, __FUNCTION__,
4220 // pcop->name, id, PCOW2(pcop)->pcop.name, id2);
4229 /*-----------------------------------------------------------------*/
4230 /*-----------------------------------------------------------------*/
4231 pCodeOp *pic16_newpCodeOpBit(char *s, int bit, int inBitSpace, PIC_OPTYPE subt)
4235 pcop = Safe_calloc(1,sizeof(pCodeOpRegBit) );
4236 pcop->type = PO_GPR_BIT;
4238 pcop->name = Safe_strdup(s);
4242 PCORB(pcop)->bit = bit;
4243 PCORB(pcop)->inBitSpace = inBitSpace;
4244 PCORB(pcop)->subtype = subt;
4246 /* pCodeOpBit is derived from pCodeOpReg. We need to init this too */
4247 PCOR(pcop)->r = pic16_regWithName(s); //NULL;
4248 // fprintf(stderr, "%s:%d %s for reg: %s\treg= %p\n", __FILE__, __LINE__, __FUNCTION__, s, PCOR(pcop)->r);
4249 // PCOR(pcop)->rIdx = 0;
4253 pCodeOp *pic16_newpCodeOpBit_simple (struct asmop *op, int offs, int bit)
4255 return pic16_newpCodeOpBit (pic16_aopGet(op,offs,FALSE,FALSE),
4256 bit, 0, PO_GPR_REGISTER);
4260 /*-----------------------------------------------------------------*
4261 * pCodeOp *pic16_newpCodeOpReg(int rIdx) - allocate a new register
4263 * If rIdx >=0 then a specific register from the set of registers
4264 * will be selected. If rIdx <0, then a new register will be searched
4266 *-----------------------------------------------------------------*/
4268 pCodeOp *pic16_newpCodeOpReg(int rIdx)
4273 pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
4278 r = pic16_regWithIdx(rIdx);
4280 r = pic16_allocWithIdx(rIdx);
4282 r = pic16_findFreeReg(REG_GPR);
4285 fprintf(stderr, "%s:%d Could not find a free GPR register\n",
4286 __FUNCTION__, __LINE__);
4291 PCOR(pcop)->rIdx = rIdx;
4293 pcop->type = PCOR(pcop)->r->pc_type;
4298 pCodeOp *pic16_newpCodeOpRegNotVect(bitVect *bv)
4303 pcop = Safe_calloc(1, sizeof(pCodeOpReg));
4306 r = pic16_findFreeReg(REG_GPR);
4309 if(!bitVectBitValue(bv, r->rIdx)) {
4311 PCOR(pcop)->rIdx = r->rIdx;
4312 pcop->type = r->pc_type;
4316 r = pic16_findFreeRegNext(REG_GPR, r);
4324 pCodeOp *pic16_newpCodeOpRegFromStr(char *name)
4329 pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
4330 PCOR(pcop)->r = r = pic16_allocRegByName(name, 1, NULL);
4331 PCOR(pcop)->rIdx = PCOR(pcop)->r->rIdx;
4332 pcop->type = PCOR(pcop)->r->pc_type;
4333 pcop->name = PCOR(pcop)->r->name;
4335 // if(pic16_pcode_verbose) {
4336 // fprintf(stderr, "%s:%d %s allocates register %s rIdx:0x%02x\n",
4337 // __FILE__, __LINE__, __FUNCTION__, r->name, r->rIdx);
4343 /*-----------------------------------------------------------------*/
4344 /*-----------------------------------------------------------------*/
4345 pCodeOp *pic16_newpCodeOpOpt(OPT_TYPE type, char *key)
4349 pcop = Safe_calloc(1, sizeof(pCodeOpOpt));
4352 pcop->key = Safe_strdup( key );
4354 return (PCOP(pcop));
4357 /*-----------------------------------------------------------------*/
4358 /*-----------------------------------------------------------------*/
4359 pCodeOp *pic16_newpCodeOpLocalRegs(LR_TYPE type)
4361 pCodeOpLocalReg *pcop;
4363 pcop = Safe_calloc(1, sizeof(pCodeOpLocalReg));
4367 return (PCOP(pcop));
4371 /*-----------------------------------------------------------------*/
4372 /*-----------------------------------------------------------------*/
4374 pCodeOp *pic16_newpCodeOp(char *name, PIC_OPTYPE type)
4381 pcop = pic16_newpCodeOpBit(name, -1,0, type);
4385 pcop = pic16_newpCodeOpLit(-1);
4389 pcop = pic16_newpCodeOpLabel(NULL,-1);
4392 pcop = pic16_newpCodeOpReg(-1);
4395 case PO_GPR_REGISTER:
4397 pcop = pic16_newpCodeOpRegFromStr(name);
4399 pcop = pic16_newpCodeOpReg(-1);
4403 pcop = Safe_calloc(1,sizeof(pCodeOp) );
4406 pcop->name = Safe_strdup(name);
4414 /* This is a multiple of two as gpasm pads DB directives to even length,
4415 * thus the data would be interleaved with \0 bytes...
4416 * This is a multiple of three in order to have arrays of 3-byte pointers
4417 * continuously in memory (without 0-padding at the lines' end).
4418 * This is rather 12 than 6 in order not to split up 4-byte data types
4419 * in arrays right in the middle of a 4-byte word. */
4420 #define DB_ITEMS_PER_LINE 12
4422 typedef struct DBdata
4429 static int DBd_init = -1;
4431 /*-----------------------------------------------------------------*/
4432 /* Initialiase "DB" data buffer */
4433 /*-----------------------------------------------------------------*/
4434 void pic16_initDB(void)
4440 /*-----------------------------------------------------------------*/
4441 /* Flush pending "DB" data to a pBlock */
4443 /* ptype - type of p pointer, 'f' file pointer, 'p' pBlock pointer */
4444 /*-----------------------------------------------------------------*/
4445 void pic16_flushDB(char ptype, void *p)
4449 pic16_addpCode2pBlock(((pBlock *)p),pic16_newpCodeAsmDir("DB", "%s", DBd.buffer));
4452 fprintf(((FILE *)p), "\tdb\t%s\n", DBd.buffer);
4455 fprintf(stderr, "PIC16 port error: could not emit initial value data\n");
4459 DBd.buffer[0] = '\0';
4464 /*-----------------------------------------------------------------*/
4465 /* Add "DB" directives to a pBlock */
4466 /*-----------------------------------------------------------------*/
4467 void pic16_emitDB(int c, char ptype, void *p)
4472 // we need to initialize
4475 DBd.buffer[0] = '\0';
4478 l = strlen(DBd.buffer);
4479 sprintf(DBd.buffer+l,"%s0x%02x", (DBd.count>0?", ":""), c & 0xff);
4481 // fprintf(stderr, "%s:%d DBbuffer: '%s'\n", __FILE__, __LINE__, DBd.buffer);
4484 if (DBd.count>= DB_ITEMS_PER_LINE)
4485 pic16_flushDB(ptype, p);
4488 void pic16_emitDS(char *s, char ptype, void *p)
4493 // we need to initialize
4496 DBd.buffer[0] = '\0';
4499 l = strlen(DBd.buffer);
4500 sprintf(DBd.buffer+l,"%s%s", (DBd.count>0?", ":""), s);
4502 // fprintf(stderr, "%s:%d DBbuffer: '%s'\n", __FILE__, __LINE__, DBd.buffer);
4504 DBd.count++; //=strlen(s);
4505 if (DBd.count>=DB_ITEMS_PER_LINE)
4506 pic16_flushDB(ptype, p);
4510 /*-----------------------------------------------------------------*/
4511 /*-----------------------------------------------------------------*/
4512 void pic16_pCodeConstString(char *name, char *value)
4516 static set *emittedSymbols = NULL;
4521 /* keep track of emitted symbols to avoid multiple definition of str_<nr> */
4522 if (emittedSymbols) {
4523 /* scan set for name */
4524 for (item = setFirstItem (emittedSymbols); item; item = setNextItem (emittedSymbols))
4526 if (!strcmp (item,name)) {
4527 //fprintf (stderr, "%s already emitted\n", name);
4532 addSet (&emittedSymbols, Safe_strdup (name));
4534 //fprintf(stderr, " %s %s %s\n",__FUNCTION__,name,value);
4536 pb = pic16_newpCodeChain(NULL, 'P',pic16_newpCodeCharP("; Starting pCode block"));
4538 pic16_addpBlock(pb);
4540 // sprintf(buffer,"; %s = ", name);
4541 // strcat(buffer, value);
4542 // fputs(buffer, stderr);
4544 // pic16_addpCode2pBlock(pb,pic16_newpCodeCharP(buffer));
4545 pic16_addpCode2pBlock(pb,pic16_newpCodeLabel(name,-1));
4548 pic16_emitDB(*value, 'p', (void *)pb);
4550 pic16_flushDB('p', (void *)pb);
4553 /*-----------------------------------------------------------------*/
4554 /*-----------------------------------------------------------------*/
4556 static void pCodeReadCodeTable(void)
4560 fprintf(stderr, " %s\n",__FUNCTION__);
4562 pb = pic16_newpCodeChain(NULL, 'P',pic16_newpCodeCharP("; Starting pCode block"));
4564 pic16_addpBlock(pb);
4566 pic16_addpCode2pBlock(pb,pic16_newpCodeCharP("; ReadCodeTable - built in function"));
4567 pic16_addpCode2pBlock(pb,pic16_newpCodeCharP("; Inputs: temp1,temp2 = code pointer"));
4568 pic16_addpCode2pBlock(pb,pic16_newpCodeCharP("; Outpus: W (from RETLW at temp2:temp1)"));
4569 pic16_addpCode2pBlock(pb,pic16_newpCodeLabel("ReadCodeTable:",-1));
4571 pic16_addpCode2pBlock(pb,pic16_newpCode(POC_MOVFW,pic16_newpCodeOpRegFromStr("temp2")));
4572 pic16_addpCode2pBlock(pb,pic16_newpCode(POC_MOVWF,pic16_newpCodeOpRegFromStr("PCLATH")));
4573 pic16_addpCode2pBlock(pb,pic16_newpCode(POC_MOVFW,pic16_newpCodeOpRegFromStr("temp1")));
4574 pic16_addpCode2pBlock(pb,pic16_newpCode(POC_MOVWF,pic16_newpCodeOpRegFromStr("PCL")));
4579 /*-----------------------------------------------------------------*/
4580 /* pic16_addpCode2pBlock - place the pCode into the pBlock linked list */
4581 /*-----------------------------------------------------------------*/
4582 void pic16_addpCode2pBlock(pBlock *pb, pCode *pc)
4589 /* If this is the first pcode to be added to a block that
4590 * was initialized with a NULL pcode, then go ahead and
4591 * make this pcode the head and tail */
4592 pb->pcHead = pb->pcTail = pc;
4595 pb->pcTail->next = pc;
4597 pc->prev = pb->pcTail;
4604 /*-----------------------------------------------------------------*/
4605 /* pic16_addpBlock - place a pBlock into the pFile */
4606 /*-----------------------------------------------------------------*/
4607 void pic16_addpBlock(pBlock *pb)
4609 // fprintf(stderr," Adding pBlock: dbName =%c\n",getpBlock_dbName(pb));
4612 /* First time called, we'll pass through here. */
4613 //_ALLOC(the_pFile,sizeof(pFile));
4614 the_pFile = Safe_calloc(1,sizeof(pFile));
4615 the_pFile->pbHead = the_pFile->pbTail = pb;
4616 the_pFile->functions = NULL;
4620 the_pFile->pbTail->next = pb;
4621 pb->prev = the_pFile->pbTail;
4623 the_pFile->pbTail = pb;
4626 /*-----------------------------------------------------------------*/
4627 /* removepBlock - remove a pBlock from the pFile */
4628 /*-----------------------------------------------------------------*/
4629 static void removepBlock(pBlock *pb)
4637 //fprintf(stderr," Removing pBlock: dbName =%c\n",getpBlock_dbName(pb));
4639 for(pbs = the_pFile->pbHead; pbs; pbs = pbs->next) {
4642 if(pbs == the_pFile->pbHead)
4643 the_pFile->pbHead = pbs->next;
4645 if (pbs == the_pFile->pbTail)
4646 the_pFile->pbTail = pbs->prev;
4649 pbs->next->prev = pbs->prev;
4652 pbs->prev->next = pbs->next;
4659 fprintf(stderr, "Warning: call to %s:%s didn't find pBlock\n",__FILE__,__FUNCTION__);
4663 /*-----------------------------------------------------------------*/
4664 /* printpCode - write the contents of a pCode to a file */
4665 /*-----------------------------------------------------------------*/
4666 static void printpCode(FILE *of, pCode *pc)
4677 fprintf(of,"warning - unable to print pCode\n");
4680 /*-----------------------------------------------------------------*/
4681 /* pic16_printpBlock - write the contents of a pBlock to a file */
4682 /*-----------------------------------------------------------------*/
4683 void pic16_printpBlock(FILE *of, pBlock *pb)
4691 for(pc = pb->pcHead; pc; pc = pc->next) {
4692 if(isPCF(pc) && PCF(pc)->fname) {
4693 fprintf(of, "S_%s_%s\tcode", PCF(pc)->modname, PCF(pc)->fname);
4694 if(pb->dbName == 'A') {
4696 for(ab=setFirstItem(absSymSet); ab; ab=setNextItem(absSymSet)) {
4697 // fprintf(stderr, "%s:%d testing %s <-> %s\n", __FILE__, __LINE__, PCF(pc)->fname, ab->name);
4698 if(!strcmp(ab->name, PCF(pc)->fname)) {
4699 // fprintf(stderr, "%s:%d address = %x\n", __FILE__, __LINE__, ab->address);
4700 if(ab->address != -1)
4701 fprintf(of, "\t0X%06X", ab->address);
4712 /*-----------------------------------------------------------------*/
4714 /* pCode processing */
4718 /*-----------------------------------------------------------------*/
4719 pCode * pic16_findNextInstruction(pCode *pci);
4720 pCode * pic16_findPrevInstruction(pCode *pci);
4722 void pic16_unlinkpCode(pCode *pc)
4728 fprintf(stderr,"Unlinking: ");
4729 printpCode(stderr, pc);
4732 pc->prev->next = pc->next;
4734 pc->next->prev = pc->prev;
4736 /* move C source line down (or up) */
4737 if (isPCI(pc) && PCI(pc)->cline) {
4738 prev = pic16_findNextInstruction (pc->next);
4739 if (prev && isPCI(prev) && !PCI(prev)->cline) {
4740 PCI(prev)->cline = PCI(pc)->cline;
4742 prev = pic16_findPrevInstruction (pc->prev);
4743 if (prev && isPCI(prev) && !PCI(prev)->cline)
4744 PCI(prev)->cline = PCI(pc)->cline;
4747 pc->prev = pc->next = NULL;
4751 /*-----------------------------------------------------------------*/
4752 /*-----------------------------------------------------------------*/
4754 static void genericDestruct(pCode *pc)
4757 pic16_unlinkpCode(pc);
4760 /* For instructions, tell the register (if there's one used)
4761 * that it's no longer needed */
4762 regs *reg = pic16_getRegFromInstruction(pc);
4764 deleteSetItem (&(reg->reglives.usedpCodes),pc);
4766 if(PCI(pc)->is2MemOp) {
4767 reg = pic16_getRegFromInstruction2(pc);
4769 deleteSetItem(&(reg->reglives.usedpCodes), pc);
4773 /* Instead of deleting the memory used by this pCode, mark
4774 * the object as bad so that if there's a pointer to this pCode
4775 * dangling around somewhere then (hopefully) when the type is
4776 * checked we'll catch it.
4780 pic16_addpCode2pBlock(pb_dead_pcodes, pc);
4786 void DEBUGpic16_emitcode (char *inst,char *fmt, ...);
4787 /*-----------------------------------------------------------------*/
4788 /*-----------------------------------------------------------------*/
4789 /* modifiers for constant immediate */
4790 const char *immdmod[3]={"LOW", "HIGH", "UPPER"};
4792 char *pic16_get_op(pCodeOp *pcop,char *buffer, size_t size)
4797 int use_buffer = 1; // copy the string to the passed buffer pointer
4802 use_buffer = 0; // Don't bother copying the string to the buffer.
4806 switch(pcop->type) {
4814 SAFE_snprintf(&buffer,&size,"%s",PCOR(pcop)->r->name);
4817 return PCOR(pcop)->r->name;
4820 r = pic16_regWithIdx(PCOR(pcop)->r->rIdx);
4822 SAFE_snprintf(&buffer,&size,"%s",r->name);
4829 if(PCOI(pcop)->offset && PCOI(pcop)->offset<4) {
4830 if(PCOI(pcop)->index) {
4831 SAFE_snprintf(&s,&size, "%s(%s + %d)",
4832 immdmod[ PCOI(pcop)->offset ],
4836 SAFE_snprintf(&s,&size,"%s(%s)",
4837 immdmod[ PCOI(pcop)->offset ],
4841 if(PCOI(pcop)->index) {
4842 SAFE_snprintf(&s,&size, "%s(%s + %d)",
4847 SAFE_snprintf(&s,&size, "%s(%s)",
4854 case PO_GPR_REGISTER:
4857 // size = sizeof(buffer);
4858 if( PCOR(pcop)->instance) {
4859 SAFE_snprintf(&s,&size,"(%s + %d)",
4861 PCOR(pcop)->instance );
4863 SAFE_snprintf(&s,&size,"%s",pcop->name);
4868 if(PCORB(pcop)->subtype == PO_GPR_TEMP) {
4869 SAFE_snprintf(&s, &size, "%s", pcop->name);
4871 if(PCORB(pcop)->pcor.instance)
4872 SAFE_snprintf(&s, &size, "(%s + %d)", pcop->name, PCORB(pcop)->pcor.instance);
4874 SAFE_snprintf(&s, &size, "%s", pcop->name);
4881 SAFE_snprintf(&buffer,&size,"%s",pcop->name);
4890 return "NO operand1";
4893 /*-----------------------------------------------------------------*/
4894 /* pic16_get_op2 - variant to support two memory operand commands */
4895 /*-----------------------------------------------------------------*/
4896 char *pic16_get_op2(pCodeOp *pcop,char *buffer, size_t size)
4901 int use_buffer = 1; // copy the string to the passed buffer pointer
4906 use_buffer = 0; // Don't bother copying the string to the buffer.
4910 fprintf(stderr, "%s:%d second operand %s is %d\tPO_DIR(%d) PO_GPR_TEMP(%d) PO_IMMEDIATE(%d) PO_INDF0(%d) PO_FSR0(%d)\n",
4911 __FUNCTION__, __LINE__, PCOR(PCOR2(pcop)->pcop2)->r->name, PCOR2(pcop)->pcop2->type,
4912 PO_DIR, PO_GPR_TEMP, PO_IMMEDIATE, PO_INDF0, PO_FSR0);
4916 switch(PCOR2(pcop)->pcop2->type) {
4924 SAFE_snprintf(&buffer,&size,"%s",PCOR(PCOR2(pcop)->pcop2)->r->name);
4927 return PCOR(PCOR2(pcop)->pcop2)->r->name;
4930 r = pic16_regWithIdx(PCOR(PCOR2(pcop)->pcop2)->r->rIdx);
4933 SAFE_snprintf(&buffer,&size,"%s",r->name);
4944 if(PCOI(pcop)->_const) {
4945 if( PCOI(pcop)->offset && PCOI(pcop)->offset<4) {
4946 SAFE_snprintf(&s,&size,"(((%s+%d) >> %d)&0xff)",
4949 8 * PCOI(pcop)->offset );
4951 SAFE_snprintf(&s,&size,"LOW(%s+%d)",pcop->name,PCOI(pcop)->index);
4953 if( PCOI(pcop)->index) {
4954 SAFE_snprintf(&s,&size,"(%s + %d)",
4956 PCOI(pcop)->index );
4958 if(PCOI(pcop)->offset)
4959 SAFE_snprintf(&s,&size,"(%s >> %d)&0xff",pcop->name, 8*PCOI(pcop)->offset);
4961 SAFE_snprintf(&s,&size,"%s",pcop->name);
4968 if( PCOR(PCOR2(pcop)->pcop2)->instance) {
4969 SAFE_snprintf(&s,&size,"(%s + %d)",
4970 PCOR(PCOR2(pcop)->pcop2)->r->name,
4971 PCOR(PCOR2(pcop)->pcop2)->instance );
4973 SAFE_snprintf(&s,&size,"%s",PCOR(PCOR2(pcop)->pcop2)->r->name);
4978 if(PCOR(PCOR2(pcop)->pcop2)->r->name) {
4980 SAFE_snprintf(&buffer,&size,"%s",PCOR(PCOR2(pcop)->pcop2)->r->name);
4983 return PCOR(PCOR2(pcop)->pcop2)->r->name;
4988 return "NO operand2";
4991 /*-----------------------------------------------------------------*/
4992 /*-----------------------------------------------------------------*/
4993 static char *pic16_get_op_from_instruction( pCodeInstruction *pcc)
4997 return pic16_get_op(pcc->pcop,NULL,0);
4999 /* gcc 3.2: warning: concatenation of string literals with __FUNCTION__ is deprecated
5000 * return ("ERROR Null: "__FUNCTION__);
5002 return ("ERROR Null: pic16_get_op_from_instruction");
5006 /*-----------------------------------------------------------------*/
5007 /*-----------------------------------------------------------------*/
5008 static void pCodeOpPrint(FILE *of, pCodeOp *pcop)
5011 fprintf(of,"pcodeopprint- not implemented\n");
5014 /*-----------------------------------------------------------------*/
5015 /* pic16_pCode2str - convert a pCode instruction to string */
5016 /*-----------------------------------------------------------------*/
5017 char *pic16_pCode2str(char *str, size_t size, pCode *pc)
5023 if(isPCI(pc) && (PCI(pc)->pci_magic != PCI_MAGIC)) {
5024 fprintf(stderr, "%s:%d: pCodeInstruction initialization error in instruction %s, magic is %x (defaut: %x)\n",
5025 __FILE__, __LINE__, PCI(pc)->mnemonic, PCI(pc)->pci_magic, PCI_MAGIC);
5033 SAFE_snprintf(&s,&size, "\t%s\t", PCI(pc)->mnemonic);
5035 if( (PCI(pc)->num_ops >= 1) && (PCI(pc)->pcop)) {
5037 if(PCI(pc)->is2MemOp) {
5038 SAFE_snprintf(&s,&size, "%s, %s",
5039 pic16_get_op(PCOP(PCI(pc)->pcop), NULL, 0),
5040 pic16_get_op2(PCOP(PCI(pc)->pcop), NULL, 0));
5044 if(PCI(pc)->is2LitOp) {
5045 SAFE_snprintf(&s,&size, "%s", PCOP(PCI(pc)->pcop)->name);
5049 if(PCI(pc)->isBitInst) {
5050 if(PCI(pc)->pcop->type != PO_GPR_BIT) {
5051 if( (((pCodeOpRegBit *)(PCI(pc)->pcop))->inBitSpace) )
5052 SAFE_snprintf(&s,&size,"(%s >> 3), (%s & 7)",
5053 PCI(pc)->pcop->name ,
5054 PCI(pc)->pcop->name );
5056 SAFE_snprintf(&s,&size,"%s,%d", pic16_get_op_from_instruction(PCI(pc)),
5057 // (((pCodeOpRegBit *)(PCI(pc)->pcop))->pcor.instance),
5058 (((pCodeOpRegBit *)(PCI(pc)->pcop))->bit ));
5060 } else if(PCI(pc)->pcop->type == PO_GPR_BIT) {
5061 SAFE_snprintf(&s,&size,"%s, %d", pic16_get_op_from_instruction(PCI(pc)),PCORB(PCI(pc)->pcop)->bit);
5063 SAFE_snprintf(&s,&size,"%s,0 ; ?bug", pic16_get_op_from_instruction(PCI(pc)));
5064 //PCI(pc)->pcop->t.bit );
5067 if(PCI(pc)->pcop->type == PO_GPR_BIT) {
5068 if( PCI(pc)->num_ops == 3)
5069 SAFE_snprintf(&s,&size,"(%s >> 3),%c",pic16_get_op_from_instruction(PCI(pc)),((PCI(pc)->isModReg) ? 'F':'W'));
5071 SAFE_snprintf(&s,&size,"(1 << (%s & 7))",pic16_get_op_from_instruction(PCI(pc)));
5076 SAFE_snprintf(&s,&size,"%s", pic16_get_op_from_instruction(PCI(pc)));
5079 if( PCI(pc)->num_ops == 3 || ((PCI(pc)->num_ops == 2) && (PCI(pc)->isAccess))) {
5080 if(PCI(pc)->num_ops == 3 && !PCI(pc)->isBitInst)
5081 SAFE_snprintf(&s,&size,", %c", ( (PCI(pc)->isModReg) ? 'F':'W'));
5083 r = pic16_getRegFromInstruction(pc);
5084 // fprintf(stderr, "%s:%d reg = %p\tname= %s, accessBank= %d\n",
5085 // __FUNCTION__, __LINE__, r, (r)?r->name:"<null>", (r)?r->accessBank:-1);
5087 if(PCI(pc)->isAccess) {
5088 static char *bank_spec[2][2] = {
5089 { "", ", ACCESS" }, /* gpasm uses access bank by default */
5090 { ", B", ", BANKED" }/* MPASM (should) use BANKED by default */
5093 SAFE_snprintf(&s,&size,"%s", bank_spec[(r && !r->accessBank) ? 1 : 0][pic16_mplab_comp ? 1 : 0]);
5102 /* assuming that comment ends with a \n */
5103 SAFE_snprintf(&s,&size,";%s", ((pCodeComment *)pc)->comment);
5107 SAFE_snprintf(&s,&size,"; info ==>");
5108 switch( PCINF(pc)->type ) {
5109 case INF_OPTIMIZATION:
5110 SAFE_snprintf(&s,&size, " [optimization] %s\n", OPT_TYPE_STR[ PCOO(PCINF(pc)->oper1)->type ]);
5113 SAFE_snprintf(&s,&size, " [localregs] %s\n", LR_TYPE_STR[ PCOLR(PCINF(pc)->oper1)->type ]);
5118 /* assuming that inline code ends with a \n */
5119 SAFE_snprintf(&s,&size,"%s", ((pCodeComment *)pc)->comment);
5123 SAFE_snprintf(&s,&size,";label=%s, key=%d\n",PCL(pc)->label,PCL(pc)->key);
5126 SAFE_snprintf(&s,&size,";modname=%s,function=%s: id=%d\n",PCF(pc)->modname,PCF(pc)->fname);
5129 SAFE_snprintf(&s,&size,";\tWild opcode: id=%d\n",PCW(pc)->id);
5132 SAFE_snprintf(&s,&size,";\t--FLOW change\n");
5135 // SAFE_snprintf(&s,&size,";#CSRC\t%s %d\t%s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
5136 SAFE_snprintf(&s,&size,"%s\t.line\t%d; %s\t%s\n", ((pic16_mplab_comp || !options.debug)?";":""),
5137 PCCS(pc)->line_number, PCCS(pc)->file_name, PCCS(pc)->line);
5140 if(PCAD(pc)->directive) {
5141 SAFE_snprintf(&s,&size,"\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
5144 /* special case to handle inline labels without a tab */
5145 SAFE_snprintf(&s,&size,"%s\n", PCAD(pc)->arg);
5150 SAFE_snprintf(&s,&size,";A bad pCode is being used\n");
5158 /*-----------------------------------------------------------------*/
5159 /* genericPrint - the contents of a pCode to a file */
5160 /*-----------------------------------------------------------------*/
5161 static void genericPrint(FILE *of, pCode *pc)
5169 // fputs(((pCodeComment *)pc)->comment, of);
5170 fprintf(of,"; %s\n", ((pCodeComment *)pc)->comment);
5175 pBranch *pbl = PCI(pc)->label;
5176 while(pbl && pbl->pc) {
5177 if(pbl->pc->type == PC_LABEL)
5178 pCodePrintLabel(of, pbl->pc);
5183 if(pic16_pcode_verbose) {
5184 fprintf(of, "; info ==>");
5185 switch(((pCodeInfo *)pc)->type) {
5186 case INF_OPTIMIZATION:
5187 fprintf(of, " [optimization] %s\n", OPT_TYPE_STR[ PCOO(PCINF(pc)->oper1)->type ]);
5190 fprintf(of, " [localregs] %s\n", LR_TYPE_STR[ PCOLR(PCINF(pc)->oper1)->type ]);
5198 fprintf(of,"%s\n", ((pCodeComment *)pc)->comment);
5202 // If the opcode has a label, print that first
5204 pBranch *pbl = PCI(pc)->label;
5205 while(pbl && pbl->pc) {
5206 if(pbl->pc->type == PC_LABEL)
5207 pCodePrintLabel(of, pbl->pc);
5213 genericPrint(of,PCODE(PCI(pc)->cline));
5218 pic16_pCode2str(str, 256, pc);
5220 fprintf(of,"%s",str);
5222 if(pic16_debug_verbose) {
5223 fprintf(of, "\t;key=%03x",pc->seq);
5225 fprintf(of,", flow seq=%03x",PCI(pc)->pcflow->pc.seq);
5232 fprintf(of,";\tWild opcode: id=%d\n",PCW(pc)->id);
5233 if(PCW(pc)->pci.label)
5234 pCodePrintLabel(of, PCW(pc)->pci.label->pc);
5236 if(PCW(pc)->operand) {
5237 fprintf(of,";\toperand ");
5238 pCodeOpPrint(of,PCW(pc)->operand );
5243 if(pic16_debug_verbose) {
5244 fprintf(of,";<>Start of new flow, seq=0x%x",pc->seq);
5245 if(PCFL(pc)->ancestor)
5246 fprintf(of," ancestor = 0x%x", PCODE(PCFL(pc)->ancestor)->seq);
5253 // fprintf(of,";#CSRC\t%s %d\t\t%s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
5254 fprintf(of,"%s\t.line\t%d; %s\t%s\n", ((pic16_mplab_comp || !options.debug)?";":""),
5255 PCCS(pc)->line_number, PCCS(pc)->file_name, PCCS(pc)->line);
5261 pBranch *pbl = PCAD(pc)->pci.label;
5262 while(pbl && pbl->pc) {
5263 if(pbl->pc->type == PC_LABEL)
5264 pCodePrintLabel(of, pbl->pc);
5268 if(PCAD(pc)->directive) {
5269 fprintf(of, "\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
5272 /* special case to handle inline labels without tab */
5273 fprintf(of, "%s\n", PCAD(pc)->arg);
5279 fprintf(of,"unknown pCode type %d\n",pc->type);
5284 /*-----------------------------------------------------------------*/
5285 /* pCodePrintFunction - prints function begin/end */
5286 /*-----------------------------------------------------------------*/
5288 static void pCodePrintFunction(FILE *of, pCode *pc)
5295 if( ((pCodeFunction *)pc)->modname)
5296 fprintf(of,"F_%s",((pCodeFunction *)pc)->modname);
5299 if(!PCF(pc)->absblock) {
5300 if(PCF(pc)->fname) {
5301 pBranch *exits = PCF(pc)->to;
5304 fprintf(of,"%s:", PCF(pc)->fname);
5306 if(pic16_pcode_verbose)
5307 fprintf(of, "\t;Function start");
5313 exits = exits->next;
5317 if(pic16_pcode_verbose)
5318 fprintf(of,"; %d exit point%c\n",i, ((i==1) ? ' ':'s'));
5321 if((PCF(pc)->from &&
5322 PCF(pc)->from->pc->type == PC_FUNCTION &&
5323 PCF(PCF(pc)->from->pc)->fname) ) {
5325 if(pic16_pcode_verbose)
5326 fprintf(of,"; exit point of %s\n",PCF(PCF(pc)->from->pc)->fname);
5328 if(pic16_pcode_verbose)
5329 fprintf(of,"; exit point [can't find entry point]\n");
5335 /*-----------------------------------------------------------------*/
5336 /* pCodePrintLabel - prints label */
5337 /*-----------------------------------------------------------------*/
5339 static void pCodePrintLabel(FILE *of, pCode *pc)
5346 fprintf(of,"%s:\n",PCL(pc)->label);
5347 else if (PCL(pc)->key >=0)
5348 fprintf(of,"_%05d_DS_:\n",PCL(pc)->key);
5350 fprintf(of,";wild card label: id=%d\n",-PCL(pc)->key);
5353 /*-----------------------------------------------------------------*/
5354 /* unlinkpCodeFromBranch - Search for a label in a pBranch and */
5355 /* remove it if it is found. */
5356 /*-----------------------------------------------------------------*/
5357 static void unlinkpCodeFromBranch(pCode *pcl , pCode *pc)
5364 if(pcl->type == PC_OPCODE || pcl->type == PC_INLINE || pcl->type == PC_ASMDIR)
5365 b = PCI(pcl)->label;
5367 fprintf(stderr, "LINE %d. can't unlink from non opcode\n",__LINE__);
5372 //fprintf (stderr, "%s \n",__FUNCTION__);
5373 //pcl->print(stderr,pcl);
5374 //pc->print(stderr,pc);
5377 //fprintf (stderr, "found label\n");
5378 //pc->print(stderr, pc);
5382 bprev->next = b->next; /* Not first pCode in chain */
5386 PCI(pcl)->label = b->next; /* First pCode in chain */
5389 return; /* A label can't occur more than once */
5397 /*-----------------------------------------------------------------*/
5398 /*-----------------------------------------------------------------*/
5399 pBranch * pic16_pBranchAppend(pBranch *h, pBranch *n)
5418 /*-----------------------------------------------------------------*/
5419 /* pBranchLink - given two pcodes, this function will link them */
5420 /* together through their pBranches */
5421 /*-----------------------------------------------------------------*/
5422 static void pBranchLink(pCodeFunction *f, pCodeFunction *t)
5426 // Declare a new branch object for the 'from' pCode.
5428 //_ALLOC(b,sizeof(pBranch));
5429 b = Safe_calloc(1,sizeof(pBranch));
5430 b->pc = PCODE(t); // The link to the 'to' pCode.
5433 f->to = pic16_pBranchAppend(f->to,b);
5435 // Now do the same for the 'to' pCode.
5437 //_ALLOC(b,sizeof(pBranch));
5438 b = Safe_calloc(1,sizeof(pBranch));
5442 t->from = pic16_pBranchAppend(t->from,b);
5447 /*-----------------------------------------------------------------*/
5448 /* pBranchFind - find the pBranch in a pBranch chain that contains */
5450 /*-----------------------------------------------------------------*/
5451 static pBranch *pBranchFind(pBranch *pb,pCode *pc)
5464 /*-----------------------------------------------------------------*/
5465 /* pic16_pCodeUnlink - Unlink the given pCode from its pCode chain. */
5466 /*-----------------------------------------------------------------*/
5467 void pic16_pCodeUnlink(pCode *pc)
5472 if(!pc->prev || !pc->next) {
5473 fprintf(stderr,"unlinking bad pCode in %s:%d\n",__FILE__,__LINE__);
5477 /* move C source line down (or up) */
5478 if (isPCI(pc) && PCI(pc)->cline) {
5479 pc1 = pic16_findNextInstruction (pc->next);
5480 if (pc1 && isPCI(pc1) && !PCI(pc1)->cline) {
5481 PCI(pc1)->cline = PCI(pc)->cline;
5483 pc1 = pic16_findPrevInstruction (pc->prev);
5484 if (pc1 && isPCI(pc1) && !PCI(pc1)->cline)
5485 PCI(pc1)->cline = PCI(pc)->cline;
5489 /* first remove the pCode from the chain */
5490 pc->prev->next = pc->next;
5491 pc->next->prev = pc->prev;
5493 pc->prev = pc->next = NULL;
5495 /* Now for the hard part... */
5497 /* Remove the branches */
5499 pb1 = PCI(pc)->from;
5501 pc1 = pb1->pc; /* Get the pCode that branches to the
5502 * one we're unlinking */
5504 /* search for the link back to this pCode (the one we're
5506 if((pb2 = pBranchFind(PCI(pc1)->to,pc))) {
5507 pb2->pc = PCI(pc)->to->pc; // make the replacement
5509 /* if the pCode we're unlinking contains multiple 'to'
5510 * branches (e.g. this a skip instruction) then we need
5511 * to copy these extra branches to the chain. */
5512 if(PCI(pc)->to->next)
5513 pic16_pBranchAppend(pb2, PCI(pc)->to->next);
5522 /*-----------------------------------------------------------------*/
5523 /*-----------------------------------------------------------------*/
5525 static void genericAnalyze(pCode *pc)
5535 // Go through the pCodes that are in pCode chain and link
5536 // them together through the pBranches. Note, the pCodes
5537 // are linked together as a contiguous stream like the
5538 // assembly source code lines. The linking here mimics this
5539 // except that comments are not linked in.
5541 pCode *npc = pc->next;
5543 if(npc->type == PC_OPCODE || npc->type == PC_LABEL) {
5544 pBranchLink(pc,npc);
5549 /* reached the end of the pcode chain without finding
5550 * an instruction we could link to. */
5554 fprintf(stderr,"analyze PC_FLOW\n");
5558 fprintf(stderr,,";A bad pCode is being used\n");
5564 /*-----------------------------------------------------------------*/
5565 /*-----------------------------------------------------------------*/
5566 static int compareLabel(pCode *pc, pCodeOpLabel *pcop_label)
5570 if(pc->type == PC_LABEL) {
5571 if( ((pCodeLabel *)pc)->key == pcop_label->key)
5574 if((pc->type == PC_OPCODE)
5575 || (pc->type == PC_ASMDIR)
5577 pbr = PCI(pc)->label;
5579 if(pbr->pc->type == PC_LABEL) {
5580 if( ((pCodeLabel *)(pbr->pc))->key == pcop_label->key)
5590 /*-----------------------------------------------------------------*/
5591 /*-----------------------------------------------------------------*/
5592 static int checkLabel(pCode *pc)
5596 if(pc && isPCI(pc)) {
5597 pbr = PCI(pc)->label;
5599 if(isPCL(pbr->pc) && (PCL(pbr->pc)->key >= 0))
5609 /*-----------------------------------------------------------------*/
5610 /* findLabelinpBlock - Search the pCode for a particular label */
5611 /*-----------------------------------------------------------------*/
5612 static pCode * findLabelinpBlock(pBlock *pb,pCodeOpLabel *pcop_label)
5619 for(pc = pb->pcHead; pc; pc = pc->next)
5620 if(compareLabel(pc,pcop_label))
5626 /*-----------------------------------------------------------------*/
5627 /* findLabel - Search the pCode for a particular label */
5628 /*-----------------------------------------------------------------*/
5629 static pCode * findLabel(pCodeOpLabel *pcop_label)
5637 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5638 if( (pc = findLabelinpBlock(pb,pcop_label)) != NULL)
5642 fprintf(stderr,"Couldn't find label %s", pcop_label->pcop.name);
5646 /*-----------------------------------------------------------------*/
5647 /* pic16_findNextpCode - given a pCode, find the next of type 'pct' */
5648 /* in the linked list */
5649 /*-----------------------------------------------------------------*/
5650 pCode * pic16_findNextpCode(pCode *pc, PC_TYPE pct)
5663 /*-----------------------------------------------------------------*/
5664 /* findPrevpCode - given a pCode, find the previous of type 'pct' */
5665 /* in the linked list */
5666 /*-----------------------------------------------------------------*/
5667 static pCode * findPrevpCode(pCode *pc, PC_TYPE pct)
5681 //#define PCODE_DEBUG
5682 /*-----------------------------------------------------------------*/
5683 /* pic16_findNextInstruction - given a pCode, find the next instruction */
5684 /* in the linked list */
5685 /*-----------------------------------------------------------------*/
5686 pCode * pic16_findNextInstruction(pCode *pci)
5691 if((pc->type == PC_OPCODE)
5692 || (pc->type == PC_WILD)
5693 || (pc->type == PC_ASMDIR)
5698 fprintf(stderr,"pic16_findNextInstruction: ");
5699 printpCode(stderr, pc);
5704 //fprintf(stderr,"Couldn't find instruction\n");
5708 /*-----------------------------------------------------------------*/
5709 /* pic16_findPrevInstruction - given a pCode, find the next instruction */
5710 /* in the linked list */
5711 /*-----------------------------------------------------------------*/
5712 pCode * pic16_findPrevInstruction(pCode *pci)
5718 if((pc->type == PC_OPCODE)
5719 || (pc->type == PC_WILD)
5720 || (pc->type == PC_ASMDIR)
5726 fprintf(stderr,"pic16_findPrevInstruction: ");
5727 printpCode(stderr, pc);
5732 //fprintf(stderr,"Couldn't find instruction\n");
5739 /*-----------------------------------------------------------------*/
5740 /* findFunctionEnd - given a pCode find the end of the function */
5741 /* that contains it */
5742 /*-----------------------------------------------------------------*/
5743 static pCode * findFunctionEnd(pCode *pc)
5747 if(pc->type == PC_FUNCTION && !(PCF(pc)->fname))
5753 fprintf(stderr,"Couldn't find function end\n");
5758 /*-----------------------------------------------------------------*/
5759 /* AnalyzeLabel - if the pCode is a label, then merge it with the */
5760 /* instruction with which it is associated. */
5761 /*-----------------------------------------------------------------*/
5762 static void AnalyzeLabel(pCode *pc)
5765 pic16_pCodeUnlink(pc);
5771 static void AnalyzeGOTO(pCode *pc)
5774 pBranchLink(pc,findLabel( (pCodeOpLabel *) (PCI(pc)->pcop) ));
5778 static void AnalyzeSKIP(pCode *pc)
5781 pBranchLink(pc,pic16_findNextInstruction(pc->next));
5782 pBranchLink(pc,pic16_findNextInstruction(pc->next->next));
5786 static void AnalyzeRETURN(pCode *pc)
5789 // branch_link(pc,findFunctionEnd(pc->next));
5795 /*-------------------------------------------------------------------*/
5796 /* pic16_getRegFrompCodeOp - extract the register from a pCodeOp */
5797 /* if one is present. This is the common */
5798 /* part of pic16_getRegFromInstruction(2) */
5799 /*-------------------------------------------------------------------*/
5801 regs * pic16_getRegFrompCodeOp (pCodeOp *pcop) {
5802 if (!pcop) return NULL;
5804 switch(pcop->type) {
5817 return PCOR(pcop)->r;
5819 case PO_SFR_REGISTER:
5820 //fprintf (stderr, "%s - SFR\n", __FUNCTION__);
5821 return PCOR(pcop)->r;
5825 // fprintf(stderr, "pic16_getRegFromInstruction - bit or temp\n");
5826 return PCOR(pcop)->r;
5829 // return pic16_dirregWithName(PCOI(pcop)->r->name);
5832 return (PCOI(pcop)->r);
5837 return PCOR(pcop)->r;
5839 case PO_GPR_REGISTER:
5841 // fprintf(stderr, "pic16_getRegFromInstruction - dir\n");
5842 return PCOR(pcop)->r;
5845 //fprintf(stderr, "pic16_getRegFromInstruction - literal\n");
5850 //fprintf (stderr, "%s - label or address: %d (%s)\n", __FUNCTION__, pcop->type, dumpPicOptype(pcop->type));
5855 /* this should never turn up */
5856 //fprintf (stderr, "%s - unused pCodeOp->type: %d (%s)\n", __FUNCTION__, pcop->type, dumpPicOptype(pcop->type));
5863 fprintf(stderr, "pic16_getRegFromInstruction - unknown reg type %d (%s)\n",pcop->type, dumpPicOptype (pcop->type));
5871 /*-----------------------------------------------------------------*/
5872 /*-----------------------------------------------------------------*/
5873 regs * pic16_getRegFromInstruction(pCode *pc)
5879 PCI(pc)->num_ops == 0 ||
5880 (PCI(pc)->num_ops == 1 && PCI(pc)->isFastCall))
5884 fprintf(stderr, "pic16_getRegFromInstruction - reg type %s (%d)\n",
5885 dumpPicOptype( PCI(pc)->pcop->type), PCI(pc)->pcop->type);
5888 return pic16_getRegFrompCodeOp (PCI(pc)->pcop);
5891 /*-------------------------------------------------------------------------------*/
5892 /* pic16_getRegFromInstruction2 - variant to support two memory operand commands */
5893 /*-------------------------------------------------------------------------------*/
5894 regs * pic16_getRegFromInstruction2(pCode *pc)
5900 PCI(pc)->num_ops == 0 ||
5901 (PCI(pc)->num_ops == 1)) // accept only 2 operand commands
5906 fprintf(stderr, "pic16_getRegFromInstruction2 - reg type %s (%d)\n",
5907 dumpPicOptype( PCI(pc)->pcop->type), PCI(pc)->pcop->type);
5910 return pic16_getRegFrompCodeOp (PCOR2(PCI(pc)->pcop)->pcop2);
5913 /*-----------------------------------------------------------------*/
5914 /*-----------------------------------------------------------------*/
5916 static void AnalyzepBlock(pBlock *pb)
5923 /* Find all of the registers used in this pBlock
5924 * by looking at each instruction and examining it's
5927 for(pc = pb->pcHead; pc; pc = pc->next) {
5929 /* Is this an instruction with operands? */
5930 if(pc->type == PC_OPCODE && PCI(pc)->pcop) {
5932 if(PCI(pc)->pcop->type == PO_GPR_TEMP) {
5934 /* Loop through all of the registers declared so far in
5935 this block and see if we find this one there */
5937 regs *r = setFirstItem(pb->tregisters);
5940 if(r->rIdx == PCOR(PCI(pc)->pcop)->r->rIdx) {
5941 PCOR(PCI(pc)->pcop)->r = r;
5944 r = setNextItem(pb->tregisters);
5948 /* register wasn't found */
5949 //r = Safe_calloc(1, sizeof(regs));
5950 //memcpy(r,PCOR(PCI(pc)->pcop)->r, sizeof(regs));
5951 //addSet(&pb->tregisters, r);
5952 addSet(&pb->tregisters, PCOR(PCI(pc)->pcop)->r);
5953 //PCOR(PCI(pc)->pcop)->r = r;
5954 //fprintf(stderr,"added register to pblock: reg %d\n",r->rIdx);
5956 fprintf(stderr,"found register in pblock: reg %d\n",r->rIdx);
5959 if(PCI(pc)->pcop->type == PO_GPR_REGISTER) {
5960 if(PCOR(PCI(pc)->pcop)->r) {
5961 pic16_allocWithIdx(PCOR(PCI(pc)->pcop)->r->rIdx); /* FIXME! - VR */
5962 DFPRINTF((stderr,"found register in pblock: reg 0x%x\n",PCOR(PCI(pc)->pcop)->r->rIdx));
5964 if(PCI(pc)->pcop->name)
5965 fprintf(stderr,"ERROR: %s is a NULL register\n",PCI(pc)->pcop->name );
5967 fprintf(stderr,"ERROR: NULL register\n");
5976 /*-----------------------------------------------------------------*/
5978 /*-----------------------------------------------------------------*/
5979 #define PCI_HAS_LABEL(x) ((x) && (PCI(x)->label != NULL))
5981 static void InsertpFlow(pCode *pc, pCode **pflow)
5984 PCFL(*pflow)->end = pc;
5986 if(!pc || !pc->next)
5989 *pflow = pic16_newpCodeFlow();
5990 pic16_pCodeInsertAfter(pc, *pflow);
5993 /*-----------------------------------------------------------------*/
5994 /* pic16_BuildFlow(pBlock *pb) - examine the code in a pBlock and build */
5995 /* the flow blocks. */
5997 * pic16_BuildFlow inserts pCodeFlow objects into the pCode chain at each
5998 * point the instruction flow changes.
6000 /*-----------------------------------------------------------------*/
6001 void pic16_BuildFlow(pBlock *pb)
6004 pCode *last_pci=NULL;
6011 //fprintf (stderr,"build flow start seq %d ",GpcFlowSeq);
6012 /* Insert a pCodeFlow object at the beginning of a pBlock */
6014 InsertpFlow(pb->pcHead, &pflow);
6016 //pflow = pic16_newpCodeFlow(); /* Create a new Flow object */
6017 //pflow->next = pb->pcHead; /* Make the current head the next object */
6018 //pb->pcHead->prev = pflow; /* let the current head point back to the flow object */
6019 //pb->pcHead = pflow; /* Make the Flow object the head */
6022 for( pc = pic16_findNextInstruction(pb->pcHead);
6024 pc=pic16_findNextInstruction(pc)) {
6027 PCI(pc)->pcflow = PCFL(pflow);
6029 //fprintf(stderr," build: ");
6030 //pflow->print(stderr,pflow);
6032 if (checkLabel(pc)) {
6034 /* This instruction marks the beginning of a
6035 * new flow segment */
6040 /* If the previous pCode is not a flow object, then
6041 * insert a new flow object. (This check prevents
6042 * two consecutive flow objects from being insert in
6043 * the case where a skip instruction preceeds an
6044 * instruction containing a label.) */
6046 if(last_pci && (PCI(last_pci)->pcflow == PCFL(pflow)))
6047 InsertpFlow(pic16_findPrevInstruction(pc->prev), &pflow);
6049 PCI(pc)->pcflow = PCFL(pflow);
6053 if( PCI(pc)->isSkip) {
6055 /* The two instructions immediately following this one
6056 * mark the beginning of a new flow segment */
6058 while(pc && PCI(pc)->isSkip) {
6060 PCI(pc)->pcflow = PCFL(pflow);
6064 InsertpFlow(pc, &pflow);
6065 pc=pic16_findNextInstruction(pc->next);
6073 PCI(pc)->pcflow = PCFL(pflow);
6075 InsertpFlow(pc, &pflow);
6077 } else if ( PCI(pc)->isBranch && !checkLabel(pic16_findNextInstruction(pc->next))) {
6079 InsertpFlow(pc, &pflow);
6087 //fprintf (stderr,",end seq %d",GpcFlowSeq);
6089 PCFL(pflow)->end = pb->pcTail;
6092 /*-------------------------------------------------------------------*/
6093 /* unBuildFlow(pBlock *pb) - examine the code in a pBlock and build */
6094 /* the flow blocks. */
6096 * unBuildFlow removes pCodeFlow objects from a pCode chain
6098 /*-----------------------------------------------------------------*/
6099 static void unBuildFlow(pBlock *pb)
6114 if(PCI(pc)->pcflow) {
6115 //Safe_free(PCI(pc)->pcflow);
6116 PCI(pc)->pcflow = NULL;
6119 } else if(isPCFL(pc) )
6128 /*-----------------------------------------------------------------*/
6129 /*-----------------------------------------------------------------*/
6130 static void dumpCond(int cond)
6133 static char *pcc_str[] = {
6147 int ncond = sizeof(pcc_str) / sizeof(char *);
6150 fprintf(stderr, "0x%04X\n",cond);
6152 for(i=0,j=1; i<ncond; i++, j<<=1)
6154 fprintf(stderr, " %s\n",pcc_str[i]);
6160 /*-----------------------------------------------------------------*/
6161 /*-----------------------------------------------------------------*/
6162 static void FlowStats(pCodeFlow *pcflow)
6170 fprintf(stderr, " FlowStats - flow block (seq=%d)\n", pcflow->pc.seq);
6172 pc = pic16_findNextpCode(PCODE(pcflow), PC_OPCODE);
6175 fprintf(stderr, " FlowStats - empty flow (seq=%d)\n", pcflow->pc.seq);
6180 fprintf(stderr, " FlowStats inCond: ");
6181 dumpCond(pcflow->inCond);
6182 fprintf(stderr, " FlowStats outCond: ");
6183 dumpCond(pcflow->outCond);
6187 /*-----------------------------------------------------------------*
6188 * int isBankInstruction(pCode *pc) - examine the pCode *pc to determine
6189 * if it affects the banking bits.
6191 * return: -1 == Banking bits are unaffected by this pCode.
6193 * return: > 0 == Banking bits are affected.
6195 * If the banking bits are affected, then the returned value describes
6196 * which bits are affected and how they're affected. The lower half
6197 * of the integer maps to the bits that are affected, the upper half
6198 * to whether they're set or cleared.
6200 *-----------------------------------------------------------------*/
6202 static int isBankInstruction(pCode *pc)
6210 if( PCI(pc)->op == POC_MOVLB ||
6211 (( (reg = pic16_getRegFromInstruction(pc)) != NULL) && isBSR_REG(reg))) {
6212 bank = PCOL(pc)->lit;
6219 /*-----------------------------------------------------------------*/
6220 /*-----------------------------------------------------------------*/
6221 static void FillFlow(pCodeFlow *pcflow)
6230 // fprintf(stderr, " FillFlow - flow block (seq=%d)\n", pcflow->pc.seq);
6232 pc = pic16_findNextpCode(PCODE(pcflow), PC_OPCODE);
6235 //fprintf(stderr, " FillFlow - empty flow (seq=%d)\n", pcflow->pc.seq);
6242 isBankInstruction(pc);
6244 } while (pc && (pc != pcflow->end) && !isPCFL(pc));
6248 fprintf(stderr, " FillFlow - Bad end of flow\n");
6250 fprintf(stderr, " FillFlow - Ending flow with\n ");
6251 pc->print(stderr,pc);
6254 fprintf(stderr, " FillFlow inCond: ");
6255 dumpCond(pcflow->inCond);
6256 fprintf(stderr, " FillFlow outCond: ");
6257 dumpCond(pcflow->outCond);
6261 /*-----------------------------------------------------------------*/
6262 /*-----------------------------------------------------------------*/
6263 static void LinkFlow_pCode(pCodeInstruction *from, pCodeInstruction *to)
6265 pCodeFlowLink *fromLink, *toLink;
6267 if(!from || !to || !to->pcflow || !from->pcflow)
6270 fromLink = pic16_newpCodeFlowLink(from->pcflow);
6271 toLink = pic16_newpCodeFlowLink(to->pcflow);
6273 addSetIfnotP(&(from->pcflow->to), toLink); //to->pcflow);
6274 addSetIfnotP(&(to->pcflow->from), fromLink); //from->pcflow);
6278 pCode *pic16_getJumptabpCode (pCode *pc) {
6281 //fprintf (stderr, "%s - start for %p in %p", __FUNCTION__, pc, isPCI(pc) ? PCI(pc)->pcflow : NULL);
6282 //pc->print (stderr, pc);
6285 if (isPCI(pcinf) && PCI(pcinf)->op != POC_GOTO) return NULL;
6286 if (pcinf->type == PC_INFO && PCINF(pcinf)->type == INF_OPTIMIZATION) {
6287 switch (PCOO(PCINF(pcinf)->oper1)->type) {
6288 case OPT_JUMPTABLE_BEGIN:
6289 /* leading begin of jump table -- in one */
6290 pcinf = pic16_findPrevInstruction (pcinf);
6294 case OPT_JUMPTABLE_END:
6295 /* leading end of jumptable -- not in one */
6300 /* ignore all other PCInfos */
6304 pcinf = pcinf->prev;
6307 /* no PCInfo found -- not in a jumptable */
6311 /*-----------------------------------------------------------------*
6312 * void LinkFlow(pBlock *pb)
6314 * In pic16_BuildFlow, the PIC code has been partitioned into contiguous
6315 * non-branching segments. In LinkFlow, we determine the execution
6316 * order of these segments. For example, if one of the segments ends
6317 * with a skip, then we know that there are two possible flow segments
6318 * to which control may be passed.
6319 *-----------------------------------------------------------------*/
6320 static void LinkFlow(pBlock *pb)
6325 pCode *jumptab_pre = NULL;
6327 //fprintf(stderr,"linkflow \n");
6329 for( pcflow = pic16_findNextpCode(pb->pcHead, PC_FLOW);
6331 pcflow = pic16_findNextpCode(pcflow->next, PC_FLOW) ) {
6334 fprintf(stderr, "LinkFlow - pcflow is not a flow object ");
6336 //fprintf(stderr," link: ");
6337 //pcflow->print(stderr,pcflow);
6339 //FillFlow(PCFL(pcflow));
6341 pc = PCFL(pcflow)->end;
6343 //fprintf(stderr, "LinkFlow - flow block (seq=%d) ", pcflow->seq);
6344 if(isPCI_SKIP(pc)) {
6345 // fprintf(stderr, "ends with skip\n");
6346 // pc->print(stderr,pc);
6348 pct=pic16_findNextInstruction(pc->next);
6349 LinkFlow_pCode(PCI(pc),PCI(pct));
6350 pct=pic16_findNextInstruction(pct->next);
6351 LinkFlow_pCode(PCI(pc),PCI(pct));
6355 if(isPCI_BRANCH(pc)) {
6356 pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
6358 /* handle GOTOs in jumptables */
6359 if ((jumptab_pre = pic16_getJumptabpCode (pc)) != NULL) {
6360 /* link to previous flow */
6361 //fprintf (stderr, "linked jumptable GOTO to predecessor %p\n", PCI(jumptab_pre)->pcflow);
6362 LinkFlow_pCode (PCI(jumptab_pre), PCI(pc));
6365 switch (PCI(pc)->op) {
6371 /* unconditional branches -- do not link to next instruction */
6372 //fprintf (stderr, "%s: flow ended by unconditional branch\n", __FUNCTION__);
6377 /* unconditional calls -- link to next instruction */
6378 //fprintf (stderr, "%s: flow ended by CALL\n", __FUNCTION__);
6379 LinkFlow_pCode(PCI(pc),PCI(pic16_findNextInstruction(pc->next)));
6390 /* conditional branches -- also link to next instruction */
6391 //fprintf (stderr, "%s: flow ended by conditional branch\n", __FUNCTION__);
6392 LinkFlow_pCode(PCI(pc),PCI(pic16_findNextInstruction(pc->next)));
6396 fprintf (stderr, "%s: unhandled op %u (%s)\n", __FUNCTION__, PCI(pc)->op , PCI(pc)->mnemonic);
6397 assert (0 && "unhandled branching instruction");
6401 //fprintf(stderr, "ends with branch\n ");
6402 //pc->print(stderr,pc);
6404 if(!(pcol && isPCOLAB(pcol))) {
6405 if((PCI(pc)->op != POC_RETLW)
6406 && (PCI(pc)->op != POC_RETURN) && (PCI(pc)->op != POC_CALL) && (PCI(pc)->op != POC_RCALL) && (PCI(pc)->op != POC_RETFIE) ) {
6408 /* continue if label is '$' which assembler knows how to parse */
6409 if(((PCI(pc)->pcop->type == PO_STR) && !strcmp(PCI(pc)->pcop->name, "$")))continue;
6411 if(pic16_pcode_verbose) {
6412 pc->print(stderr,pc);
6413 fprintf(stderr, "ERROR: %s, branch instruction doesn't have label\n",__FUNCTION__);
6419 if( (pct = findLabelinpBlock(pb,pcol)) != NULL)
6420 LinkFlow_pCode(PCI(pc),PCI(pct));
6422 fprintf(stderr, "ERROR: %s, couldn't find label. key=%d,lab=%s\n",
6423 __FUNCTION__,pcol->key,((PCOP(pcol)->name)?PCOP(pcol)->name:"-"));
6425 // fprintf(stderr,"pic16_newpCodeOpLabel: key=%d, name=%s\n",pcol->key,(PCOP(pcol)->name)?(PCOP(pcol)->name):"<unknown>");
6431 //fprintf(stderr, "ends with non-branching instruction:\n");
6432 //pc->print(stderr,pc);
6434 LinkFlow_pCode(PCI(pc),PCI(pic16_findNextInstruction(pc->next)));
6440 //fprintf(stderr, "ends with unknown\n");
6441 //pc->print(stderr,pc);
6445 //fprintf(stderr, "ends with nothing: ERROR\n");
6449 /*-----------------------------------------------------------------*/
6450 /*-----------------------------------------------------------------*/
6452 /*-----------------------------------------------------------------*/
6453 /*-----------------------------------------------------------------*/
6454 int pic16_isPCinFlow(pCode *pc, pCode *pcflow)
6460 if((!isPCI(pc) && !isPCAD(pc)) || !PCI(pc)->pcflow || !isPCFL(pcflow) )
6463 if( PCI(pc)->pcflow->pc.seq == pcflow->seq)
6473 /*-----------------------------------------------------------------*/
6474 /* insertBankSwitch - inserts a bank switch statement in the */
6475 /* assembly listing */
6477 /* position == 0: insert before */
6478 /* position == 1: insert after pc */
6479 /* position == 2: like 0 but previous was a skip instruction */
6480 /*-----------------------------------------------------------------*/
6481 pCodeOp *pic16_popGetLabel(unsigned int key);
6482 extern int pic16_labelOffset;
6484 static void insertBankSwitch(unsigned char position, pCode *pc)
6491 /* emit BANKSEL [symbol] */
6494 new_pc = pic16_newpCodeAsmDir("BANKSEL", "%s", pic16_get_op_from_instruction(PCI(pc)));
6496 // position = 0; // position is always before (sanity check!)
6499 fprintf(stderr, "%s:%d: inserting bank switch (pos: %d)\n", __FUNCTION__, __LINE__, position);
6500 pc->print(stderr, pc);
6505 /* insert the bank switch after this pc instruction */
6506 pCode *pcnext = pic16_findNextInstruction(pc);
6508 pic16_pCodeInsertAfter(pc, new_pc);
6509 if(pcnext)pc = pcnext;
6513 /* insert the bank switch BEFORE this pc instruction */
6514 pic16_pCodeInsertAfter(pc->prev, new_pc);
6519 pCode *pcnext, *pcprev, *npci, *ppc;
6521 int ofs1=0, ofs2=0, len=0;
6523 /* just like 0, but previous was a skip instruction,
6524 * so some care should be taken */
6526 pic16_labelOffset += 10000;
6527 tlbl = newiTempLabel(NULL);
6529 /* invert skip instruction */
6530 pcprev = pic16_findPrevInstruction(pc->prev);
6531 ipci = PCI(pcprev)->inverted_op;
6532 npci = pic16_newpCode(ipci, PCI(pcprev)->pcop);
6534 // fprintf(stderr, "%s:%d old OP: %d\tnew OP: %d\n", __FILE__, __LINE__, PCI(pcprev)->op, ipci);
6536 /* copy info from old pCode */
6537 ofs1 = ofs2 = sizeof( pCode ) + sizeof(PIC_OPCODE);
6538 len = sizeof(pCodeInstruction) - ofs1 - sizeof( char const * const *);
6539 ofs1 += strlen( PCI(pcprev)->mnemonic) + 1;
6540 ofs2 += strlen( PCI(npci)->mnemonic) + 1;
6541 memcpy(&PCI(npci)->from, &PCI(pcprev)->from, (char *)(&(PCI(npci)->pci_magic)) - (char *)(&(PCI(npci)->from)));
6542 PCI(npci)->op = PCI(pcprev)->inverted_op;
6544 /* unlink old pCode */
6546 ppc->next = pcprev->next;
6547 pcprev->next->prev = ppc;
6548 pic16_pCodeInsertAfter(ppc, npci);
6550 /* extra instructions to handle invertion */
6551 pcnext = pic16_newpCode(POC_BRA, pic16_popGetLabel(tlbl->key));
6552 pic16_pCodeInsertAfter(npci, pcnext);
6553 pic16_pCodeInsertAfter(pc->prev, new_pc);
6555 pcnext = pic16_newpCodeLabel(NULL,tlbl->key+100+pic16_labelOffset);
6556 pic16_pCodeInsertAfter(pc, pcnext);
6561 /* Move the label, if there is one */
6562 if(PCI(pc)->label) {
6563 // fprintf(stderr, "%s:%d: moving label due to bank switch directive src= 0x%p dst= 0x%p\n",
6564 // __FILE__, __LINE__, pc, new_pc);
6565 PCAD(new_pc)->pci.label = PCI(pc)->label;
6566 PCI(pc)->label = NULL;
6571 /*-----------------------------------------------------------------*/
6572 /*int compareBankFlow - compare the banking requirements between */
6574 /*-----------------------------------------------------------------*/
6575 static int compareBankFlow(pCodeFlow *pcflow, pCodeFlowLink *pcflowLink, int toORfrom)
6578 if(!pcflow || !pcflowLink || !pcflowLink->pcflow)
6581 if(!isPCFL(pcflow) || !isPCFL(pcflowLink->pcflow))
6584 if(pcflow->firstBank == -1)
6588 if(pcflowLink->pcflow->firstBank == -1) {
6589 pCodeFlowLink *pctl = setFirstItem( toORfrom ?
6590 pcflowLink->pcflow->to :
6591 pcflowLink->pcflow->from);
6592 return compareBankFlow(pcflow, pctl, toORfrom);
6596 if(pcflow->lastBank == pcflowLink->pcflow->firstBank)
6599 pcflowLink->bank_conflict++;
6600 pcflowLink->pcflow->FromConflicts++;
6601 pcflow->ToConflicts++;
6604 if(pcflow->firstBank == pcflowLink->pcflow->lastBank)
6607 pcflowLink->bank_conflict++;
6608 pcflowLink->pcflow->ToConflicts++;
6609 pcflow->FromConflicts++;
6613 fprintf(stderr,"compare flow found conflict: seq %d from conflicts %d, to conflicts %d\n",
6614 pcflowLink->pcflow->pc.seq,
6615 pcflowLink->pcflow->FromConflicts,
6616 pcflowLink->pcflow->ToConflicts);
6623 /*-----------------------------------------------------------------*/
6624 /*-----------------------------------------------------------------*/
6625 static void DumpFlow(pBlock *pb)
6629 pCodeFlowLink *pcfl;
6632 fprintf(stderr,"Dump flow \n");
6633 pb->pcHead->print(stderr, pb->pcHead);
6635 pcflow = pic16_findNextpCode(pb->pcHead, PC_FLOW);
6636 pcflow->print(stderr,pcflow);
6638 for( pcflow = pic16_findNextpCode(pb->pcHead, PC_FLOW);
6640 pcflow = pic16_findNextpCode(pcflow->next, PC_FLOW) ) {
6642 if(!isPCFL(pcflow)) {
6643 fprintf(stderr, "DumpFlow - pcflow is not a flow object ");
6646 fprintf(stderr,"dumping: ");
6647 pcflow->print(stderr,pcflow);
6648 FlowStats(PCFL(pcflow));
6650 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
6652 pc = PCODE(pcfl->pcflow);
6654 fprintf(stderr, " from seq %d:\n",pc->seq);
6656 fprintf(stderr,"oops dumpflow - from is not a pcflow\n");
6657 pc->print(stderr,pc);
6662 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
6664 pc = PCODE(pcfl->pcflow);
6666 fprintf(stderr, " to seq %d:\n",pc->seq);
6668 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
6669 pc->print(stderr,pc);
6678 /*-----------------------------------------------------------------*/
6679 /*-----------------------------------------------------------------*/
6680 static int OptimizepBlock(pBlock *pb)
6685 if(!pb || !peepOptimizing)
6688 DFPRINTF((stderr," Optimizing pBlock: %c\n",getpBlock_dbName(pb)));
6690 for(pc = pb->pcHead; pc; pc = pc->next)
6691 matches += pic16_pCodePeepMatchRule(pc);
6694 pc = pic16_findNextInstruction(pb->pcHead);
6702 if(pic16_pCodePeepMatchRule(pc)) {
6707 pc = pic16_findNextInstruction(pcprev->next);
6709 pc = pic16_findNextInstruction(pb->pcHead);
6711 pc = pic16_findNextInstruction(pc->next);
6715 DFPRINTF((stderr," Optimizing pBlock: %c - matches=%d\n",getpBlock_dbName(pb),matches));
6720 /*-----------------------------------------------------------------*/
6721 /*-----------------------------------------------------------------*/
6722 static pCode * findInstructionUsingLabel(pCodeLabel *pcl, pCode *pcs)
6726 for(pc = pcs; pc; pc = pc->next) {
6728 if(((pc->type == PC_OPCODE) || (pc->type == PC_INLINE) || (pc->type == PC_ASMDIR)) &&
6730 (PCI(pc)->pcop->type == PO_LABEL) &&
6731 (PCOLAB(PCI(pc)->pcop)->key == pcl->key))
6739 /*-----------------------------------------------------------------*/
6740 /*-----------------------------------------------------------------*/
6741 static void exchangeLabels(pCodeLabel *pcl, pCode *pc)
6748 (PCI(pc)->pcop->type == PO_LABEL)) {
6750 pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
6752 // fprintf(stderr,"changing label key from %d to %d\n",pcol->key, pcl->key);
6753 // if(pcol->pcop.name)
6754 // Safe_free(pcol->pcop.name);
6756 /* If the key is negative, then we (probably) have a label to
6757 * a function and the name is already defined */
6760 sprintf(s=buffer,"_%05d_DS_",pcl->key);
6764 //sprintf(buffer,"_%05d_DS_",pcl->key);
6766 fprintf(stderr, "ERROR %s:%d function label is null\n",__FUNCTION__,__LINE__);
6768 pcol->pcop.name = Safe_strdup(s);
6769 pcol->key = pcl->key;
6770 //pc->print(stderr,pc);
6777 /*-----------------------------------------------------------------*/
6778 /* pBlockRemoveUnusedLabels - remove the pCode labels from the */
6779 /* pCode chain if they're not used. */
6780 /*-----------------------------------------------------------------*/
6781 static void pBlockRemoveUnusedLabels(pBlock *pb)
6783 pCode *pc; pCodeLabel *pcl;
6788 for(pc = pb->pcHead; (pc=pic16_findNextInstruction(pc->next)) != NULL; ) {
6790 pBranch *pbr = PCI(pc)->label;
6791 if(pbr && pbr->next) {
6792 pCode *pcd = pb->pcHead;
6794 // fprintf(stderr, "multiple labels\n");
6795 // pc->print(stderr,pc);
6800 while ( (pcd = findInstructionUsingLabel(PCL(PCI(pc)->label->pc), pcd)) != NULL) {
6801 //fprintf(stderr,"Used by:\n");
6802 //pcd->print(stderr,pcd);
6804 exchangeLabels(PCL(pbr->pc),pcd);
6813 for(pc = pb->pcHead; pc; pc = pc->next) {
6815 if(isPCL(pc)) // pc->type == PC_LABEL)
6817 else if (isPCI(pc) && PCI(pc)->label) //((pc->type == PC_OPCODE) && PCI(pc)->label)
6818 pcl = PCL(PCI(pc)->label->pc);
6821 // fprintf(stderr," found A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
6823 /* This pCode is a label, so search the pBlock to see if anyone
6826 if( (pcl->key>0) && (!findInstructionUsingLabel(pcl, pb->pcHead))
6828 //if( !findInstructionUsingLabel(pcl, pb->pcHead)) {
6829 /* Couldn't find an instruction that refers to this label
6830 * So, unlink the pCode label from it's pCode chain
6831 * and destroy the label */
6832 // fprintf(stderr," removed A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
6834 DFPRINTF((stderr," !!! REMOVED A LABEL !!! key = %d, %s\n", pcl->key,pcl->label));
6835 if(pc->type == PC_LABEL) {
6836 pic16_unlinkpCode(pc);
6837 pCodeLabelDestruct(pc);
6839 unlinkpCodeFromBranch(pc, PCODE(pcl));
6840 /*if(pc->label->next == NULL && pc->label->pc == NULL) {
6841 Safe_free(pc->label);
6851 /*-----------------------------------------------------------------*/
6852 /* pic16_pBlockMergeLabels - remove the pCode labels from the pCode */
6853 /* chain and put them into pBranches that are */
6854 /* associated with the appropriate pCode */
6856 /*-----------------------------------------------------------------*/
6857 void pic16_pBlockMergeLabels(pBlock *pb)
6860 pCode *pc, *pcnext=NULL;
6865 /* First, Try to remove any unused labels */
6866 //pBlockRemoveUnusedLabels(pb);
6868 /* Now loop through the pBlock and merge the labels with the opcodes */
6871 // for(pc = pb->pcHead; pc; pc = pc->next) {
6874 pCode *pcn = pc->next;
6876 if(pc->type == PC_LABEL) {
6878 // fprintf(stderr," checking merging label %s\n",PCL(pc)->label);
6879 // fprintf(stderr,"Checking label key = %d\n",PCL(pc)->key);
6881 if((pcnext = pic16_findNextInstruction(pc) )) {
6883 // pcnext->print(stderr, pcnext);
6885 // Unlink the pCode label from it's pCode chain
6886 pic16_unlinkpCode(pc);
6888 // fprintf(stderr,"Merged label key = %d\n",PCL(pc)->key);
6889 // And link it into the instruction's pBranch labels. (Note, since
6890 // it's possible to have multiple labels associated with one instruction
6891 // we must provide a means to accomodate the additional labels. Thus
6892 // the labels are placed into the singly-linked list "label" as
6893 // opposed to being a single member of the pCodeInstruction.)
6895 //_ALLOC(pbr,sizeof(pBranch));
6897 pbr = Safe_calloc(1,sizeof(pBranch));
6901 PCI(pcnext)->label = pic16_pBranchAppend(PCI(pcnext)->label,pbr);
6904 if(pic16_pcode_verbose)
6905 fprintf(stderr, "WARNING: couldn't associate label %s with an instruction\n",PCL(pc)->label);
6907 } else if(pc->type == PC_CSOURCE) {
6909 /* merge the source line symbolic info into the next instruction */
6910 if((pcnext = pic16_findNextInstruction(pc) )) {
6912 // Unlink the pCode label from it's pCode chain
6913 pic16_unlinkpCode(pc);
6914 PCI(pcnext)->cline = PCCS(pc);
6915 //fprintf(stderr, "merging CSRC\n");
6916 //genericPrint(stderr,pcnext);
6922 pBlockRemoveUnusedLabels(pb);
6926 /*-----------------------------------------------------------------*/
6927 /*-----------------------------------------------------------------*/
6928 static int OptimizepCode(char dbName)
6930 #define MAX_PASSES 4
6939 DFPRINTF((stderr," Optimizing pCode\n"));
6943 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6944 if('*' == dbName || getpBlock_dbName(pb) == dbName)
6945 matches += OptimizepBlock(pb);
6948 while(matches && ++passes < MAX_PASSES);
6955 const char *pic16_pCodeOpType(pCodeOp *pcop);
6956 const char *pic16_pCodeOpSubType(pCodeOp *pcop);
6959 /*-----------------------------------------------------------------*/
6960 /* pic16_popCopyGPR2Bit - copy a pcode operator */
6961 /*-----------------------------------------------------------------*/
6963 pCodeOp *pic16_popCopyGPR2Bit(pCodeOp *pc, int bitval)
6967 // fprintf(stderr, "%s:%d pc type: %s\tname: %s\n", __FILE__, __LINE__, pic16_pCodeOpType(pc), pc->name);
6970 pcop = pic16_newpCodeOpBit(pc->name, bitval, 0, pc->type);
6972 if(PCOR(pc)->r)pcop = pic16_newpCodeOpBit(PCOR(pc)->r->name, bitval, 0, pc->type);
6975 assert(pcop != NULL);
6977 if( !( (pcop->type == PO_LABEL) ||
6978 (pcop->type == PO_LITERAL) ||
6979 (pcop->type == PO_STR) ))
6980 PCOR(pcop)->r = PCOR(pc)->r; /* This is dangerous... */
6981 PCOR(pcop)->r->wasUsed = 1;
6982 PCOR(pcop)->instance = PCOR(pc)->instance;
6988 /*----------------------------------------------------------------------*
6989 * pic16_areRegsSame - check to see if the names of two registers match *
6990 *----------------------------------------------------------------------*/
6991 int pic16_areRegsSame(regs *r1, regs *r2)
6993 if(!strcmp(r1->name, r2->name))return 1;
6999 /*-----------------------------------------------------------------*/
7000 /*-----------------------------------------------------------------*/
7001 static void pic16_FixRegisterBanking(pBlock *pb)
7005 regs *reg, *prevreg;
7006 unsigned char flag=0;
7011 pc = pic16_findNextpCode(pb->pcHead, PC_OPCODE);
7014 /* loop through all of the flow blocks with in one pblock */
7016 // fprintf(stderr,"%s:%d: Register banking\n", __FUNCTION__, __LINE__);
7020 /* at this point, pc should point to a PC_FLOW object */
7021 /* for each flow block, determine the register banking
7025 /* if label, then might come from other point, force banksel */
7026 if(isPCL(pc))prevreg = NULL;
7028 if(!isPCI(pc))goto loop;
7030 if(PCI(pc)->label)prevreg = NULL;
7032 if(PCI(pc)->is2MemOp)goto loop;
7034 /* if goto, then force banksel */
7035 // if(PCI(pc)->op == POC_GOTO)prevreg = NULL;
7037 reg = pic16_getRegFromInstruction(pc);
7040 pc->print(stderr, pc);
7041 fprintf(stderr, "reg = %p\n", reg);
7044 fprintf(stderr, "%s:%d: %s %d\n",__FUNCTION__, __LINE__, reg->name, reg->rIdx);
7045 fprintf(stderr, "addr = 0x%03x, bit=%d\tfix=%d\n",
7046 reg->address,reg->isBitField, reg->isFixed);
7050 /* now make some tests to make sure that instruction needs bank switch */
7052 /* if no register exists, and if not a bit opcode goto loop */
7054 if(!(PCI(pc)->pcop && PCI(pc)->pcop->type == PO_GPR_BIT))goto loop;
7057 if(isPCI_SKIP(pc)) {
7058 // fprintf(stderr, "instruction is SKIP instruction\n");
7061 if(reg && isACCESS_BANK(reg))goto loop;
7063 if(!isBankInstruction(pc))goto loop;
7065 if(isPCI_LIT(pc))goto loop;
7067 if(PCI(pc)->op == POC_CALL)goto loop;
7069 /* Examine the instruction before this one to make sure it is
7070 * not a skip type instruction */
7071 pcprev = findPrevpCode(pc->prev, PC_OPCODE);
7073 flag = 0; /* add before this instruction */
7075 /* if previous instruction is a skip one, then set flag
7076 * to 2 and call insertBankSwitch */
7077 if(pcprev && isPCI_SKIP(pcprev)) {
7082 if(pic16_options.opt_banksel>0) {
7083 char op1[128], op2[128];
7086 strcpy(op1, pic16_get_op_from_instruction(PCI(pc)));
7087 strcpy(op2, pic16_get_op_from_instruction(PCI(pcprev)));
7088 if(!strcmp(op1, op2))goto loop;
7092 insertBankSwitch(flag, pc);
7094 // fprintf(stderr, "BANK SWITCH inserted\n");
7102 /** ADDITIONS BY RAPHAEL NEIDER, 2004-11-16: GOTO OPTIMIZATIONS **/
7104 /* Returns the (maximum of the) number of bytes used by the specified pCode. */
7105 int instrSize (pCode *pc)
7110 if (!PCAD(pc)->directive || strlen (PCAD(pc)->directive) < 3) return 0;
7111 return 4; // assumes only regular instructions using <= 4 bytes
7114 if (isPCI(pc)) return PCI(pc)->isize;
7119 /* Returns 1 if pc is referenced by the given label (either
7120 * pc is the label itself or is an instruction with an attached
7122 * Returns 0 if pc is not preceeded by the specified label.
7124 int isLabel (pCode *pc, char *label)
7128 // label attached to the pCode?
7129 if (isPCI(pc) || isPCAD(pc) || isPCW(pc) || pc->type == PC_INFO) {
7130 pBranch *lab = NULL;
7131 lab = PCI(pc)->label;
7134 if (isPCL(lab->pc) && strcmp(PCL(lab->pc)->label, label) == 0) {
7141 // is inline assembly label?
7142 if (isPCAD(pc) && PCAD(pc)->directive == NULL && PCAD(pc)->arg) {
7143 // do not compare trailing ':'
7144 if (strncmp (PCAD(pc)->arg, label, strlen (label)) == 0) {
7151 if (strcmp(PCL(pc)->label,label) == 0) {
7156 // no label/no label attached/wrong label(s)
7160 /* Returns the distance to the given label in terms of words.
7161 * Labels are searched only within -max .. max words from pc.
7162 * Returns max if the label could not be found or
7163 * its distance from pc in (-max..+max).
7165 int findpCodeLabel (pCode *pc, char *label, int max, pCode **target) {
7166 int dist = instrSize(pc);
7170 while (dist < max && curr && !isLabel (curr, label)) {
7172 dist += instrSize(curr); // sizeof (instruction)
7174 if (curr && dist < max) {
7175 if (target != NULL) *target = curr;
7180 curr = pic16_findNextInstruction (pc->next);
7182 while (dist < max && curr && !isLabel (curr, label)) {
7183 dist += instrSize(curr); // sizeof (instruction)
7186 if (curr && dist < max) {
7187 if (target != NULL) *target = curr;
7191 if (target != NULL) *target = NULL;
7195 /* Returns -1 if pc does NOT denote an instruction like
7197 * Otherwise we return
7198 * (a) 0x10 + i for BTFSS
7199 * (b) 0x00 + i for BTFSC
7201 int isSkipOnStatus (pCode *pc)
7205 if (!pc || !isPCI(pc)) return -1;
7206 if (PCI(pc)->op == POC_BTFSS) res = 0x10;
7207 else if (PCI(pc)->op == POC_BTFSC) res = 0x00;
7210 pcop = PCI(pc)->pcop;
7212 if (pcop->type == PO_STATUS || (pcop->type == PO_GPR_BIT && strcmp(pcop->name, "STATUS") == 0)) {
7213 return res + ((pCodeOpRegBit *)pcop)->bit;
7219 /* Returns 1 if pc is one of BC, BZ, BOV, BN, BNC, BNZ, BNOV or BNN,
7220 * returns 0 otherwise. */
7221 int isConditionalBranch (pCode *pc)
7223 if (!pc || !isPCI_BRANCH(pc)) return 0;
7225 switch (PCI(pc)->op) {
7243 /* Returns 1 if pc has a label attached to it.
7244 * This can be either a label stored in the pCode itself (.label)
7245 * or a label making up its own pCode preceding this pc.
7246 * Returns 0 if pc cannot be reached directly via a label.
7248 int hasNoLabel (pCode *pc)
7253 // are there any label pCodes between pc and the previous instruction?
7254 prev = pic16_findPrevInstruction (pc->prev);
7255 while (pc && pc != prev) {
7256 // pCode with attached label?
7257 if ((isPCI(pc) || isPCAD(pc) || isPCW(pc) || pc->type == PC_INFO)
7258 && PCI(pc)->label) {
7261 // is inline assembly label?
7262 if (isPCAD(pc) && PCAD(pc)->directive == NULL) return 0;
7263 if (isPCW(pc) && PCW(pc)->label) return 0;
7266 if (isPCL(pc)) return 0;
7275 static void pic16_InsertCommentAfter (pCode *pc, const char *fmt, ...) {
7280 vsprintf (buf, fmt, va);
7283 pic16_pCodeInsertAfter (pc, pic16_newpCodeCharP(buf));
7286 /* Replaces the old pCode with the new one, moving the labels,
7287 * C source line and probably flow information to the new pCode.
7289 void pic16_pCodeReplace (pCode *oldPC, pCode *newPC) {
7290 if (!oldPC || !newPC || !isPCI(oldPC) || !isPCI(newPC))
7293 /* first move all labels from old to new */
7294 PCI(newPC)->label = pic16_pBranchAppend (PCI(oldPC)->label, PCI(newPC)->label);
7295 PCI(oldPC)->label = NULL;
7298 /* move C source line (if possible) */
7299 if (PCI(oldPC)->cline && !PCI(newPC)->cline)
7300 PCI(newPC)->cline = PCI(oldPC)->cline;
7303 /* keep flow information intact */
7304 newPC->seq = oldPC->seq;
7305 PCI(newPC)->pcflow = PCI(oldPC)->pcflow;
7306 if (PCI(newPC)->pcflow && PCI(newPC)->pcflow->end == oldPC) {
7307 PCI(newPC)->pcflow->end = newPC;
7310 /* insert a comment stating which pCode has been replaced */
7312 if (pic16_pcode_verbose || pic16_debug_verbose) {
7314 pic16_pCode2str (pc_str, 256, oldPC);
7315 pic16_InsertCommentAfter (oldPC->prev, "%s: replaced %s", __FUNCTION__, pc_str);
7319 /* insert new pCode into pBlock */
7320 pic16_pCodeInsertAfter (oldPC, newPC);
7321 pic16_unlinkpCode (oldPC);
7323 /* destruct replaced pCode */
7324 oldPC->destruct (oldPC);
7327 /* Returns the inverted conditional branch (if any) or NULL.
7328 * pcop must be set to the new jump target.
7330 pCode *getNegatedBcc (pCode *bcc, pCodeOp *pcop)
7334 if (!bcc || !isPCI(bcc)) return NULL;
7336 switch (PCI(bcc)->op) {
7337 case POC_BC: newBcc = pic16_newpCode (POC_BNC , pcop); break;
7338 case POC_BZ: newBcc = pic16_newpCode (POC_BNZ , pcop); break;
7339 case POC_BOV: newBcc = pic16_newpCode (POC_BNOV, pcop); break;
7340 case POC_BN: newBcc = pic16_newpCode (POC_BNN , pcop); break;
7341 case POC_BNC: newBcc = pic16_newpCode (POC_BC , pcop); break;
7342 case POC_BNZ: newBcc = pic16_newpCode (POC_BZ , pcop); break;
7343 case POC_BNOV: newBcc = pic16_newpCode (POC_BOV , pcop); break;
7344 case POC_BNN: newBcc = pic16_newpCode (POC_BN , pcop); break;
7351 #define MAX_DIST_GOTO 0x7FFFFFFF
7352 #define MAX_DIST_BRA 1020 // maximum offset (in bytes) possible with BRA
7353 #define MAX_DIST_BCC 120 // maximum offset (in bytes) possible with Bcc
7354 #define MAX_JUMPCHAIN_DEPTH 16 // number of GOTOs to follow in resolveJumpChain() (to prevent endless loops)
7355 #define IS_GOTO(arg) ((arg) && isPCI(arg) && (PCI(arg)->op == POC_GOTO || PCI(arg)->op == POC_BRA))
7357 /* Follows GOTO/BRA instructions to their target instructions, stores the
7358 * final destination (not a GOTO or BRA instruction) in target and returns
7359 * the distance from the original pc to *target.
7361 int resolveJumpChain (pCode *pc, pCode **target, pCodeOp **pcop) {
7364 pCodeOp *lastPCOP = NULL;
7368 //fprintf (stderr, "%s:%d: -=-", __FUNCTION__, __LINE__);
7370 /* only follow unconditional branches, except for the initial pCode (which may be a conditional branch) */
7371 while (curr && (last != curr) && (depth++ < MAX_JUMPCHAIN_DEPTH) && isPCI(curr)
7372 && (PCI(curr)->op == POC_GOTO || PCI(curr)->op == POC_BRA || (curr == pc && isConditionalBranch(curr)))) {
7374 lastPCOP = PCI(curr)->pcop;
7375 dist = findpCodeLabel (pc, PCI(curr)->pcop->name, MAX_DIST_GOTO, &curr);
7376 //fprintf (stderr, "last:%p, curr:%p, label:%s\n", last, curr, PCI(last)->pcop->name);
7379 if (target) *target = last;
7380 if (pcop) *pcop = lastPCOP;
7384 /* Returns pc if it is not a OPT_JUMPTABLE_BEGIN INFO pCode.
7385 * Otherwise the first pCode after the jumptable (after
7386 * the OPT_JUMPTABLE_END tag) is returned.
7388 pCode *skipJumptables (pCode *pc, int *isJumptable)
7391 if (!pc) return NULL;
7393 while (pc->type == PC_INFO && PCINF(pc)->type == INF_OPTIMIZATION && PCOO(PCINF(pc)->oper1)->type == OPT_JUMPTABLE_BEGIN) {
7395 //fprintf (stderr, "SKIPPING jumptable\n");
7397 //pc->print(stderr, pc);
7399 } while (pc && (pc->type != PC_INFO || PCINF(pc)->type != INF_OPTIMIZATION
7400 || PCOO(PCINF(pc)->oper1)->type != OPT_JUMPTABLE_END));
7401 //fprintf (stderr, "<<JUMPTAB:\n");
7402 // skip OPT_END as well
7403 if (pc) pc = pc->next;
7409 pCode *pic16_findNextInstructionSkipJumptables (pCode *pc, int *isJumptable)
7413 while (pc && !isPCI(pc) && !isPCAD(pc) && !isPCW(pc)) {
7414 // set pc to the first pCode after a jumptable, leave pc untouched otherwise
7415 pc = skipJumptables (pc, &isJumptab);
7417 // pc is the first pCode after the jumptable
7420 // pc has not been changed by skipJumptables()
7428 /* Turn GOTOs into BRAs if distance between GOTO and label
7429 * is less than 1024 bytes.
7431 * This method is especially useful if GOTOs after BTFS[SC]
7432 * can be turned into BRAs as GOTO would cost another NOP
7435 void pic16_OptimizeJumps ()
7438 pCode *pc_prev = NULL;
7439 pCode *pc_next = NULL;
7442 int change, iteration, isJumptab;
7445 int opt=0, toofar=0, opt_cond = 0, cond_toofar=0, opt_reorder = 0, opt_gotonext = 0, opt_gotochain = 0;
7447 if (!the_pFile) return;
7449 //fprintf (stderr, "%s:%d: %s\n", __FILE__, __LINE__, __FUNCTION__);
7451 for (pb = the_pFile->pbHead; pb != NULL; pb = pb->next) {
7452 int matchedInvertRule = 1;
7455 //fprintf (stderr, "%s:%d: iterating over pBlock %p\n", __FUNCTION__, __LINE__, pb);
7457 pc = pic16_findNextInstruction (pb->pcHead);
7460 pc_next = pic16_findNextInstructionSkipJumptables (pc->next, &isJumptab);
7462 // skip jumptable, i.e. start over with no pc_prev!
7468 /* (1) resolve chained jumps
7469 * Do not perform this until pattern (4) is no longer present! Otherwise we will
7470 * (a) leave dead code in and
7471 * (b) skip over the dead code with an (unneccessary) jump.
7473 if (!matchedInvertRule && (IS_GOTO(pc) || isConditionalBranch(pc))) {
7474 pCodeOp *lastTargetOp = NULL;
7475 int newDist = resolveJumpChain (pc, &target, &lastTargetOp);
7476 int maxDist = MAX_DIST_BCC;
7477 if (PCI(pc)->op == POC_BRA) maxDist = MAX_DIST_BRA;
7478 if (PCI(pc)->op == POC_GOTO) maxDist = MAX_DIST_GOTO;
7480 /* be careful NOT to make the jump instruction longer (might break previously shortened jumps!) */
7481 if (lastTargetOp && newDist <= maxDist && lastTargetOp != PCI(pc)->pcop
7482 && strcmp (lastTargetOp->name, PCI(pc)->pcop->name) != 0) {
7483 //fprintf (stderr, "(1) ");pc->print(stderr, pc); fprintf (stderr, " --> %s\n", lastTargetOp->name);
7484 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter (pc->prev, pic16_newpCodeCharP("(1) jump chain resolved")); }
7485 PCI(pc)->pcop->name = lastTargetOp->name;
7494 int condBraType = isSkipOnStatus(pc_prev);
7495 label = PCI(pc)->pcop->name;
7496 dist = findpCodeLabel(pc, label, MAX_DIST_BRA, &target);
7497 if (dist < 0) dist = -dist;
7498 //fprintf (stderr, "distance: %d (", dist); pc->print(stderr, pc);fprintf (stderr, ")\n");
7502 /* (2) remove "GOTO label; label:" */
7503 if (isLabel (pc_next, label)) {
7504 //fprintf (stderr, "(2) GOTO next instruction: ");pc->print(stderr, pc);fprintf (stderr, " --> ");pc_next->print(stderr, pc_next); fprintf(stderr, "\n");
7505 // first remove all preceeding SKIP instructions
7506 while (pc_prev && isPCI_SKIP(pc_prev)) {
7507 // attach labels on this instruction to pc_next
7508 //fprintf (stderr, "(2) preceeding SKIP removed: ");pc_prev->print(stderr, pc_prev);fprintf(stderr, "\n");
7509 PCI(pc_next)->label = pic16_pBranchAppend (PCI(pc_prev)->label, PCI(pc_next)->label);
7510 PCI(pc_prev)->label = NULL;
7511 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter (pc->prev, pic16_newpCodeCharP("(2) SKIP removed")); }
7512 pic16_unlinkpCode (pc_prev);
7513 pc_prev = pic16_findPrevInstruction (pc);
7515 // now remove the redundant goto itself
7516 PCI(pc_next)->label = pic16_pBranchAppend (PCI(pc)->label, PCI(pc_next)->label);
7517 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter (pc, pic16_newpCodeCharP("(2) GOTO next instruction removed")); }
7518 pic16_unlinkpCode (pc);
7519 pc = pic16_findPrevInstruction(pc_next->prev);
7520 isHandled = 1; // do not perform further optimizations
7526 /* (3) turn BTFSx STATUS,i; GOTO label into Bcc label if possible */
7527 if (!isHandled && condBraType != -1 && hasNoLabel(pc)) {
7528 if (dist < MAX_DIST_BCC) {
7530 switch (condBraType) {
7531 case 0x00: bcc = pic16_newpCode (POC_BC, PCI(pc)->pcop);break;
7532 // no BDC on DIGIT CARRY available
7533 case 0x02: bcc = pic16_newpCode (POC_BZ, PCI(pc)->pcop);break;
7534 case 0x03: bcc = pic16_newpCode (POC_BOV, PCI(pc)->pcop);break;
7535 case 0x04: bcc = pic16_newpCode (POC_BN, PCI(pc)->pcop);break;
7536 case 0x10: bcc = pic16_newpCode (POC_BNC, PCI(pc)->pcop);break;
7537 // no BNDC on DIGIT CARRY available
7538 case 0x12: bcc = pic16_newpCode (POC_BNZ, PCI(pc)->pcop);break;
7539 case 0x13: bcc = pic16_newpCode (POC_BNOV, PCI(pc)->pcop);break;
7540 case 0x14: bcc = pic16_newpCode (POC_BNN, PCI(pc)->pcop);break;
7542 // no replacement possible
7547 // ATTENTION: keep labels attached to BTFSx!
7548 // HINT: GOTO is label free (checked above)
7549 //fprintf (stderr, "%s:%d: (3) turning %s %s into %s %s\n", __FUNCTION__, __LINE__, PCI(pc)->mnemonic, label, PCI(bcc)->mnemonic, label);
7550 isHandled = 1; // do not perform further optimizations
7551 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter(pc_prev->prev, pic16_newpCodeCharP("(3) conditional branch introduced")); }
7552 pic16_pCodeReplace (pc_prev, bcc);
7559 //fprintf (stderr, "(%d, too far for Bcc)\n", dist);
7565 // (4) eliminate the following (common) tripel:
7567 // labels1: Bcc label2;
7568 // GOTO somewhere; ; <-- instruction referenced by pc
7570 // and replace it by
7571 // labels1: B#(cc) somewhere; ; #(cc) is the negated condition cc
7573 // ATTENTION: all labels pointing to "Bcc label2" must be attached
7574 // to <cont.> instead
7575 // ATTENTION: This optimization is only valid if <pred.> is
7576 // not a skip operation!
7577 // ATTENTION: somewhere must be within MAX_DIST_BCC bytes!
7578 // ATTENTION: no label may be attached to the GOTO instruction!
7579 if (isConditionalBranch(pc_prev)
7580 && (!isPCI_SKIP(pic16_findPrevInstruction(pc_prev->prev)))
7581 && (dist < MAX_DIST_BCC)
7582 && isLabel(pc_next,PCI(pc_prev)->pcop->name)
7583 && hasNoLabel(pc)) {
7584 pCode *newBcc = getNegatedBcc (pc_prev, PCI(pc)->pcop);
7587 //fprintf (stderr, "%s:%d: (4) turning %s %s into %s %s\n", __FUNCTION__, __LINE__, PCI(pc)->mnemonic, label, PCI(newBcc)->mnemonic, label);
7588 isHandled = 1; // do not perform further optimizations
7589 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter(pc_prev->prev, pic16_newpCodeCharP("(4) conditional skipping branch inverted")); }
7590 pic16_pCodeReplace (pc_prev, newBcc);
7595 matchedInvertRule++;
7600 /* (5) now just turn GOTO into BRA */
7601 if (!isHandled && (PCI(pc)->op == POC_GOTO)) {
7602 if (dist < MAX_DIST_BRA) {
7603 pCode *newBra = pic16_newpCode (POC_BRA, PCI(pc)->pcop);
7604 //fprintf (stderr, "%s:%d: (5) turning %s %s into %s %s\n", __FUNCTION__, __LINE__, PCI(pc)->mnemonic, label, PCI(newBra)->mnemonic, label);
7605 if (pic16_pcode_verbose) { pic16_pCodeInsertAfter(pc->prev, pic16_newpCodeCharP("(5) GOTO replaced by BRA")); }
7606 pic16_pCodeReplace (pc, newBra);
7611 //fprintf (stderr, "(%d, too far for BRA)\n", dist);
7614 } // if (!isHandled)
7621 pBlockRemoveUnusedLabels (pb);
7623 // This line enables goto chain resolution!
7624 if (matchedInvertRule > 1) matchedInvertRule = 1; else matchedInvertRule = 0;
7627 } while (change); /* fixpoint iteration per pBlock */
7630 // emit some statistics concerning goto-optimization
7632 if (pic16_debug_verbose || pic16_pcode_verbose) {
7633 fprintf (stderr, "optimize-goto:\n"
7634 "\t%5d GOTO->BRA; (%d GOTOs too far)\n"
7635 "\t%5d BTFSx, GOTO->Bcc (%d too far)\n"
7636 "\t%5d conditional \"skipping\" jumps inverted\n"
7637 "\t%5d GOTOs to next instruction removed\n"
7638 "\t%5d chained GOTOs resolved\n",
7639 opt, toofar, opt_cond, cond_toofar, opt_reorder, opt_gotonext, opt_gotochain);
7642 //fprintf (stderr, "%s:%d: %s\n", __FILE__, __LINE__, __FUNCTION__);
7646 #undef MAX_JUMPCHAIN_DEPTH
7647 #undef MAX_DIST_GOTO
7651 /** END OF RAPHAEL NEIDER'S ADDITIONS **/
7653 static void pBlockDestruct(pBlock *pb)
7664 /*-----------------------------------------------------------------*/
7665 /* void mergepBlocks(char dbName) - Search for all pBlocks with the*/
7666 /* name dbName and combine them */
7667 /* into one block */
7668 /*-----------------------------------------------------------------*/
7669 static void mergepBlocks(char dbName)
7672 pBlock *pb, *pbmerged = NULL,*pbn;
7674 pb = the_pFile->pbHead;
7676 //fprintf(stderr," merging blocks named %c\n",dbName);
7680 //fprintf(stderr,"looking at %c\n",getpBlock_dbName(pb));
7681 if( getpBlock_dbName(pb) == dbName) {
7683 //fprintf(stderr," merged block %c\n",dbName);
7688 pic16_addpCode2pBlock(pbmerged, pb->pcHead);
7689 /* pic16_addpCode2pBlock doesn't handle the tail: */
7690 pbmerged->pcTail = pb->pcTail;
7692 pb->prev->next = pbn;
7694 pbn->prev = pb->prev;
7699 //pic16_printpBlock(stderr, pbmerged);
7706 /*-----------------------------------------------------------------*/
7707 /* AnalyzeFlow - Examine the flow of the code and optimize */
7709 /* level 0 == minimal optimization */
7710 /* optimize registers that are used only by two instructions */
7711 /* level 1 == maximal optimization */
7712 /* optimize by looking at pairs of instructions that use the */
7714 /*-----------------------------------------------------------------*/
7716 static void AnalyzeFlow(int level)
7718 static int times_called=0;
7722 /* remove unused allocated registers before exiting */
7723 pic16_RemoveUnusedRegisters();
7728 /* if this is not the first time this function has been called,
7729 * then clean up old flow information */
7730 if(times_called++) {
7731 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7733 pic16_RegsUnMapLiveRanges();
7737 /* Phase 2 - Flow Analysis - Register Banking
7739 * In this phase, the individual flow blocks are examined
7740 * and register banking is fixed.
7744 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7745 pic16_FixRegisterBanking(pb);
7748 /* Phase 2 - Flow Analysis
7750 * In this phase, the pCode is partition into pCodeFlow
7751 * blocks. The flow blocks mark the points where a continuous
7752 * stream of instructions changes flow (e.g. because of
7753 * a call or goto or whatever).
7756 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7757 pic16_BuildFlow(pb);
7760 /* Phase 2 - Flow Analysis - linking flow blocks
7762 * In this phase, the individual flow blocks are examined
7763 * to determine their order of excution.
7766 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7770 if (pic16_options.opt_flags & OF_OPTIMIZE_DF) {
7771 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
7772 pic16_createDF (pb);
7773 #if defined (DUMP_DF_GRAPHS) && DUMP_DF_GRAPHS > 0
7774 pic16_vcg_dump_default (pb);
7776 //pic16_destructDF (pb);
7780 if (0) releaseStack (); // releasing is costly...
7784 /* Phase 3 - Flow Analysis - Flow Tree
7786 * In this phase, the individual flow blocks are examined
7787 * to determine their order of execution.
7790 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7791 pic16_BuildFlowTree(pb);
7794 /* Phase x - Flow Analysis - Used Banks
7796 * In this phase, the individual flow blocks are examined
7797 * to determine the Register Banks they use
7801 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7806 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7807 pic16_pCodeRegMapLiveRanges(pb);
7809 pic16_RemoveUnusedRegisters();
7810 pic16_removeUnusedRegistersDF ();
7812 // for(pb = the_pFile->pbHead; pb; pb = pb->next)
7813 pic16_pCodeRegOptimizeRegUsage(level);
7822 for(pb = the_pFile->pbHead; pb; pb = pb->next)
7827 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
7830 for( pcflow = pic16_findNextpCode(pb->pcHead, PC_FLOW);
7831 (pcflow = pic16_findNextpCode(pcflow, PC_FLOW)) != NULL;
7832 pcflow = pcflow->next) {
7833 FillFlow(PCFL(pcflow));
7838 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
7841 for( pcflow = pic16_findNextpCode(pb->pcHead, PC_FLOW);
7842 (pcflow = pic16_findNextpCode(pcflow, PC_FLOW)) != NULL;
7843 pcflow = pcflow->next) {
7844 FlowStats(PCFL(pcflow));
7850 /* VR -- no need to analyze banking in flow, but left here :
7851 * 1. because it may be used in the future for other purposes
7852 * 2. because if omitted we'll miss some optimization done here
7854 * Perhaps I should rename it to something else
7857 /*-----------------------------------------------------------------*/
7858 /* pic16_AnalyzeBanking - Called after the memory addresses have been */
7859 /* assigned to the registers. */
7861 /*-----------------------------------------------------------------*/
7863 void pic16_AnalyzeBanking(void)
7867 /* Phase x - Flow Analysis - Used Banks
7869 * In this phase, the individual flow blocks are examined
7870 * to determine the Register Banks they use
7880 if(!the_pFile)return;
7882 if(!pic16_options.no_banksel) {
7883 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
7884 // fprintf(stderr, "%s:%d: Fix register banking in pb= 0x%p\n", __FILE__, __LINE__, pb);
7885 pic16_FixRegisterBanking(pb);
7890 /*-----------------------------------------------------------------*/
7891 /* buildCallTree - Look at the flow and extract all of the calls. */
7892 /*-----------------------------------------------------------------*/
7893 static set *register_usage(pBlock *pb);
7895 static void buildCallTree(void )
7907 /* Now build the call tree.
7908 First we examine all of the pCodes for functions.
7909 Keep in mind that the function boundaries coincide
7910 with pBlock boundaries.
7912 The algorithm goes something like this:
7913 We have two nested loops. The outer loop iterates
7914 through all of the pBlocks/functions. The inner
7915 loop iterates through all of the pCodes for
7916 a given pBlock. When we begin iterating through
7917 a pBlock, the variable pc_fstart, pCode of the start
7918 of a function, is cleared. We then search for pCodes
7919 of type PC_FUNCTION. When one is encountered, we
7920 initialize pc_fstart to this and at the same time
7921 associate a new pBranch object that signifies a
7922 branch entry. If a return is found, then this signifies
7923 a function exit point. We'll link the pCodes of these
7924 returns to the matching pc_fstart.
7926 When we're done, a doubly linked list of pBranches
7927 will exist. The head of this list is stored in
7928 `the_pFile', which is the meta structure for all
7929 of the pCode. Look at the pic16_printCallTree function
7930 on how the pBranches are linked together.
7933 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
7934 pCode *pc_fstart=NULL;
7935 for(pc = pb->pcHead; pc; pc = pc->next) {
7937 if(isPCI(pc) && pc_fstart) {
7938 if(PCI(pc)->is2MemOp) {
7939 r = pic16_getRegFromInstruction2(pc);
7940 if(r && !strcmp(r->name, "POSTDEC1"))
7941 PCF(pc_fstart)->stackusage++;
7943 r = pic16_getRegFromInstruction(pc);
7944 if(r && !strcmp(r->name, "PREINC1"))
7945 PCF(pc_fstart)->stackusage--;
7950 if (PCF(pc)->fname) {
7953 sprintf(buf, "%smain", port->fun_prefix);
7954 if(STRCASECMP(PCF(pc)->fname, buf) == 0) {
7955 //fprintf(stderr," found main \n");
7956 pb->cmemmap = NULL; /* FIXME do we need to free ? */
7960 pbr = Safe_calloc(1,sizeof(pBranch));
7961 pbr->pc = pc_fstart = pc;
7964 the_pFile->functions = pic16_pBranchAppend(the_pFile->functions,pbr);
7966 // Here's a better way of doing the same:
7967 addSet(&pb->function_entries, pc);
7970 // Found an exit point in a function, e.g. return
7971 // (Note, there may be more than one return per function)
7973 pBranchLink(PCF(pc_fstart), PCF(pc));
7975 addSet(&pb->function_exits, pc);
7977 } else if(isCALL(pc)) {
7978 addSet(&pb->function_calls,pc);
7985 /* This is not needed because currently all register used
7986 * by a function are stored in stack -- VR */
7988 /* Re-allocate the registers so that there are no collisions
7989 * between local variables when one function call another */
7992 // pic16_deallocateAllRegs();
7994 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8002 /*-----------------------------------------------------------------*/
8003 /* pic16_AnalyzepCode - parse the pCode that has been generated and form */
8004 /* all of the logical connections. */
8006 /* Essentially what's done here is that the pCode flow is */
8008 /*-----------------------------------------------------------------*/
8010 void pic16_AnalyzepCode(char dbName)
8021 /* Phase 1 - Register allocation and peep hole optimization
8023 * The first part of the analysis is to determine the registers
8024 * that are used in the pCode. Once that is done, the peep rules
8025 * are applied to the code. We continue to loop until no more
8026 * peep rule optimizations are found (or until we exceed the
8027 * MAX_PASSES threshold).
8029 * When done, the required registers will be determined.
8035 DFPRINTF((stderr," Analyzing pCode: PASS #%d\n",i+1));
8036 //fprintf(stderr," Analyzing pCode: PASS #%d\n",i+1);
8038 /* First, merge the labels with the instructions */
8039 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8040 if('*' == dbName || getpBlock_dbName(pb) == dbName) {
8042 DFPRINTF((stderr," analyze and merging block %c\n",dbName));
8043 //fprintf(stderr," analyze and merging block %c\n",dbName);
8044 pic16_pBlockMergeLabels(pb);
8047 DFPRINTF((stderr," skipping block analysis dbName=%c blockname=%c\n",dbName,getpBlock_dbName));
8052 changes = OptimizepCode(dbName);
8055 } while(changes && (i++ < MAX_PASSES));
8062 /* convert a series of movff's of local regs to stack, with a single call to
8063 * a support functions which does the same thing via loop */
8064 static void pic16_convertLocalRegs2Support(pCode *pcstart, pCode *pcend, int count, regs *r, int entry)
8068 char *fname[]={"__lr_store", "__lr_restore"};
8070 // pc = pic16_newpCode(POC_CALL, pic16_popGetFromString( (entry?fname[0]:fname[1]) ));
8072 pct = pic16_findNextInstruction(pcstart->next);
8075 pct = pc->next; //pic16_findNextInstruction(pc->next);
8076 // pc->print(stderr, pc);
8077 if(isPCI(pc) && PCI(pc)->label) {
8078 pbr = PCI(pc)->label;
8079 while(pbr && pbr->pc) {
8080 PCI(pcstart)->label = pic16_pBranchAppend(PCI(pcstart)->label, pbr);
8084 // pc->print(stderr, pc);
8086 pc->prev->next = pct;
8087 pct->prev = pc->prev;
8091 } while ((pc) && (pc != pcend));
8093 /* unlink movff instructions */
8094 pcstart->next = pcend;
8095 pcend->prev = pcstart;
8099 // pic16_pCodeInsertAfter(pc, pct = pic16_newpCode(POC_MOVFF, pic16_popGet2p(
8100 // pic16_popCopyReg(&pic16_pc_fsr0l), pic16_popCopyReg(pic16_framepnt_lo)))); pc = pct;
8103 pic16_pCodeInsertAfter(pc, pct=pic16_newpCode(POC_LFSR, pic16_popGetLit2(0, pic16_popGetWithString(r->name)))); pc = pct;
8104 pic16_pCodeInsertAfter(pc, pct=pic16_newpCode(POC_MOVLW, pic16_popGetLit( count ))); pc = pct;
8105 pic16_pCodeInsertAfter(pc, pct=pic16_newpCode(POC_CALL, pic16_popGetWithString( fname[ (entry==1?0:1) ] ))); pc = pct;
8108 // pic16_pCodeInsertAfter(pc, pct = pic16_newpCode(POC_MOVFF, pic16_popGet2p(
8109 // pic16_popCopyReg(pic16_framepnt_lo), pic16_popCopyReg(&pic16_pc_fsr0l)))); pc = pct;
8116 sym = newSymbol( fname[ entry?0:1 ], 0 );
8117 strcpy(sym->rname, fname[ entry?0:1 ]);
8118 checkAddSym(&externs, sym);
8120 // fprintf(stderr, "%s:%d adding extern symbol %s in externs\n", __FILE__, __LINE__, fname[ entry?0:1 ]);
8125 /*-----------------------------------------------------------------*/
8126 /* OptimizeLocalRegs - turn sequence of MOVFF instructions for */
8127 /* local registers to a support function call */
8128 /*-----------------------------------------------------------------*/
8129 void pic16_OptimizeLocalRegs(void)
8134 pCodeOpLocalReg *pclr;
8137 regs *r, *lastr=NULL, *firstr=NULL;
8138 pCode *pcstart=NULL, *pcend=NULL;
8143 * local_regs begin mark
8144 * MOVFF r0x01, POSTDEC1
8145 * MOVFF r0x02, POSTDEC1
8148 * MOVFF r0x0n, POSTDEC1
8149 * local_regs end mark
8151 * convert the above to the below:
8152 * MOVLW starting_register_index
8154 * MOVLW register_count
8155 * call __save_registers_in_stack
8161 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8162 inRegCount = regCount = 0;
8163 firstr = lastr = NULL;
8164 for(pc = pb->pcHead; pc; pc = pc->next) {
8166 /* hold current function name */
8167 if(pc && isPCF(pc))curFunc = PCF(pc)->fname;
8169 if(pc && (pc->type == PC_INFO)) {
8172 if(pci->type == INF_LOCALREGS) {
8173 pclr = PCOLR(pci->oper1);
8175 if((pclr->type == LR_ENTRY_BEGIN)
8176 || (pclr->type == LR_ENTRY_END))inEntry = 1;
8179 switch(pclr->type) {
8180 case LR_ENTRY_BEGIN:
8182 inRegCount = 1; regCount = 0;
8183 pcstart = pc; //pic16_findNextInstruction(pc->next);
8184 firstr = lastr = NULL;
8190 pcend = pc; //pic16_findPrevInstruction(pc->prev);
8193 if(curFunc && inWparamList(curFunc+1)) {
8194 fprintf(stderr, "sdcc: %s: warning: disabling lr-support for functionn %s\n",
8198 pic16_convertLocalRegs2Support(pcstart, pcend, regCount,
8203 firstr = lastr = NULL;
8207 if(inRegCount == -1) {
8208 // fprintf(stderr, "%s:%d registers used [%s] %d\n", __FILE__, __LINE__, inEntry?"entry":"exit", regCount);
8214 if(isPCI(pc) && (PCI(pc)->op == POC_MOVFF) && (inRegCount == 1)) {
8216 r = pic16_getRegFromInstruction(pc);
8218 r = pic16_getRegFromInstruction2(pc);
8219 if(r && (r->type == REG_GPR) && (r->pc_type == PO_GPR_TEMP)) {
8220 if(!firstr)firstr = r;
8222 // fprintf(stderr, "%s:%d\t%s\t%i\t%d/%d\n", __FILE__, __LINE__, r->name, r->rIdx);
8234 /*-----------------------------------------------------------------*/
8235 /* ispCodeFunction - returns true if *pc is the pCode of a */
8237 /*-----------------------------------------------------------------*/
8238 static bool ispCodeFunction(pCode *pc)
8241 if(pc && pc->type == PC_FUNCTION && PCF(pc)->fname)
8247 /*-----------------------------------------------------------------*/
8248 /* findFunction - Search for a function by name (given the name) */
8249 /* in the set of all functions that are in a pBlock */
8250 /* (note - I expect this to change because I'm planning to limit */
8251 /* pBlock's to just one function declaration */
8252 /*-----------------------------------------------------------------*/
8253 static pCode *findFunction(char *fname)
8260 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8262 pc = setFirstItem(pb->function_entries);
8265 if((pc->type == PC_FUNCTION) &&
8267 (strcmp(fname, PCF(pc)->fname)==0))
8270 pc = setNextItem(pb->function_entries);
8278 static void MarkUsedRegisters(set *regset)
8283 for(r1=setFirstItem(regset); r1; r1=setNextItem(regset)) {
8284 // fprintf(stderr, "marking register = %s\t", r1->name);
8285 r2 = pic16_regWithIdx(r1->rIdx);
8286 // fprintf(stderr, "to register = %s\n", r2->name);
8292 static void pBlockStats(FILE *of, pBlock *pb)
8298 if(!pic16_pcode_verbose)return;
8300 fprintf(of,";***\n; pBlock Stats: dbName = %c\n;***\n",getpBlock_dbName(pb));
8302 // for now just print the first element of each set
8303 pc = setFirstItem(pb->function_entries);
8305 fprintf(of,";entry: ");
8308 pc = setFirstItem(pb->function_exits);
8310 fprintf(of,";has an exit\n");
8314 pc = setFirstItem(pb->function_calls);
8316 fprintf(of,";functions called:\n");
8319 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
8320 fprintf(of,"; %s\n",pic16_get_op_from_instruction(PCI(pc)));
8322 pc = setNextItem(pb->function_calls);
8326 r = setFirstItem(pb->tregisters);
8328 int n = elementsInSet(pb->tregisters);
8330 fprintf(of,";%d compiler assigned register%c:\n",n, ( (n!=1) ? 's' : ' '));
8333 fprintf(of, "; %s\n",r->name);
8334 r = setNextItem(pb->tregisters);
8338 fprintf(of, "; uses %d bytes of stack\n", 1+ elementsInSet(pb->tregisters));
8341 /*-----------------------------------------------------------------*/
8342 /*-----------------------------------------------------------------*/
8344 static void sequencepCode(void)
8350 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8352 pb->seq = GpCodeSequenceNumber+1;
8354 for( pc = pb->pcHead; pc; pc = pc->next)
8355 pc->seq = ++GpCodeSequenceNumber;
8361 /*-----------------------------------------------------------------*/
8362 /*-----------------------------------------------------------------*/
8363 static set *register_usage(pBlock *pb)
8366 set *registers=NULL;
8367 set *registersInCallPath = NULL;
8369 /* check recursion */
8371 pc = setFirstItem(pb->function_entries);
8378 if(pc->type != PC_FUNCTION)
8379 fprintf(stderr,"%s, first pc is not a function???\n",__FUNCTION__);
8381 pc = setFirstItem(pb->function_calls);
8382 for( ; pc; pc = setNextItem(pb->function_calls)) {
8384 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
8385 char *dest = pic16_get_op_from_instruction(PCI(pc));
8387 pcn = findFunction(dest);
8389 registersInCallPath = register_usage(pcn->pb);
8391 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
8396 pBlockStats(stderr,pb); // debug
8399 // Mark the registers in this block as used.
8401 MarkUsedRegisters(pb->tregisters);
8402 if(registersInCallPath) {
8403 /* registers were used in the functions this pBlock has called */
8404 /* so now, we need to see if these collide with the ones we are */
8407 regs *r1,*r2, *newreg;
8409 DFPRINTF((stderr,"comparing registers\n"));
8411 r1 = setFirstItem(registersInCallPath);
8414 r2 = setFirstItem(pb->tregisters);
8416 while(r2 && (r1->type != REG_STK)) {
8418 if(r2->rIdx == r1->rIdx) {
8419 newreg = pic16_findFreeReg(REG_GPR);
8423 DFPRINTF((stderr,"Bummer, no more registers.\n"));
8427 DFPRINTF((stderr,"Cool found register collision nIdx=%d moving to %d\n",
8428 r1->rIdx, newreg->rIdx));
8429 r2->rIdx = newreg->rIdx;
8430 //if(r2->name) Safe_free(r2->name);
8432 r2->name = Safe_strdup(newreg->name);
8436 newreg->wasUsed = 1;
8438 r2 = setNextItem(pb->tregisters);
8441 r1 = setNextItem(registersInCallPath);
8444 /* Collisions have been resolved. Now free the registers in the call path */
8445 r1 = setFirstItem(registersInCallPath);
8447 if(r1->type != REG_STK) {
8448 newreg = pic16_regWithIdx(r1->rIdx);
8451 r1 = setNextItem(registersInCallPath);
8455 // MarkUsedRegisters(pb->registers);
8457 registers = unionSets(pb->tregisters, registersInCallPath, THROW_NONE);
8460 DFPRINTF((stderr,"returning regs\n"));
8462 DFPRINTF((stderr,"not returning regs\n"));
8464 DFPRINTF((stderr,"pBlock after register optim.\n"));
8465 pBlockStats(stderr,pb); // debug
8471 /*-----------------------------------------------------------------*/
8472 /* pct2 - writes the call tree to a file */
8474 /*-----------------------------------------------------------------*/
8475 static void pct2(FILE *of,pBlock *pb,int indent,int usedstack)
8479 // set *registersInCallPath = NULL;
8485 fprintf(of, "recursive function\n");
8486 return; //recursion ?
8489 pc = setFirstItem(pb->function_entries);
8496 for(i=0;i<indent;i++) // Indentation
8500 if(pc->type == PC_FUNCTION) {
8501 usedstack += PCF(pc)->stackusage;
8502 fprintf(of,"%s (stack: %i)\n",PCF(pc)->fname, usedstack);
8503 } else return; // ???
8506 pc = setFirstItem(pb->function_calls);
8507 for( ; pc; pc = setNextItem(pb->function_calls)) {
8509 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
8510 char *dest = pic16_get_op_from_instruction(PCI(pc));
8512 pcn = findFunction(dest);
8514 pct2(of,pcn->pb,indent+1, usedstack); // + PCF(pcn)->stackusage);
8516 fprintf(of,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
8524 /*-----------------------------------------------------------------*/
8525 /* pic16_printCallTree - writes the call tree to a file */
8527 /*-----------------------------------------------------------------*/
8529 void pic16_printCallTree(FILE *of)
8541 fprintf(of, "\npBlock statistics\n");
8542 for(pb = the_pFile->pbHead; pb; pb = pb->next )
8546 fprintf(of,"Call Tree\n");
8547 pbr = the_pFile->functions;
8551 if(!ispCodeFunction(pc))
8552 fprintf(of,"bug in call tree");
8555 fprintf(of,"Function: %s\n", PCF(pc)->fname);
8557 while(pc->next && !ispCodeFunction(pc->next)) {
8559 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL)
8560 fprintf(of,"\t%s\n",pic16_get_op_from_instruction(PCI(pc)));
8568 fprintf(of,"\n**************\n\na better call tree\n");
8569 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8574 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8575 fprintf(of,"block dbname: %c\n", getpBlock_dbName(pb));
8581 /*-----------------------------------------------------------------*/
8583 /*-----------------------------------------------------------------*/
8585 static void InlineFunction(pBlock *pb)
8593 pc = setFirstItem(pb->function_calls);
8595 for( ; pc; pc = setNextItem(pb->function_calls)) {
8598 pCode *pcn = findFunction(pic16_get_op_from_instruction(PCI(pc)));
8604 if(pcn && isPCF(pcn) && (PCF(pcn)->ncalled == 0)) { /* change 0 to 1 to enable inlining */
8606 //fprintf(stderr,"Cool can inline:\n");
8607 //pcn->print(stderr,pcn);
8609 //fprintf(stderr,"recursive call Inline\n");
8610 InlineFunction(pcn->pb);
8611 //fprintf(stderr,"return from recursive call Inline\n");
8614 At this point, *pc points to a CALL mnemonic, and
8615 *pcn points to the function that is being called.
8617 To in-line this call, we need to remove the CALL
8618 and RETURN(s), and link the function pCode in with
8624 /* Remove the CALL */
8628 /* remove callee pBlock from the pBlock linked list */
8629 removepBlock(pcn->pb);
8637 /* Remove the Function pCode */
8638 pct = pic16_findNextInstruction(pcn->next);
8640 /* Link the function with the callee */
8641 pc->next = pcn->next;
8642 pcn->next->prev = pc;
8644 /* Convert the function name into a label */
8646 pbr = Safe_calloc(1,sizeof(pBranch));
8647 pbr->pc = pic16_newpCodeLabel(PCF(pcn)->fname, -1);
8649 PCI(pct)->label = pic16_pBranchAppend(PCI(pct)->label,pbr);
8650 PCI(pct)->label = pic16_pBranchAppend(PCI(pct)->label,PCI(pc_call)->label);
8652 /* turn all of the return's except the last into goto's */
8653 /* check case for 2 instruction pBlocks */
8654 pce = pic16_findNextInstruction(pcn->next);
8656 pCode *pce_next = pic16_findNextInstruction(pce->next);
8658 if(pce_next == NULL) {
8659 /* found the last return */
8660 pCode *pc_call_next = pic16_findNextInstruction(pc_call->next);
8662 //fprintf(stderr,"found last return\n");
8663 //pce->print(stderr,pce);
8664 pce->prev->next = pc_call->next;
8665 pc_call->next->prev = pce->prev;
8666 PCI(pc_call_next)->label = pic16_pBranchAppend(PCI(pc_call_next)->label,
8676 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
8682 /*-----------------------------------------------------------------*/
8684 /*-----------------------------------------------------------------*/
8686 void pic16_InlinepCode(void)
8695 if(!functionInlining)
8698 /* Loop through all of the function definitions and count the
8699 * number of times each one is called */
8700 //fprintf(stderr,"inlining %d\n",__LINE__);
8702 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
8704 pc = setFirstItem(pb->function_calls);
8706 for( ; pc; pc = setNextItem(pb->function_calls)) {
8709 pCode *pcn = findFunction(pic16_get_op_from_instruction(PCI(pc)));
8710 if(pcn && isPCF(pcn)) {
8711 PCF(pcn)->ncalled++;
8714 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
8719 //fprintf(stderr,"inlining %d\n",__LINE__);
8721 /* Now, Loop through the function definitions again, but this
8722 * time inline those functions that have only been called once. */
8724 InlineFunction(the_pFile->pbHead);
8725 //fprintf(stderr,"inlining %d\n",__LINE__);
8727 for(pb = the_pFile->pbHead; pb; pb = pb->next)
8732 char *pic_optype_names[]={
8733 "PO_NONE", // No operand e.g. NOP
8734 "PO_W", // The working register (as a destination)
8735 "PO_WREG", // The working register (as a file register)
8736 "PO_STATUS", // The 'STATUS' register
8737 "PO_BSR", // The 'BSR' register
8738 "PO_FSR0", // The "file select register" (in PIC18 family it's one
8740 "PO_INDF0", // The Indirect register
8741 "PO_INTCON", // Interrupt Control register
8742 "PO_GPR_REGISTER", // A general purpose register
8743 "PO_GPR_BIT", // A bit of a general purpose register
8744 "PO_GPR_TEMP", // A general purpose temporary register
8745 "PO_SFR_REGISTER", // A special function register (e.g. PORTA)
8746 "PO_PCL", // Program counter Low register
8747 "PO_PCLATH", // Program counter Latch high register
8748 "PO_PCLATU", // Program counter Latch upper register
8749 "PO_PRODL", // Product Register Low
8750 "PO_PRODH", // Product Register High
8751 "PO_LITERAL", // A constant
8752 "PO_REL_ADDR", // A relative address
8753 "PO_IMMEDIATE", // (8051 legacy)
8754 "PO_DIR", // Direct memory (8051 legacy)
8755 "PO_CRY", // bit memory (8051 legacy)
8756 "PO_BIT", // bit operand.
8757 "PO_STR", // (8051 legacy)
8759 "PO_WILD" // Wild card operand in peep optimizer
8763 char *dumpPicOptype(PIC_OPTYPE type)
8765 return (pic_optype_names[ type ]);
8769 /*** BEGIN of stuff belonging to the BANKSEL optimization ***/
8772 #define MAX_COMMON_BANK_SIZE 32
8773 #define FIRST_PSEUDO_BANK_NR 1000
8775 hTab *sym2bank = NULL; // <OPERAND NAME> --> <PSEUDO BANK NR>
8776 hTab *bank2sym = NULL; // <PSEUDO BANK NR> --> <OPERAND NAME>
8777 hTab *coerce = NULL; // <PSEUDO BANK NR> --> <&PSEUDOBANK>
8780 typedef enum { INVALID_BANK = -1, UNKNOWN_BANK = -2, FIXED_BANK = -3 } pseudoBankNr;
8783 pseudoBankNr bank; // number assigned to this pseudoBank
8784 unsigned int size; // number of operands assigned to this bank
8785 unsigned int ref; // number of symbols referring to this pseudoBank (for garbage collection)
8788 /*----------------------------------------------------------------------*/
8789 /* hashSymbol - hash function used to map SYMBOLs (or operands) to ints */
8790 /*----------------------------------------------------------------------*/
8791 unsigned int hashSymbol (const char *str)
8793 unsigned int res = 0;
8798 res = (res << 4) | (res >> (8 * sizeof(unsigned int) - 4));
8805 /*-----------------------------------------------------------------------*/
8806 /* compareSymbol - return 1 iff sym1 equals sym2 */
8807 /*-----------------------------------------------------------------------*/
8808 int compareSymbol (const void *sym1, const void *sym2)
8810 char *s1 = (char*) sym1;
8811 char *s2 = (char*) sym2;
8813 return (strcmp (s1,s2) == 0);
8816 /*-----------------------------------------------------------------------*/
8817 /* comparePre - return 1 iff p1 == p2 */
8818 /*-----------------------------------------------------------------------*/
8819 int comparePtr (const void *p1, const void *p2)
8824 /*----------------------------------------------------------*/
8825 /* getSymbolFromOperand - return a pointer to the symbol in */
8826 /* the given operand and its length */
8827 /*----------------------------------------------------------*/
8828 char *getSymbolFromOperand (char *op, int *len)
8833 if (!op) return NULL;
8835 // we recognize two forms of operands: SYMBOL and (SYMBOL + offset)
8837 if (*sym == '(') sym++;
8840 while (((*curr >= 'A') && (*curr <= 'Z'))
8841 || ((*curr >= 'a') && (*curr <= 'z'))
8842 || ((curr != sym) && (*curr >= '0') && (*curr <= '9'))
8843 || (*curr == '_')) {
8844 // find end of symbol [A-Za-z_]?[A-Za-z0-9]*
8852 /*--------------------------------------------------------------------------*/
8853 /* getSymFromBank - get (one) name of a symbol assigned to the given bank */
8854 /*--------------------------------------------------------------------------*/
8855 char *getSymFromBank (pseudoBankNr bank)
8859 if (bank < 0) return "<INVALID BANK NR>";
8860 return hTabFindByKey (bank2sym, bank % bank2sym->size, (void *) bank, &comparePtr);
8863 /*-----------------------------------------------------------------------*/
8864 /* getPseudoBsrFromOperand - maps a string to its corresponding pseudo */
8865 /* bank number (uses hTab sym2bank), if the */
8866 /* symbol is not yet assigned a pseudo bank it */
8867 /* is assigned one here */
8868 /*-----------------------------------------------------------------------*/
8869 pseudoBankNr getPseudoBankNrFromOperand (const char *op)
8871 static pseudoBankNr next_bank = FIRST_PSEUDO_BANK_NR;
8877 hash = hashSymbol (op) % sym2bank->size;
8878 bank = (pseudoBankNr) hTabFindByKey (sym2bank, hash, op, &compareSymbol);
8879 if (bank == (pseudoBankNr)NULL) bank = UNKNOWN_BANK;
8881 if (bank == UNKNOWN_BANK) {
8882 // create a pseudo bank for the operand
8884 hTabAddItemLong (&sym2bank, hash, (char *)op, (void *)bank);
8885 hTabAddItemLong (&bank2sym, bank, (void *) bank, (void *)op);
8886 getOrAddGNode (adj, NULL, bank); // adds the node if it does not exist yet
8887 //fprintf (stderr, "%s:%d: adding %s with hash %u in bank %u\n", __FUNCTION__, __LINE__, op, hash, bank);
8889 //fprintf (stderr, "%s:%d: found %s with hash %u in bank %u\n", __FUNCTION__, __LINE__, op, hash, bank);
8897 /*--------------------------------------------------------------------*/
8898 /* isBanksel - check whether the given pCode is a BANKSEL instruction */
8899 /*--------------------------------------------------------------------*/
8900 int isBanksel (pCode *pc)
8904 if (isPCI(pc) && (PCI(pc)->op == POC_BANKSEL || PCI(pc)->op == POC_MOVLB)) {
8905 // BANKSEL <variablename> or MOVLB <banknr>
8906 //fprintf (stderr, "%s:%d: BANKSEL found: %s %s\n", __FUNCTION__, __LINE__, PCAD(pc)->directive, PCAD(pc)->arg);
8910 // check for inline assembler BANKSELs
8911 if (isPCAD(pc) && PCAD(pc)->directive && (STRCASECMP(PCAD(pc)->directive,"BANKSEL") == 0 ||
8912 STRCASECMP(PCAD(pc)->directive,"MOVLB") == 0)) {
8913 //fprintf (stderr, "%s:%d: BANKSEL found: %s %s\n", __FUNCTION__, __LINE__, PCAD(pc)->directive, PCAD(pc)->arg);
8917 // assume pc is no BANKSEL instruction
8921 /*---------------------------------------------------------------------------------*/
8922 /* invalidatesBSR - check whether the pCodeInstruction passed in modifies the BSR */
8923 /* This method can not guarantee to find all modifications of the */
8924 /* BSR (e.g. via INDirection registers) but covers all compiler */
8925 /* generated plus some cases. */
8926 /*---------------------------------------------------------------------------------*/
8927 int invalidatesBSR(pCode *pc)
8929 // assembler directives invalidate BSR (well, they might, we don't know)
8930 if (isPCAD(pc)) return 1;
8932 // only ASMDIRs and pCodeInstructions can invalidate BSR
8933 if (!isPCI(pc)) return 0;
8935 // we have a pCodeInstruction
8937 // check for BSR modifying instructions
8938 switch (PCI(pc)->op) {
8942 case POC_RETFIE: // might be used as CALL replacement
8943 case POC_RETLW: // might be used as CALL replacement
8944 case POC_RETURN: // might be used as CALL replacement
8949 default: // other instruction do not change BSR unless BSR is an explicit operand!
8950 // TODO: check for BSR as an explicit operand (e.g. INCF BSR,F), which should be rather unlikely...!
8954 // no change of BSR possible/probable
8958 /*------------------------------------------------------------*/
8959 /* getBankFromBanksel - return the pseudo bank nr assigned to */
8960 /* the symbol referenced in this BANKSEL */
8961 /*------------------------------------------------------------*/
8962 pseudoBankNr getBankFromBanksel (pCode *pc)
8965 int data = (int)NULL;
8967 if (!pc) return INVALID_BANK;
8969 if (isPCAD(pc) && PCAD(pc)->directive) {
8970 if (STRCASECMP(PCAD(pc)->directive,"BANKSEL") == 0) {
8971 // get symbolname from PCAD(pc)->arg
8972 //fprintf (stderr, "%s:%d: BANKSEL found: %s %s\n", __FUNCTION__, __LINE__, PCAD(pc)->directive, PCAD(pc)->arg);
8973 sym = PCAD(pc)->arg;
8974 data = getPseudoBankNrFromOperand (sym);
8975 //fprintf (stderr, "symbol: %s, data=%i\n", sym, data);
8976 } else if (STRCASECMP(PCAD(pc)->directive,"MOVLB")) {
8977 // get (literal) bank number from PCAD(pc)->arg
8978 fprintf (stderr, "%s:%d: MOVLB found: %s %s\n", __FUNCTION__, __LINE__, PCAD(pc)->directive, PCAD(pc)->arg);
8979 assert (0 && "not yet implemented - turn off banksel optimization for now");
8981 } else if (isPCI(pc)) {
8982 if (PCI(pc)->op == POC_BANKSEL) {
8983 // get symbolname from PCI(pc)->pcop->name (?)
8984 //fprintf (stderr, "%s:%d: BANKSEL found: %s %s\n", __FUNCTION__, __LINE__, PCI(pc)->mnemonic, PCI(pc)->pcop->name);
8985 sym = PCI(pc)->pcop->name;
8986 data = getPseudoBankNrFromOperand (sym);
8987 //fprintf (stderr, "symbol: %s, data=%i\n", sym, data);
8988 } else if (PCI(pc)->op == POC_MOVLB) {
8989 // get (literal) bank number from PCI(pc)->pcop->name
8990 fprintf (stderr, "%s:%d: MOVLB found: %s %s\n", __FUNCTION__, __LINE__, PCI(pc)->mnemonic, PCI(pc)->pcop->name);
8991 assert (0 && "not yet implemented - turn off banksel optimization for now");
8996 // no assigned bank could be found
8997 return UNKNOWN_BANK;
9002 /*------------------------------------------------------------------------------*/
9003 /* getEffectiveBank - resolves the currently assigned effective pseudo bank nr */
9004 /*------------------------------------------------------------------------------*/
9005 pseudoBankNr getEffectiveBank (pseudoBankNr bank)
9009 if (bank < FIRST_PSEUDO_BANK_NR) return bank;
9012 //fprintf (stderr, "%s:%d: bank=%d\n", __FUNCTION__, __LINE__, bank);
9013 data = (pseudoBank *) hTabFindByKey (coerce, bank % coerce->size, (void *) bank, &comparePtr);
9015 if (data->bank != bank)
9022 //fprintf (stderr, "%s:%d: effective bank=%d\n", __FUNCTION__, __LINE__, bank);
9026 /*------------------------------------------------------------------*/
9027 /* attachBsrInfo2pBlock - create a look-up table as to which pseudo */
9028 /* bank is selected at a given pCode */
9029 /*------------------------------------------------------------------*/
9031 /* Create a graph with pseudo banks as its nodes and switches between
9032 * these as edges (with the edge weight representing the absolute
9033 * number of BANKSELs from one to the other).
9034 * Removes redundand BANKSELs instead iff mod == 1.
9035 * BANKSELs update the pseudo BSR, labels invalidate the current BSR
9036 * value (setting it to 0=UNNKOWN), (R)CALLs also invalidate the
9038 * TODO: check ALL instructions operands if they modify BSR directly...
9040 * pb - the pBlock to annotate
9041 * mod - select either graph creation (0) or BANKSEL removal (1)
9043 unsigned int attachBsrInfo2pBlock (pBlock *pb, int mod)
9045 pCode *pc, *pc_next;
9046 unsigned int prevBSR = UNKNOWN_BANK, pseudoBSR = UNKNOWN_BANK;
9047 int isBankselect = 0;
9048 unsigned int banksels=0;
9052 pc = pic16_findNextInstruction(pb->pcHead);
9054 isBankselect = isBanksel (pc);
9055 pc_next = pic16_findNextInstruction (pc->next);
9057 if (!hasNoLabel (pc)) {
9058 // we don't know our predecessors -- assume different BSRs
9059 prevBSR = UNKNOWN_BANK;
9060 pseudoBSR = UNKNOWN_BANK;
9061 //fprintf (stderr, "invalidated by label at "); pc->print (stderr, pc);
9064 // check if this is a BANKSEL instruction
9066 pseudoBSR = getEffectiveBank (getBankFromBanksel(pc));
9067 //fprintf (stderr, "BANKSEL via "); pc->print (stderr, pc);
9069 if (prevBSR == pseudoBSR && pseudoBSR >= 0) {
9070 //fprintf (stderr, "removing redundant "); pc->print (stderr, pc);
9071 if (1 || pic16_pcode_verbose) pic16_pCodeInsertAfter (pc->prev, pic16_newpCodeCharP("removed redundant BANKSEL"));
9072 pic16_unlinkpCode (pc);
9076 addGEdge2 (getOrAddGNode (adj, NULL, prevBSR), getOrAddGNode (adj, NULL, pseudoBSR), 1, 0);
9081 if (!isBankselect && invalidatesBSR(pc)) {
9082 // check if this instruction invalidates the pseudoBSR
9083 pseudoBSR = UNKNOWN_BANK;
9084 //fprintf (stderr, "invalidated via "); pc->print (stderr, pc);
9087 prevBSR = pseudoBSR;
9094 /*------------------------------------------------------------------------------------*/
9095 /* assignToSameBank - returns 0 on success or an error code */
9096 /* 1 - common bank would be too large */
9097 /* 2 - assignment to fixed (absolute) bank not performed */
9099 /* This functions assumes that unsplittable operands are already assigned to the same */
9100 /* bank (e.g. all objects being referenced as (SYMBOL + offset) must be in the same */
9101 /* bank so that we can make sure the bytes are laid out sequentially in memory) */
9102 /* TODO: Symbols with an abslute address must be handled specially! */
9103 /*------------------------------------------------------------------------------------*/
9104 int assignToSameBank (int bank0, int bank1, int doAbs)
9106 int eff0, eff1, dummy;
9107 pseudoBank *pbank0, *pbank1;
9110 eff0 = getEffectiveBank (bank0);
9111 eff1 = getEffectiveBank (bank1);
9113 //fprintf (stderr, "%s:%d: bank0=%d/%d, bank1=%d/%d, doAbs=%d\n", __FUNCTION__, __LINE__, bank0, eff0, bank1, eff1, doAbs);
9115 // nothing to do if already same bank
9116 if (eff0 == eff1) return 0;
9118 if (!doAbs && (eff0 < FIRST_PSEUDO_BANK_NR || eff1 < FIRST_PSEUDO_BANK_NR))
9121 // ensure eff0 < eff1
9123 // swap eff0 and eff1
9132 // now assign bank eff1 to bank eff0
9133 pbank0 = (pseudoBank *) hTabFindByKey (coerce, eff0 % coerce->size, (void *)((char*)0+eff0), &comparePtr);
9135 pbank0 = Safe_calloc (1, sizeof (pseudoBank));
9136 pbank0->bank = eff0;
9139 hTabAddItemLong (&coerce, eff0 % coerce->size, (void *)((char*)0+eff0), (void *) pbank0);
9143 hitem = hTabSearch (coerce, eff1 % coerce->size);
9144 while (hitem && hitem->pkey != (void *)((char*)0+eff1))
9145 hitem = hitem->next;
9147 if (hitem) pbank1 = (pseudoBank *) hitem->item;
9150 fprintf (stderr, "bank #%d/%d & bank #%d/%d --> bank #%d: %u (%s & %s)\n", bank0, eff0, bank1, eff1,
9151 pbank0->bank, pbank0->size,
9152 getSymFromBank (eff0), getSymFromBank (eff1));
9156 if (pbank0->size + pbank1->size > MAX_COMMON_BANK_SIZE) {
9158 fprintf (stderr, "bank #%d: %u, bank #%d: %u --> bank #%d': %u > %u (%s,%s)\n",
9159 pbank0->bank, pbank0->size, pbank1->bank, pbank1->size,
9160 pbank0->bank, pbank0->size + pbank1->size, MAX_COMMON_BANK_SIZE,
9161 getSymFromBank (pbank0->bank), getSymFromBank (pbank1->bank));
9165 pbank0->size += pbank1->size;
9167 if (pbank1->ref == 0) Safe_free (pbank1);
9173 hitem->item = pbank0;
9175 hTabAddItemLong (&coerce, eff1 % coerce->size, (void *)((char*)0+eff1), (void *) pbank0);
9178 //fprintf (stderr, "%s:%d: leaving.\n", __FUNCTION__, __LINE__);
9183 /*----------------------------------------------------------------*/
9184 /* mergeGraphNodes - combines two nodes into one and modifies all */
9185 /* edges to and from the nodes accordingly */
9186 /* This method needs complete backedges, i.e. if (A,B) is an edge */
9187 /* then also (B,A) must be an edge (possibly with weight 0). */
9188 /*----------------------------------------------------------------*/
9189 void mergeGraphNodes (GraphNode *node1, GraphNode *node2)
9191 GraphEdge *edge, *backedge, *nextedge;
9195 assert (node1 && node2);
9196 assert (node1 != node2);
9198 // add all edges starting at node2 to node1
9201 nextedge = edge->next;
9203 backedge = getGEdge (node, node2);
9205 backweight = backedge->weight;
9208 // insert edges (node1,node) and (node,node1)
9209 addGEdge2 (node1, node, edge->weight, backweight);
9210 // remove edges (node, node2) and (node2, node)
9211 remGEdge (node2, node);
9212 remGEdge (node, node2);
9216 // now node2 should not be referenced by any other GraphNode...
9217 //remGNode (adj, node2->data, node2->hash);
9220 /*----------------------------------------------------------------*/
9221 /* showGraph - dump the current BANKSEL graph as a node/edge list */
9222 /*----------------------------------------------------------------*/
9223 void showGraph (Graph *g)
9227 pseudoBankNr bankNr;
9234 bankNr = getEffectiveBank (node->hash);
9235 assert (bankNr >= 0);
9236 pbank = (pseudoBank *) hTabFindByKey (coerce, bankNr % coerce->size, (void *) bankNr, &comparePtr);
9238 bankNr = pbank->bank;
9244 fprintf (stderr, "edges from %s (bank %u, size %u) to:\n", getSymFromBank (node->hash), bankNr, size);
9247 if (edge->weight > 0)
9248 fprintf (stderr, " %4u x %s\n", edge->weight, getSymFromBank (edge->node->hash));
9255 /*---------------------------------------------------------------*/
9256 /* pic16_OptimizeBanksel - remove redundant BANKSEL instructions */
9257 /*---------------------------------------------------------------*/
9258 void pic16_OptimizeBanksel ()
9260 GraphNode *node, *node1, *node1next;
9263 // needed for more effective bank assignment (needs adjusted pic16_emit_usection())
9264 GraphEdge *edge, *backedge;
9266 int maxWeight, weight, mergeMore, absMaxWeight;
9267 pseudoBankNr curr0, curr1;
9270 pseudoBankNr bankNr;
9271 char *base_symbol0, *base_symbol1;
9276 unsigned int bankselsTotal = 0, bankselsRemoved = 0;
9278 //fprintf (stderr, "%s:%s:%d: entered.\n", __FILE__, __FUNCTION__, __LINE__);
9280 if (!the_pFile || !the_pFile->pbHead) return;
9282 adj = newGraph (NULL);
9283 sym2bank = newHashTable ( 255 );
9284 bank2sym = newHashTable ( 255 );
9285 coerce = newHashTable ( 255 );
9287 // create graph of BANKSEL relationships (node = operands, edge (A,B) iff BANKSEL B follows BANKSEL A)
9288 for (pb = the_pFile->pbHead; pb; pb = pb->next) {
9289 bankselsTotal += attachBsrInfo2pBlock (pb, 0);
9293 // assign symbols with absolute addresses to their respective bank nrs
9294 set = pic16_fix_udata;
9295 for (reg = setFirstItem (set); reg; reg = setNextItem (set)) {
9296 bankNr = reg->address >> 8;
9297 node = getOrAddGNode (adj, NULL, bankNr);
9298 bankNr = (pseudoBankNr) getEffectiveBank (getPseudoBankNrFromOperand(reg->name));
9299 assignToSameBank (node->hash, bankNr, 1);
9301 assert (bankNr >= 0);
9302 pbank = (pseudoBank *) hTabFindByKey (coerce, bankNr % coerce->size, (void *) bankNr, &comparePtr);
9304 pbank = Safe_calloc (1, sizeof (pseudoBank));
9305 pbank->bank = reg->address >> 8; //FIXED_BANK;
9308 hTabAddItemLong (&coerce, bankNr % coerce->size, (void *) bankNr, pbank);
9310 assert (pbank->bank == (reg->address >> 8));
9311 pbank->bank = reg->address >> 8; //FIXED_BANK;
9313 //fprintf (stderr, "ABS: %s (%d bytes) at %x in bank %u\n", reg->name, reg->size, reg->address, bankNr);
9318 // assign operands referring to the same symbol (which is not given an absolute address) to the same bank
9319 //fprintf (stderr, "assign operands with the same symbol to the same bank\n");
9322 if (node->hash < 0) { node = node->next; continue; }
9323 base_symbol0 = getSymbolFromOperand (getSymFromBank (getEffectiveBank(node->hash)), &len0);
9326 if (node1->hash < 0) { node1 = node1->next; continue; }
9327 node1next = node1->next;
9328 base_symbol1 = getSymbolFromOperand (getSymFromBank (getEffectiveBank (node1->hash)), &len1);
9329 if (len0 == len1 && len0 > 0 && strncmp (base_symbol0, base_symbol1, len0) == 0) {
9330 // TODO: check for symbols with absolute addresses -- these might be placed across bank boundaries!
9331 //fprintf (stderr, "merging %s and %s\n", getSymFromBank (getEffectiveBank(node->hash)), getSymFromBank (getEffectiveBank(node1->hash)));
9332 if (assignToSameBank (node->hash, node1->hash, 0)) {
9333 fprintf (stderr, "%s(%d) == %s(%d)\n", base_symbol0, len0, base_symbol1, len1);
9334 assert (0 && "Could not assign a symbol to a bank!");
9336 mergeGraphNodes (node, node1);
9338 if (node->hash < node1->hash)
9339 mergeGraphNodes (node, node1);
9341 mergeGraphNodes (node1, node); // this removes node so node->next will fail...
9351 // >>> THIS ALSO NEEDS AN UPDATED pic16_emit_usection() TO REFLECT THE BANK ASSIGNMENTS <<<
9352 // assign tightly coupled operands to the same (pseudo) bank
9353 //fprintf (stderr, "assign tightly coupled operands to the same bank\n");
9361 curr0 = getEffectiveBank (node->hash);
9362 if (curr0 < 0) { node = node->next; continue; }
9365 assert (edge->src == node);
9366 backedge = getGEdge (edge->node, edge->src);
9367 weight = edge->weight + (backedge ? backedge->weight : 0);
9368 curr1 = getEffectiveBank (edge->node->hash);
9369 if (curr1 < 0) { edge = edge->next; continue; }
9371 // merging is only useful if the items are not assigned to the same bank already...
9372 if (curr0 != curr1 && weight > maxWeight) {
9373 if (maxWeight > absMaxWeight) absMaxWeight = maxWeight;
9382 if (maxWeight > 0) {
9384 fprintf (stderr, "%s:%d: merging (%4u) %d(%s) and %d(%s)\n", __FUNCTION__, __LINE__, maxWeight,
9385 max->src->hash, getSymFromBank (max->src->hash),
9386 max->node->hash, getSymFromBank (max->node->hash));
9389 node = getGNode (adj, max->src->data, max->src->hash);
9390 node1 = getGNode (adj, max->node->data, max->node->hash);
9392 if (0 == assignToSameBank (max->src->hash, max->node->hash, 0)) {
9393 if (max->src->hash < max->node->hash)
9394 mergeGraphNodes (node, node1);
9396 mergeGraphNodes (node1, node);
9398 remGEdge (node, node1);
9399 remGEdge (node1, node);
9410 // remove redundant BANKSELs
9411 //fprintf (stderr, "removing redundant BANKSELs\n");
9412 for (pb = the_pFile->pbHead; pb; pb = pb->next) {
9413 bankselsRemoved += attachBsrInfo2pBlock (pb, 1);
9418 fprintf (stderr, "display graph\n");
9423 //fprintf (stderr, "%s:%s:%d: leaving, %u/%u BANKSELs removed...\n", __FILE__, __FUNCTION__, __LINE__, bankselsRemoved, bankselsTotal);
9426 /*** END of stuff belonging to the BANKSEL optimization ***/
9430 /*** BEGIN of helpers for pCode dataflow optimizations ***/
9432 typedef unsigned int symbol_t;
9433 typedef unsigned int valnum_t;
9434 //typedef unsigned int hash_t;
9437 #define INT_TO_PTR(x) (((char *) 0) + (x))
9441 #define PTR_TO_INT(x) (((char *)(x)) - ((char *) 0))
9444 static int pic16_regIsLocal (regs *r);
9445 static int pic16_safepCodeRemove (pCode *pc, char *comment);
9448 static unsigned int pic16_df_removed_pcodes = 0;
9449 static unsigned int pic16_df_saved_bytes = 0;
9450 static unsigned int df_findall_sameflow = 0;
9451 static unsigned int df_findall_otherflow = 0;
9452 static unsigned int df_findall_in_vals = 0;
9454 static void pic16_df_stats () {
9456 if (pic16_debug_verbose || pic16_pcode_verbose) {
9457 fprintf (stderr, "PIC16: dataflow analysis removed %u instructions (%u bytes)\n", pic16_df_removed_pcodes, pic16_df_saved_bytes);
9458 fprintf (stderr, "findAll: same flow %u (%u in_vals), other flow %u\n", df_findall_sameflow, df_findall_in_vals, df_findall_otherflow);
9459 //pic16_df_removed_pcodes = pic16_df_saved_bytes = 0;
9463 /* Remove a pCode iff possible:
9464 * - previous pCode is no SKIP
9466 * Returns 1 iff the pCode has been removed, 0 otherwise. */
9467 static int pic16_safepCodeUnlink (pCode *pc, char *comment) {
9468 pCode *pcprev, *pcnext;
9469 char buf[256], *total=NULL;
9472 if (!comment) comment = "=DF= pCode removed by pic16_safepCodeUnlink";
9474 pcprev = pic16_findPrevInstruction (pc->prev);
9475 pcnext = pic16_findNextInstruction (pc->next);
9477 /* move labels to next instruction (if possible) */
9478 if (PCI(pc)->label && !pcnext) return 0;
9480 /* if this is a SKIP with side-effects -- do not remove */
9481 /* XXX: might try to replace this one with the side-effect only version */
9483 && ((PCI(pc)->outCond & (PCC_REGISTER | PCC_W)) != 0))
9486 switch (PCI(pc)->op)
9490 newpc = pic16_newpCode(POC_INCF, pic16_pCodeOpCopy( PCI(pc)->pcop ) );
9491 pic16_pCodeReplace( pc, newpc );
9495 newpc = pic16_newpCode(POC_INCFW, pic16_pCodeOpCopy( PCI(pc)->pcop ) );
9496 pic16_pCodeReplace( pc, newpc );
9501 newpc = pic16_newpCode(POC_INCF, pic16_pCodeOpCopy( PCI(pc)->pcop ) );
9502 pic16_pCodeReplace( pc, newpc );
9506 newpc = pic16_newpCode(POC_INCF, pic16_pCodeOpCopy( PCI(pc)->pcop ) );
9507 pic16_pCodeReplace( pc, newpc );
9516 /* if previous instruction is a skip -- do not remove */
9517 if (pcprev && isPCI_SKIP(pcprev)) {
9518 if (!pic16_safepCodeUnlink (pcprev, "=DF= removed now unused SKIP")) {
9519 /* preceeding SKIP could not be removed -- keep this instruction! */
9524 if (PCI(pc)->label) {
9525 //fprintf (stderr, "%s: moving label(s)\n", __FUNCTION__);
9526 //pc->print (stderr, pc);
9527 PCI(pcnext)->label = pic16_pBranchAppend (PCI(pc)->label, PCI(pcnext)->label);
9528 PCI(pc)->label = NULL;
9531 /* update statistics */
9532 pic16_df_removed_pcodes++;
9533 if (isPCI(pc)) pic16_df_saved_bytes += PCI(pc)->isize;
9535 /* remove the pCode */
9536 pic16_pCode2str (buf, 256, pc);
9537 //fprintf (stderr, "%s: removing pCode: %s\n", __FUNCTION__, buf);
9538 if (0 || pic16_debug_verbose || pic16_pcode_verbose) {
9539 len = strlen (buf) + strlen (comment) + 10;
9540 total = (char *) Safe_malloc (len);
9541 SNPRINTF (total, len, "%s: %s", comment, buf);
9542 pic16_pCodeInsertAfter (pc, pic16_newpCodeCharP(total));
9546 /* actually unlink it from the pBlock -- also remove from to/from lists */
9547 pic16_pCodeUnlink (pc);
9549 /* remove the pCode -- release registers */
9552 /* report success */
9557 /* ======================================================================== */
9558 /* === SYMBOL HANDLING ==================================================== */
9559 /* ======================================================================== */
9561 static hTab *map_strToSym = NULL; /** (char *) --> symbol_t */
9562 static hTab *map_symToStr = NULL; /** symbol_t -> (char *) */
9563 static symbol_t nextSymbol = 0x2000; /** next symbol_t assigned to the next generated symbol */
9565 /** Calculate a hash for a given string.
9566 * If len == 0 the string is assumed to be NUL terminated. */
9567 static hash_t symbolHash (const char *str, unsigned int len) {
9571 hash = (hash << 2) ^ *str;
9576 hash = (hash << 2) ^ *str;
9583 /** Return 1 iff strings v1 and v2 are identical. */
9584 static int symcmp (const void *v1, const void *v2) {
9585 return !strcmp ((const char *) v1, (const char *) v2);
9588 /** Return 1 iff pointers v1 and v2 are identical. */
9589 static int ptrcmp (const void *v1, const void *v2) {
9593 enum { SPO_WREG=0x1000,
9633 /* Return the unique symbol_t for the given string. */
9634 static symbol_t symFromStr (const char *str) {
9639 if (!map_symToStr) {
9641 struct { char *name; symbol_t sym; } predefsyms[] = {
9643 {"STATUS", SPO_STATUS},
9644 {"PRODL", SPO_PRODL},
9645 {"PRODH", SPO_PRODH},
9646 {"INDF0", SPO_INDF0},
9647 {"POSTDEC0", SPO_POSTDEC0},
9648 {"POSTINC0", SPO_POSTINC0},
9649 {"PREINC0", SPO_PREINC0},
9650 {"PLUSW0", SPO_PLUSW0},
9651 {"INDF1", SPO_INDF1},
9652 {"POSTDEC1", SPO_POSTDEC1},
9653 {"POSTINC1", SPO_POSTINC1},
9654 {"PREINC1", SPO_PREINC1},
9655 {"PLUSW1", SPO_PLUSW1},
9656 {"INDF2", SPO_INDF2},
9657 {"POSTDEC2", SPO_POSTDEC2},
9658 {"POSTINC2", SPO_POSTINC2},
9659 {"PREINC2", SPO_PREINC2},
9660 {"PLUSW2", SPO_PLUSW2},
9661 {"STKPTR", SPO_STKPTR},
9666 {"FSR0L", SPO_FSR0L},
9667 {"FSR0H", SPO_FSR0H},
9668 {"FSR1L", SPO_FSR1L},
9669 {"FSR1H", SPO_FSR1H},
9670 {"FSR2L", SPO_FSR2L},
9671 {"FSR2H", SPO_FSR2H},
9673 {"PCLATH", SPO_PCLATH},
9674 {"PCLATU", SPO_PCLATU},
9675 {"TABLAT", SPO_TABLAT},
9676 {"TBLPTRL", SPO_TBLPTRL},
9677 {"TBLPTRH", SPO_TBLPTRH},
9678 {"TBLPTRU", SPO_TBLPTRU},
9682 map_strToSym = newHashTable (128);
9683 map_symToStr = newHashTable (128);
9685 for (i=0; predefsyms[i].name; i++) {
9688 /* enter new symbol */
9689 sym = predefsyms[i].sym;
9690 name = predefsyms[i].name;
9691 res = Safe_strdup (name);
9692 hash = symbolHash (name, 0);
9694 hTabAddItemLong (&map_strToSym, hash, res, INT_TO_PTR(sym));
9695 hTabAddItemLong (&map_symToStr, sym % map_symToStr->size, INT_TO_PTR(sym), res);
9699 hash = symbolHash (str, 0) % map_strToSym->size;
9701 /* find symbol in table */
9702 sym = PTR_TO_INT(hTabFindByKey (map_strToSym, hash, str, &symcmp));
9704 //fprintf (stderr, "found symbol %x for %s\n", sym, str);
9708 /* enter new symbol */
9710 res = Safe_strdup (str);
9712 hTabAddItemLong (&map_strToSym, hash, res, INT_TO_PTR(sym));
9713 hTabAddItemLong (&map_symToStr, sym % map_symToStr->size, INT_TO_PTR(sym), res);
9715 //fprintf (stderr, "created symbol %x for %s\n", sym, res);
9721 static const char *strFromSym (symbol_t sym) {
9722 return (const char *) hTabFindByKey (map_symToStr, sym % map_symToStr->size, INT_TO_PTR(sym), &ptrcmp);
9726 /* ======================================================================== */
9727 /* === DEFINITION MAP HANDLING ============================================ */
9728 /* ======================================================================== */
9730 /* A defmap provides information about which symbol is defined by which pCode.
9731 * The most recent definitions are prepended to the list, so that the most
9732 * recent definition can be found by forward scanning the list.
9733 * pc2: MOVFF r0x00, r0x01
9735 * head --> ("r0x01",pc1,42) --> ("STATUS",pc1,44) --> ("r0x01",pc2,28) --> NULL
9737 * We attach one defmap to each flow object, and each pCode will occur at
9738 * least once in its flow's defmap (maybe defining the 0 symbol). This can be
9739 * used to find definitions for a pCode in its own defmap that precede pCode.
9742 typedef struct defmap_s {
9743 symbol_t sym; /** symbol this item refers to */
9746 unsigned int in_mask:8; /** mask leaving in accessed bits */
9747 unsigned int mask:8; /** mask leaving in modified bits (if isWrite) */
9748 int isRead:1; /** sym/mask is read */
9749 int isWrite:1; /** sym/mask is written */
9753 pCode *pc; /** pCode this symbol is refrenced at */
9754 valnum_t in_val; /** valnum_t of symbol's previous value (the one read at pc) */
9755 valnum_t val; /** new unique number for this value (if isWrite) */
9756 struct defmap_s *prev, *next; /** link to previous an next definition */
9759 static defmap_t *defmap_free = NULL; /** list of unused defmaps */
9760 static int defmap_free_count = 0; /** number of released defmap items */
9762 /* Returns a defmap_t with the specified data; this will be the new list head.
9763 * next - pointer to the current list head */
9764 static defmap_t *newDefmap (symbol_t sym, int in_mask, int mask, int isRead, int isWrite, pCode *pc, valnum_t val, defmap_t *next) {
9769 defmap_free = map->next;
9770 --defmap_free_count;
9772 map = (defmap_t *) Safe_calloc (1, sizeof (defmap_t));
9775 map->acc.access.in_mask = (isRead ? (in_mask ? in_mask : 0xFF) : 0x00);
9776 map->acc.access.mask = (isWrite ? (mask ? mask : 0xFF) : 0x00);
9777 map->acc.access.isRead = (isRead != 0);
9778 map->acc.access.isWrite = (isWrite != 0);
9781 map->val = (isWrite ? val : 0);
9784 if (next) next->prev = map;
9789 /* Returns a copy of the single defmap item. */
9790 static defmap_t *copyDefmap (defmap_t *map) {
9791 defmap_t *res = (defmap_t *) Safe_malloc (sizeof (defmap_t));
9792 memcpy (res, map, sizeof (defmap_t));
9798 /* Insert a defmap item after the specified one. */
9799 static int defmapInsertAfter (defmap_t *ref, defmap_t *newItem) {
9800 if (!ref || !newItem) return 1;
9802 newItem->next = ref->next;
9803 newItem->prev = ref;
9804 ref->next = newItem;
9805 if (newItem->next) newItem->next->prev = newItem;
9810 /* Check whether item (or an identical one) is already in the chain and add it if neccessary.
9811 * item is copied before insertion into chain and therefore left untouched.
9812 * Returns 1 iff the item has been inserted into the list, 0 otherwise. */
9813 static int defmapAddCopyIfNew (defmap_t **head, defmap_t *item) {
9816 while (dummy && (dummy->sym != item->sym
9817 || dummy->pc != item->pc
9818 || dummy->acc.accessmethod != item->acc.accessmethod
9819 || dummy->val != item->val
9820 || dummy->in_val != item->in_val)) {
9821 dummy = dummy->next;
9824 /* item already present? */
9825 if (dummy) return 0;
9827 /* otherwise: insert copy of item */
9828 dummy = copyDefmap (item);
9829 dummy->next = *head;
9830 if (*head) (*head)->prev = dummy;
9836 /* Releases a defmap. This also removes the map from its chain -- update the head manually! */
9837 static void deleteDefmap (defmap_t *map) {
9840 /* unlink from chain -- fails for the first item (head is not updated!) */
9841 if (map->next) map->next->prev = map->prev;
9842 if (map->prev) map->prev->next = map->next;
9845 memset (map, 0, sizeof (defmap_t));
9847 /* save for future use */
9848 map->next = defmap_free;
9850 ++defmap_free_count;
9853 /* Release all defmaps referenced from map. */
9854 static void deleteDefmapChain (defmap_t **_map) {
9855 defmap_t *map, *next;
9861 /* find list head */
9862 while (map && map->prev) map = map->prev;
9864 /* delete all items */
9874 /* Free all defmap items. */
9875 static void freeDefmap (defmap_t **_map) {
9883 /* find list head */
9884 while (map->prev) map = map->prev;
9886 /* release all items */
9896 /* Returns the most recent definition for the given symbol preceeding pc.
9897 * If no definition is found, NULL is returned.
9898 * If pc == NULL the whole list is scanned. */
9899 static defmap_t *defmapFindDef (defmap_t *map, symbol_t sym, pCode *pc) {
9900 defmap_t *curr = map;
9903 /* skip all definitions up to pc */
9904 while (curr && (curr->pc != pc)) curr = curr->next;
9906 /* pc not in the list -- scan the whole list for definitions */
9908 fprintf (stderr, "pc %p not found in defmap -- scanning whole list for symbol '%s'\n", pc, strFromSym (sym));
9911 /* skip all definitions performed by pc */
9912 while (curr && (curr->pc == pc)) curr = curr->next;
9916 /* find definition for sym */
9917 while (curr && (!curr->acc.access.isWrite || (curr->sym != sym))) {
9925 /* Returns the first use (read) of the given symbol AFTER pc.
9926 * If no such use is found, NULL is returned.
9927 * If pc == NULL the whole list is scanned. */
9928 static defmap_t *defmapFindUse (defmap_t *map, symbol_t sym, pCode *pc) {
9929 defmap_t *curr = map, *prev = NULL;
9932 /* skip all definitions up to pc */
9933 while (curr && (curr->pc != pc)) { prev = curr; curr = curr->next; }
9935 /* pc not in the list -- scan the whole list for definitions */
9937 //fprintf (stderr, "pc %p not found in defmap -- scanning whole list for symbol '%s'\n", pc, strFromSym (sym));
9941 /* find end of list */
9942 while (curr && curr->next) curr = curr->next;
9945 /* find use of sym (scan list backwards) */
9946 while (curr && (!curr->acc.access.isRead || (curr->sym != sym))) curr = curr->prev;
9952 /* Return the defmap entry for sym AT pc.
9953 * If none is found, NULL is returned.
9954 * If more than one entry is found an assertion is triggered. */
9955 static defmap_t *defmapCurr (defmap_t *map, symbol_t sym, pCode *pc) {
9956 defmap_t *res = NULL;
9958 /* find entries for pc */
9959 while (map && map->pc != pc) map = map->next;
9961 /* find first entry for sym @ pc */
9962 while (map && map->pc == pc && map->sym != sym) map = map->next;
9964 /* no entry found */
9965 if (!map) return NULL;
9967 /* check for more entries */
9970 while (map && map->pc == pc) {
9971 /* more than one entry for sym @ pc found? */
9972 assert (map->sym != sym);
9976 /* return single entry for sym @ pc */
9980 /* Modifies the definition of sym at pCode to newval.
9981 * Returns 0 on success, 1 if no definition of sym in pc has been found.
9983 static int defmapUpdate (defmap_t *map, symbol_t sym, pCode *pc, valnum_t newval) {
9986 /* find definitions of pc */
9987 while (m && m->pc != pc) m = m->next;
9989 /* find definition of sym at pc */
9990 while (m && m->pc == pc && (!m->acc.access.isWrite || (m->sym != sym))) m = m->next;
9992 /* no definition found */
9998 /* update following uses of sym */
9999 while (m && m->pc == pc) m = m->prev;
10001 if (m->sym == sym) {
10002 m->in_val = newval;
10003 if (m->acc.access.isWrite) m = NULL;
10005 if (m) m = m->prev;
10011 /* ======================================================================== */
10012 /* === STACK ROUTINES ===================================================== */
10013 /* ======================================================================== */
10015 typedef struct stack_s {
10017 struct stack_s *next;
10020 typedef stackitem_t *dynstack_t;
10021 static stackitem_t *free_stackitems = NULL;
10023 /* Create a stack with one item. */
10024 static dynstack_t *newStack () {
10025 dynstack_t *s = (dynstack_t *) Safe_malloc (sizeof (dynstack_t));
10030 /* Remove a stack -- its items are only marked free. */
10031 static void deleteStack (dynstack_t *s) {
10037 i->next = free_stackitems;
10038 free_stackitems = i;
10043 /* Release all stackitems. */
10044 static void releaseStack () {
10047 while (free_stackitems) {
10048 i = free_stackitems->next;
10049 Safe_free(free_stackitems);
10050 free_stackitems = i;
10054 static void stackPush (dynstack_t *stack, void *data) {
10057 if (free_stackitems) {
10058 i = free_stackitems;
10059 free_stackitems = free_stackitems->next;
10061 i = (stackitem_t *) Safe_calloc (1, sizeof (stackitem_t));
10068 static void *stackPop (dynstack_t *stack) {
10072 if (stack && *stack) {
10073 data = (*stack)->data;
10075 *stack = (*stack)->next;
10076 i->next = free_stackitems;
10077 free_stackitems = i;
10085 static int stackContains (dynstack_t *s, void *data) {
10090 if (i->data == data) return 1;
10099 static int stackIsEmpty (dynstack_t *s) {
10100 return (*s == NULL);
10109 static state_t *newState (pCodeFlow *flow, defmap_t *lastdef) {
10110 state_t *s = (state_t *) Safe_calloc (1, sizeof (state_t));
10112 s->lastdef = lastdef;
10116 static void deleteState (state_t *s) {
10120 static int stateIsNew (state_t *state, dynstack_t *todo, dynstack_t *done) {
10123 /* scan working list for state */
10127 /* is i == state? -- state not new */
10128 if ((((state_t *) (i->data))->flow == state->flow) && (((state_t *) (i->data))->lastdef == state->lastdef)) return 0;
10136 /* is i == state? -- state not new */
10137 if ((((state_t *) (i->data))->flow == state->flow) && (((state_t *) (i->data))->lastdef == state->lastdef)) return 0;
10142 /* not found -- state is new */
10146 static inline valnum_t newValnum ();
10148 const char *pic16_pBlockGetFunctionName (pBlock *pb) {
10151 if (!pb) return "<unknown function>";
10153 pc = pic16_findNextpCode (pb->pcHead, PC_FUNCTION);
10154 if (pc && isPCF(pc)) return PCF(pc)->fname;
10155 else return "<unknown function>";
10158 static defmap_t *pic16_pBlockAddInval (pBlock *pb, symbol_t sym) {
10162 pcfl = PCI(pic16_findNextInstruction (pb->pcHead))->pcflow;
10164 /* find initial value (assigning pc == NULL) */
10165 map = PCFL(pcfl)->in_vals;
10166 while (map && map->sym != sym) map = map->next;
10168 /* initial value already present? */
10170 //fprintf (stderr, "found init value for sym %s (%x): %u\n", strFromSym(sym), sym, map->val);
10174 /* create a new initial value */
10175 map = newDefmap (sym, 0x00, 0xff, 0, 1, NULL, newValnum(), PCFL(pcfl)->in_vals);
10176 PCFL(pcfl)->in_vals = map;
10177 //fprintf (stderr, "Created init value for sym %s (%x): %u\n", strFromSym(sym), sym, map->val);
10181 /* insert map as last item in pcfl's defmap */
10182 if (!prev) prev = PCFL(pcfl)->defmap;
10184 PCFL(pcfl)->defmap = map;
10186 while (prev->next) prev = prev->next;
10195 /* Find all reaching definitions for sym at pc.
10196 * A new (!) list of definitions is returned.
10197 * Returns the number of reaching definitions found.
10198 * The defining defmap entries are returned in *chain.
10200 static int defmapFindAll (symbol_t sym, pCode *pc, defmap_t **chain) {
10205 pCodeFlowLink *succ;
10207 dynstack_t *todo; /** stack of state_t */
10208 dynstack_t *done; /** stack of state_t */
10210 int firstState, n_defs;
10212 assert (pc && isPCI(pc) && PCI(pc)->pcflow);
10215 /* initialize return list */
10218 /* wildcard symbol? */
10219 if (!sym) return 0;
10221 //fprintf (stderr, "Searching definition of sym %s(%x) @ pc %p(%p)\n", strFromSym(sym), sym, pc, pc->pb);
10223 map = PCI(pc)->pcflow->defmap;
10225 res = defmapFindDef (map, sym, pc);
10226 //if (res) fprintf (stderr, "found def in own flow @ pc %p\n", res->pc);
10228 #define USE_PRECALCED_INVALS 1
10229 #if USE_PRECALCED_INVALS
10230 if (!res && PCI(pc)->pcflow->in_vals) {
10231 res = defmapFindDef (PCI(pc)->pcflow->in_vals, sym, NULL);
10233 //fprintf (stderr, "found def in init values\n");
10234 df_findall_in_vals++;
10240 // found a single definition (in pc's flow)
10241 //fprintf (stderr, "unique definition for %s @ %p found @ %p (val: %x)\n", strFromSym(sym), pc, res->pc, res->val);
10242 defmapAddCopyIfNew (chain, res);
10243 df_findall_sameflow++;
10247 #if USE_PRECALCED_INVALS
10249 defmapAddCopyIfNew (chain, pic16_pBlockAddInval (pc->pb, sym));
10255 #define FORWARD_FLOW_ANALYSIS 1
10256 #if defined FORWARD_FLOW_ANALYSIS && FORWARD_FLOW_ANALYSIS
10257 /* no definition found in pc's flow preceeding pc */
10258 todo = newStack ();
10259 done = newStack ();
10260 n_defs = 0; firstState = 1;
10261 stackPush (todo, newState (PCI(pic16_findNextInstruction(pc->pb->pcHead))->pcflow, res));
10263 while (!stackIsEmpty (todo)) {
10264 state = (state_t *) stackPop (todo);
10265 stackPush (done, state);
10266 curr = state->flow;
10267 res = state->lastdef;
10268 //fprintf (stderr, "searching def of sym %s in pcFlow %p (lastdef %x @ %p)\n", strFromSym(sym), curr, res ? res->val : 0, res ? res->pc : NULL);
10270 /* there are no definitions BEFORE pc in pc's flow (see above) */
10271 if (curr == PCI(pc)->pcflow) {
10273 //fprintf (stderr, "symbol %s(%x) might be used uninitialized at %p\n", strFromSym(sym), sym, pc);
10274 res = pic16_pBlockAddInval (pc->pb, sym);
10275 if (defmapAddCopyIfNew (chain, res)) n_defs++;
10278 //fprintf (stderr, "reaching definition for %s @ %p found @ %p (val: %x)\n", strFromSym(sym), pc, res->pc, res->val);
10279 if (defmapAddCopyIfNew (chain, res)) n_defs++;
10283 /* save last definition of sym in this flow as initial def in successors */
10284 res = defmapFindDef (curr->defmap, sym, NULL);
10285 if (!res) res = state->lastdef;
10287 /* add successors to working list */
10288 state = newState (NULL, NULL);
10289 succ = (pCodeFlowLink *) setFirstItem (curr->to);
10291 //fprintf (stderr, " %p --> %p with %x\n", curr, succ->pcflow, res ? res->val : 0);
10292 state->flow = succ->pcflow;
10293 state->lastdef = res;
10294 if (stateIsNew (state, todo, done)) {
10295 stackPush (todo, state);
10296 state = newState (NULL, NULL);
10298 succ = (pCodeFlowLink *) setNextItem (curr->to);
10300 deleteState (state);
10303 #else // !FORWARD_FLOW_ANALYSIS
10305 /* no definition found in pc's flow preceeding pc */
10306 todo = newStack ();
10307 done = newStack ();
10308 n_defs = 0; firstState = 1;
10309 stackPush (todo, newState (PCI(pc)->pcflow, res));
10311 while (!stackIsEmpty (todo)) {
10312 state = (state_t *) stackPop (todo);
10313 curr = state->flow;
10317 /* only check predecessor flows */
10319 /* get (last) definition of sym in this flow */
10320 res = defmapFindDef (curr->defmap, sym, NULL);
10324 /* definition found */
10325 //fprintf (stderr, "reaching definition for %s @ %p found @ %p (val: %x)\n", strFromSym(sym), pc, res->pc, res->val);
10326 if (defmapAddCopyIfNew (chain, res)) n_defs++;
10328 /* no definition found -- check predecessor flows */
10329 state = newState (NULL, NULL);
10330 succ = (pCodeFlowLink *) setFirstItem (curr->from);
10332 /* if no flow predecessor available -- sym might be uninitialized */
10334 //fprintf (stder, "sym %s might be used uninitialized at %p\n", strFromSym (sym), pc);
10335 res = newDefmap (sym, 0xff, 0, 1, NULL, 0, *chain);
10336 if (defmapAddCopyIfNew (chain, res)) n_defs++;
10337 deleteDefmap (res); res = NULL;
10341 //fprintf (stderr, " %p --> %p with %x\n", curr, succ->pcflow, res ? res->val : 0);
10342 state->flow = succ->pcflow;
10343 state->lastdef = res;
10344 if (stateIsNew (state, todo, done)) {
10345 stackPush (todo, state);
10346 state = newState (NULL, NULL);
10348 succ = (pCodeFlowLink *) setNextItem (curr->from);
10350 deleteState (state);
10356 /* clean up done stack */
10357 while (!stackIsEmpty(done)) {
10358 deleteState ((state_t *) stackPop (done));
10360 deleteStack (done);
10362 /* return number of items in result set */
10364 //fprintf (stderr, "sym %s might be used uninitialized at %p\n", strFromSym (sym), pc);
10365 } else if (n_defs == 1) {
10367 //fprintf (stderr, "sym %s at %p always defined as %x @ %p\n", strFromSym(sym), pc, (*chain)->val, (*chain)->pc);
10368 } else if (n_defs > 0) {
10369 //fprintf (stderr, "%u definitions for sym %s at %p found:\n", n_defs, strFromSym(sym), pc);
10373 fprintf (stderr, " as %4x @ %p\n", res->val, res->pc);
10378 //fprintf (stderr, "%u definitions for sym %s at %p found\n", n_defs, strFromSym(sym), pc);
10379 df_findall_otherflow++;
10383 /* ======================================================================== */
10384 /* === VALUE NUMBER HANDLING ============================================== */
10385 /* ======================================================================== */
10387 static valnum_t nextValnum = 0x1000;
10388 static hTab *map_symToValnum = NULL;
10390 /** Return a new value number. */
10391 static inline valnum_t newValnum () {
10392 return (nextValnum += 4);
10395 static valnum_t valnumFromStr (const char *str) {
10400 sym = symFromStr (str);
10402 if (!map_symToValnum) {
10403 map_symToValnum = newHashTable (128);
10406 /* literal already known? */
10407 res = hTabFindByKey (map_symToValnum, sym % map_symToValnum->size, INT_TO_PTR(sym), &ptrcmp);
10409 /* return existing valnum */
10410 if (res) return (valnum_t) PTR_TO_INT(res);
10412 /* create new valnum */
10414 hTabAddItemLong (&map_symToValnum, sym % map_symToValnum->size, INT_TO_PTR(sym), INT_TO_PTR(val));
10415 //fprintf (stderr, "NEW VALNUM %x for symbol %s\n", val, str);
10419 /* Create a valnum for a literal. */
10420 static valnum_t valnumFromLit (unsigned int lit) {
10421 return ((valnum_t) 0x100 + (lit & 0x0FF));
10424 /* Return the (positive) literal value represented by val
10425 * or -1 iff val is no known literal's valnum. */
10426 static int litFromValnum (valnum_t val) {
10427 if (val >= 0x100 && val < 0x200) {
10428 /* valnum is a (known) literal */
10429 return val & 0x00FF;
10431 /* valnum is not a known literal */
10437 /* Sanity check - all flows in a block must be reachable from initial flow. */
10438 static int verifyAllFlowsReachable (pBlock *pb) {
10444 pCodeFlowLink *succ;
10447 //fprintf (stderr, "%s - started for %s.\n" ,__FUNCTION__, pic16_pBlockGetFunctionName (pb));
10450 flowInBlock = NULL;
10452 /* mark initial flow as reached (and "not needs to be reached") */
10453 pc = pic16_findNextpCode (pb->pcHead, PC_FLOW);
10455 addSetHead (&reached, pc);
10456 addSetHead (&checked, pc);
10458 /* mark all further flows in block as "need to be reached" */
10461 if (isPCI(pc)) addSetIfnotP (&flowInBlock, PCI(pc)->pcflow);
10462 pc = pic16_findNextInstruction (pc->next);
10465 while (reached && (pcfl = (pCodeFlow *)indexSet (reached, 0)) != NULL) {
10466 /* mark as reached and "not need to be reached" */
10467 deleteSetItem (&reached, pcfl);
10468 //fprintf (stderr, "%s - checking %p\n" ,__FUNCTION__, pcfl);
10470 /* flow is no longer considered unreachable */
10471 deleteSetItem (&flowInBlock, pcfl);
10473 for (succ = setFirstItem (pcfl->to); succ; succ = setNextItem (pcfl->to)) {
10474 if (!isinSet (checked, succ->pcflow)) {
10475 /* flow has never been reached before */
10476 addSetHead (&reached, succ->pcflow);
10477 addSetHead (&checked, succ->pcflow);
10482 //fprintf (stderr, "%s - finished\n", __FUNCTION__);
10484 /* by now every flow should have been reached
10485 * --> flowInBlock should be empty */
10486 res = (flowInBlock == NULL);
10490 fprintf (stderr, "not all flows reached in %s:\n", pic16_pBlockGetFunctionName (pb));
10491 while (flowInBlock) {
10492 pcfl = indexSet (flowInBlock, 0);
10493 fprintf (stderr, "not reached: flow %p\n", pcfl);
10494 deleteSetItem (&flowInBlock, pcfl);
10500 deleteSet (&reached);
10501 deleteSet (&flowInBlock);
10502 deleteSet (&checked);
10504 /* if we reached every flow, succ is NULL by now... */
10505 //assert (res); // will fire on unreachable code...
10510 /* Checks a flow for accesses to sym AFTER pc.
10512 * Returns -1 if the symbol is read in this flow (before redefinition),
10513 * returns 0 if the symbol is redefined in this flow or
10514 * returns a mask [0x01 -- 0xFF] indicating the bits still alive after this flow.
10516 int pic16_isAliveInFlow (symbol_t sym, int mask, pCodeFlow *pcfl, pCode *pc) {
10517 defmap_t *map, *mappc;
10519 /* find pc or start of definitions */
10520 map = pcfl->defmap;
10521 while (map && (map->pc != pc) && map->next) map = map->next;
10522 /* if we found pc -- ignore it */
10523 while (map && map->pc == pc) map = map->prev;
10525 /* scan list backwards (first definition first) */
10526 while (map && mask) {
10527 // if (map->sym == sym) {
10528 //fprintf (stderr, "%s: accessing sym %s in pc %p/map %p\n", __FUNCTION__, strFromSym(sym), map->pc, map);
10530 /* scan list for reads at this pc first */
10531 while (map && map->pc == mappc->pc) {
10532 /* is the symbol (partially) read? */
10533 if ((map->sym == sym) && (map->acc.access.isRead && ((map->acc.access.in_mask & mask) != 0))) {
10534 //if (sym != SPO_STATUS) fprintf (stderr, "%s: symbol %s read at pc %p\n", __FUNCTION__, strFromSym (sym), map->pc);
10541 while (map && map->pc == mappc->pc) {
10542 /* honor (partial) redefinitions of sym */
10543 if ((map->sym == sym) && (map->acc.access.isWrite)) {
10544 mask &= ~map->acc.access.mask;
10545 //if (sym != SPO_STATUS) fprintf (stderr, "%s: symbol %s redefined at pc %p, alive mask: %x\n", __FUNCTION__, strFromSym (sym), map->pc, mask);
10550 /* map already points to the first defmap for the next pCode */
10551 //map = mappc->prev;
10554 /* the symbol is not completely redefined in this flow and not accessed -- symbol
10555 * is still alive; return the appropriate mask of alive bits */
10559 /* Check whether a symbol is alive (AFTER pc). */
10560 static int pic16_isAlive (symbol_t sym, pCode *pc) {
10563 dynstack_t *todo, *done;
10566 pCodeFlowLink *succ;
10570 assert (isPCI(pc));
10571 pcfl = PCI(pc)->pcflow;
10572 map = pcfl->defmap;
10574 todo = newStack ();
10575 done = newStack ();
10577 state = newState (pcfl, (defmap_t *) INT_TO_PTR(mask));
10578 stackPush (todo, state);
10581 while (!stackIsEmpty (todo)) {
10582 state = (state_t *) stackPop (todo);
10583 pcfl = state->flow;
10584 mask = PTR_TO_INT(state->lastdef);
10585 if (visit) stackPush (done, state); else deleteState(state);
10586 //fprintf (stderr, "%s: checking flow %p for symbol %s (%x)/%x\n", __FUNCTION__, pcfl, strFromSym(sym), sym, mask);
10587 // make sure flows like A(i1,i2,pc,i3,...) --> A with pc reading and writing sym are handled correctly!
10588 mask = pic16_isAliveInFlow (sym, mask, pcfl, visit == 0 ? pc : NULL);
10591 /* symbol is redefined in flow before use -- not alive in this flow (maybe in others?) */
10592 if (mask == 0) continue;
10594 /* symbol is (partially) read before redefinition in flow */
10595 if (mask == -1) break;
10597 /* symbol is neither read nor completely redefined -- check successor flows */
10598 for (succ = setFirstItem(pcfl->to); succ; succ = setNextItem (pcfl->to)) {
10599 state = newState (succ->pcflow, (defmap_t *) INT_TO_PTR(mask));
10600 if (stateIsNew (state, todo, done)) {
10601 stackPush (todo, state);
10603 deleteState (state);
10608 while (!stackIsEmpty (todo)) deleteState ((state_t *) stackPop (todo));
10609 while (!stackIsEmpty (done)) deleteState ((state_t *) stackPop (done));
10611 /* symbol is read in at least one flow -- is alive */
10612 if (mask == -1) return 1;
10614 /* symbol is read in no flow */
10618 /* Returns whether access to the given symbol has side effects. */
10619 static int pic16_symIsSpecial (symbol_t sym) {
10620 //fprintf (stderr, "%s: sym=%x\n", __FUNCTION__, sym);
10640 /* no special effects known */
10647 /* Check whether a register should be considered local (to the current function) or not. */
10648 static int pic16_regIsLocal (regs *r) {
10651 if (r->type == REG_TMP) return 1;
10653 sym = symFromStr (r->name);
10656 case SPO_FSR0L: // used in ptrget/ptrput
10657 case SPO_FSR0H: // ... as well
10658 case SPO_FSR1L: // used as stack pointer... (so not really local but shared among function calls)
10659 case SPO_FSR1H: // ... as well
10660 case SPO_FSR2L: // used as frame pointer
10661 case SPO_FSR2H: // ... as well
10662 case SPO_PRODL: // used to return values from functions
10663 case SPO_PRODH: // ... as well
10664 /* these registers (and some more...) are considered local */
10668 /* for unknown regs: check is marked local, leave if not */
10672 //fprintf (stderr, "%s: non-local reg used: %s\n", __FUNCTION__, r->name);
10678 /* if in doubt, assume non-local... */
10682 /* Check all symbols touched by pc whether their newly assigned values are read.
10683 * Returns 0 if no symbol is used later on, 1 otherwise. */
10684 static int pic16_pCodeIsAlive (pCode *pc) {
10685 pCodeInstruction *pci;
10686 defmap_t *map, *lastpc;
10689 /* we can only handle PCIs */
10690 if (!isPCI(pc)) return 1;
10692 //pc->print (stderr, pc);
10695 assert (pci && pci->pcflow && pci->pcflow->defmap);
10697 /* NEVER remove instructions with implicit side effects */
10700 case POC_TBLRD_POSTINC: /* modify TBLPTRx */
10701 case POC_TBLRD_POSTDEC:
10702 case POC_TBLRD_PREINC:
10703 case POC_TBLWT: /* modify program memory */
10704 case POC_TBLWT_POSTINC: /* modify TBLPTRx */
10705 case POC_TBLWT_POSTDEC:
10706 case POC_TBLWT_PREINC:
10707 case POC_CLRWDT: /* clear watchdog timer */
10708 case POC_PUSH: /* should be safe to remove though... */
10709 case POC_POP: /* should be safe to remove though... */
10714 //fprintf (stderr, "%s: instruction with implicit side effects not removed: %s\n", __FUNCTION__, pci->mnemonic);
10718 /* no special instruction */
10722 /* prevent us from removing assignments to non-local variables */
10724 if (PCI(pc)->outCond & PCC_REGISTER) checkreg = pic16_getRegFromInstruction (pc);
10725 else if (PCI(pc)->outCond & PCC_REGISTER2) checkreg = pic16_getRegFromInstruction2(pc);
10727 if ((PCI(pc)->outCond & (PCC_REGISTER | PCC_REGISTER2)) && !checkreg) {
10728 /* assignment to DIRECT operand like "BSF (_global + 1),6" */
10729 //fprintf (stderr, "%s: assignment to register detected, but register not available!\n", __FUNCTION__);
10730 //pc->print (stderr, pc);
10733 if ((PCI(pc)->outCond & (PCC_REGISTER | PCC_REGISTER2)) && !pic16_regIsLocal (checkreg)) {
10734 //fprintf (stderr, "%s: dest-reg not local %s\n", __FUNCTION__, checkreg ? checkreg->name : "<unknown>");
10739 /* OVERKILL: prevent us from removing reads from non-local variables
10740 * THIS IS HERE TO AVOID PROBLEMS WITH VOLATILE OPERANDS ONLY!
10741 * Once registers get a "isVolatile" field this might be handled more efficiently... */
10743 if (PCI(pc)->inCond & PCC_REGISTER) checkreg = pic16_getRegFromInstruction (pc);
10744 else if (PCI(pc)->inCond & PCC_REGISTER2) checkreg = pic16_getRegFromInstruction2(pc);
10746 if ((PCI(pc)->inCond & (PCC_REGISTER | PCC_REGISTER2)) && !checkreg) {
10747 /* read from DIRECT operand like "BTFSS (_global + 1),6" -- might be volatile */
10748 //fprintf (stderr, "%s: read from register detected, but register not available!\n", __FUNCTION__);
10749 //pc->print (stderr, pc);
10752 if ((PCI(pc)->inCond & (PCC_REGISTER | PCC_REGISTER2)) && !pic16_regIsLocal (checkreg)) {
10753 //fprintf (stderr, "%s: src-reg not local: %s\n", __FUNCTION__, checkreg ? checkreg->name : "<unknown>");
10758 /* now check that the defined symbols are not used */
10759 map = pci->pcflow->defmap;
10761 /* find items for pc */
10762 while (map && map->pc != pc) map = map->next;
10764 /* no entries found? something is fishy with DF analysis... -- play safe */
10766 if (pic16_pcode_verbose) {
10767 fprintf (stderr, "%s: defmap not found\n", __FUNCTION__);
10772 /* remember first item assigned to pc for later use */
10775 /* check all symbols being modified by pc */
10776 while (map && map->pc == pc) {
10777 if (map->sym == 0) { map = map->next; continue; }
10779 /* keep pc if it references special symbols (like POSTDEC0) */
10783 pic16_pCode2str (buf, 256, pc);
10784 fprintf (stderr, "%s: checking for sym %x(%s) at pc %p (%s)\n", __FUNCTION__, map->sym, strFromSym (map->sym), pc, buf);
10787 if (pic16_symIsSpecial (map->sym)) {
10788 //fprintf (stderr, "%s: special sym\n", __FUNCTION__);
10791 if (map->acc.access.isWrite) {
10792 if (pic16_isAlive (map->sym, pc)) {
10793 //fprintf (stderr, "%s(%s): pCode is alive (sym %s still used)\n", __FUNCTION__, pic16_pBlockGetFunctionName (pc->pb),strFromSym (map->sym));
10800 /* no use for any of the pc-assigned symbols found -- pCode is dead and can be removed */
10804 pic16_pCode2str (buf, 256, pc);
10805 fprintf (stderr, "%s: pCode %p (%s) is dead.\n", __FUNCTION__, pc, buf);
10811 /* Adds implied operands to the list.
10812 * sym - operand being accessed in the pCode
10813 * list - list to append the operand
10814 * isRead - set to 1 iff sym is read in pCode
10815 * listRead - set to 1 iff all operands being read are to be listed
10817 * Returns 0 for "normal" operands, 1 for special operands.
10819 static int fixupSpecialOperands (symbol_t sym, int in_mask, int mask, pCode *pc, valnum_t val, defmap_t **list, int isRead, int isWrite) {
10820 /* check whether accessing REG accesses other REGs as well */
10824 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10825 *list = newDefmap (SPO_FSR0L, 0xff, 0xff, 1, 0, pc, 0, *list);
10826 *list = newDefmap (SPO_FSR0H, 0xff, 0xff, 1, 0, pc, 0, *list);
10830 /* reads FSR0x and WREG */
10831 *list = newDefmap (SPO_WREG, 0xff, 0x00, 1, 0, pc, 0, *list);
10832 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10833 *list = newDefmap (SPO_FSR0L, 0xff, 0xff, 1, 0, pc, 0, *list);
10834 *list = newDefmap (SPO_FSR0H, 0xff, 0xff, 1, 0, pc, 0, *list);
10840 /* reads/modifies FSR0x */
10841 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10842 *list = newDefmap (SPO_FSR0L, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10843 *list = newDefmap (SPO_FSR0H, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10848 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10849 *list = newDefmap (SPO_FSR1L, 0xff, 0xff, 1, 0, pc, 0, *list);
10850 *list = newDefmap (SPO_FSR1H, 0xff, 0xff, 1, 0, pc, 0, *list);
10854 /* reads FSR1x and WREG */
10855 *list = newDefmap (SPO_WREG, 0xff, 0x00, 1, 0, pc, 0, *list);
10856 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10857 *list = newDefmap (SPO_FSR1L, 0xff, 0xff, 1, 0, pc, 0, *list);
10858 *list = newDefmap (SPO_FSR1H, 0xff, 0xff, 1, 0, pc, 0, *list);
10864 /* reads/modifies FSR1x */
10865 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10866 *list = newDefmap (SPO_FSR1L, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10867 *list = newDefmap (SPO_FSR1H, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10872 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10873 *list = newDefmap (SPO_FSR2L, 0xff, 0xff, 1, 0, pc, 0, *list);
10874 *list = newDefmap (SPO_FSR2H, 0xff, 0xff, 1, 0, pc, 0, *list);
10878 /* reads FSR2x and WREG */
10879 *list = newDefmap (SPO_WREG, 0xff, 0x00, 1, 0, pc, 0, *list);
10880 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10881 *list = newDefmap (SPO_FSR2L, 0xff, 0xff, 1, 0, pc, 0, *list);
10882 *list = newDefmap (SPO_FSR2H, 0xff, 0xff, 1, 0, pc, 0, *list);
10888 /* reads/modifies FSR2x */
10889 *list = newDefmap (sym, 0xff, 0xff, 0, 0, pc, 0, *list);
10890 *list = newDefmap (SPO_FSR2L, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10891 *list = newDefmap (SPO_FSR2H, 0xff, 0xff, 1, 1, pc, newValnum (), *list);
10895 /* modifies PCLATH and PCLATU */
10896 *list = newDefmap (SPO_PCL, 0xff, 0xff, isRead, isWrite, pc, newValnum (), *list);
10898 /* reading PCL updates PCLATx */
10899 *list = newDefmap (SPO_PCLATH, 0xff, 0xff, 0, 1, pc, newValnum (), *list);
10900 *list = newDefmap (SPO_PCLATU, 0xff, 0xff, 0, 1, pc, newValnum (), *list);
10903 /* writing PCL implicitly reads PCLATx (computed GOTO) */
10904 *list = newDefmap (SPO_PCLATH, 0xff, 0xff, 1, 0, pc, 0, *list);
10905 *list = newDefmap (SPO_PCLATU, 0xff, 0xff, 1, 0, pc, 0, *list);
10910 *list = newDefmap (sym, in_mask, mask, isRead, isWrite, pc, val, *list);
10911 /* nothing special */
10916 /* has been a special operand */
10920 static symbol_t pic16_fsrsym_idx[][2] = {
10921 {SPO_FSR0L, SPO_FSR0H},
10922 {SPO_FSR1L, SPO_FSR1H},
10923 {SPO_FSR2L, SPO_FSR2H}
10926 /* Merge multiple defmap entries for the same symbol for list's pCode. */
10927 static void mergeDefmapSymbols (defmap_t *list) {
10928 defmap_t *ref, *curr, *temp;
10930 /* now make sure that each symbol occurs at most once per pc */
10932 while (ref && (ref->pc == list->pc)) {
10934 while (curr && (curr->pc == list->pc)) {
10935 if (curr->sym == ref->sym) {
10936 //fprintf (stderr, "Merging defmap entries for symbol %s\n", strFromSym (ref->sym));
10937 /* found a symbol occuring twice... merge the two */
10938 if (curr->acc.access.isRead) {
10939 //if (ref->acc.access.isRead) fprintf (stderr, "symbol %s was marked twice as read at pc %p\n", strFromSym (ref->sym), ref->pc);
10940 ref->acc.access.isRead = 1;
10941 ref->acc.access.in_mask |= curr->acc.access.in_mask;
10943 if (curr->acc.access.isWrite) {
10944 //if (ref->acc.access.isWrite) fprintf (stderr, "symbol %s was marked twice as written at pc %p\n", strFromSym (ref->sym), ref->pc);
10945 ref->acc.access.isWrite = 1;
10946 ref->acc.access.mask |= curr->acc.access.mask;
10950 deleteDefmap (temp);
10951 continue; // do not skip curr!
10959 /** Prepend list with the reads and definitions performed by pc. */
10960 static defmap_t *createDefmap (pCode *pc, defmap_t *list) {
10961 pCodeInstruction *pci;
10962 int cond, inCond, outCond;
10963 int mask = 0xff, smask;
10964 int isSpecial, isSpecial2;
10965 symbol_t sym, sym2;
10969 /* make sure there is at least one entry for each pc (needed by list traversal routines) */
10970 /* TODO: mark this defmap node as an ASMDIR -- any values might be read/modified */
10971 fprintf (stderr, "ASMDIRs not supported by data flow analysis!\n");
10972 list = newDefmap (0, 0xff, 0xff, 0, 0, pc, 0, list);
10975 assert (isPCI(pc));
10978 /* handle bit instructions */
10979 if (pci->isBitInst) {
10980 assert (pci->pcop->type == PO_GPR_BIT);
10981 mask = 1U << (PCORB(PCI(pc)->pcop)->bit);
10984 /* handle (additional) implicit arguments */
10990 lit = PCOL(pci->pcop)->lit;
10991 assert (lit >= 0 && lit < 3);
10992 //fprintf (stderr, "LFSR: %s // %s\n", pci->pcop->name, pic16_get_op(((pCodeOpLit2 *)(pci->pcop))->arg2, NULL, 0));
10993 val = valnumFromStr (pic16_get_op(((pCodeOpLit2 *)(pci->pcop))->arg2, NULL, 0));
10994 //fprintf (stderr, "LFSR lit=%u, symval=%4x\n", lit, val);
10995 list = newDefmap (pic16_fsrsym_idx[lit][0], 0x00, 0xff, 0, 1, pc, val, list);
10996 list = newDefmap (pic16_fsrsym_idx[lit][1], 0x00, 0xff, 0, 1, pc, val+1, list); // val+1 is guaranteed not be used as a valnum...
11000 case POC_MOVLB: // BSR
11001 case POC_BANKSEL: // BSR
11002 list = newDefmap (SPO_BSR, 0x00, 0xff, 0, 1, pc, valnumFromStr (pic16_get_op (((pCodeOpLit2 *)(pci->pcop))->arg2, NULL, 0)), list);
11005 case POC_MULWF: // PRODx
11006 case POC_MULLW: // PRODx
11007 list = newDefmap (SPO_PRODH, 0x00, 0xff, 0, 1, pc, newValnum (), list);
11008 list = newDefmap (SPO_PRODL, 0x00, 0xff, 0, 1, pc, newValnum (), list);
11011 case POC_POP: // TOS, STKPTR
11012 list = newDefmap (SPO_STKPTR, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11013 list = newDefmap (SPO_TOSL, 0x00, 0xff, 0, 1, pc, newValnum (), list);
11014 list = newDefmap (SPO_TOSH, 0x00, 0xff, 0, 1, pc, newValnum (), list);
11015 list = newDefmap (SPO_TOSU, 0x00, 0xff, 0, 1, pc, newValnum (), list);
11018 case POC_PUSH: // STKPTR
11019 list = newDefmap (SPO_STKPTR, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11020 list = newDefmap (SPO_TOSL, 0xff, 0xff, 0, 1, pc, newValnum (), list);
11021 list = newDefmap (SPO_TOSH, 0xff, 0xff, 0, 1, pc, newValnum (), list);
11022 list = newDefmap (SPO_TOSU, 0xff, 0xff, 0, 1, pc, newValnum (), list);
11025 case POC_CALL: // return values (and arguments?): WREG, PRODx, FSR0L
11026 case POC_RCALL: // return values (and arguments?): WREG, PRODx, FSR0L
11027 list = newDefmap (SPO_WREG, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11028 list = newDefmap (SPO_PRODL, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11029 list = newDefmap (SPO_PRODH, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11030 list = newDefmap (SPO_FSR0L, 0xff, 0xff, 1, 1, pc, newValnum (), list);
11032 /* needs correctly set-up stack pointer */
11033 list = newDefmap (SPO_FSR1L, 0xff, 0x00, 1, 0, pc, 0, list);
11034 list = newDefmap (SPO_FSR1H, 0xff, 0x00, 1, 0, pc, 0, list);
11037 case POC_RETLW: // return values: WREG, PRODx, FSR0L
11038 /* pseudo read on (possible) return values */
11039 // WREG is handled below via outCond
11040 list = newDefmap (SPO_PRODL, 0xff, 0x00, 1, 0, pc, 0, list);
11041 list = newDefmap (SPO_PRODH, 0xff, 0x00, 1, 0, pc, 0, list);
11042 list = newDefmap (SPO_FSR0L, 0xff, 0x00, 1, 0, pc, 0, list);
11044 /* caller's stack pointers must be restored */
11045 list = newDefmap (SPO_FSR1L, 0xff, 0x00, 1, 0, pc, 0, list);
11046 list = newDefmap (SPO_FSR1H, 0xff, 0x00, 1, 0, pc, 0, list);
11047 list = newDefmap (SPO_FSR2L, 0xff, 0x00, 1, 0, pc, 0, list);
11048 list = newDefmap (SPO_FSR2H, 0xff, 0x00, 1, 0, pc, 0, list);
11051 case POC_RETURN: // return values; WREG, PRODx, FSR0L
11052 case POC_RETFIE: // return value: WREG, PRODx, FSR0L
11053 /* pseudo read on (possible) return values */
11054 list = newDefmap (SPO_WREG, 0xff, 0x00, 1, 0, pc, 0, list);
11055 list = newDefmap (SPO_PRODL, 0xff, 0x00, 1, 0, pc, 0, list);
11056 list = newDefmap (SPO_PRODH, 0xff, 0x00, 1, 0, pc, 0, list);
11057 list = newDefmap (SPO_FSR0L, 0xff, 0x00, 1, 0, pc, 0, list);
11059 /* caller's stack pointers must be restored */
11060 list = newDefmap (SPO_FSR1L, 0xff, 0x00, 1, 0, pc, 0, list);
11061 list = newDefmap (SPO_FSR1H, 0xff, 0x00, 1, 0, pc, 0, list);
11062 list = newDefmap (SPO_FSR2L, 0xff, 0x00, 1, 0, pc, 0, list);
11063 list = newDefmap (SPO_FSR2H, 0xff, 0x00, 1, 0, pc, 0, list);
11067 list = newDefmap (SPO_TBLPTRL, 0xff, 0x00, 1, 0, pc, 0, list);
11068 list = newDefmap (SPO_TBLPTRH, 0xff, 0x00, 1, 0, pc, 0, list);
11069 list = newDefmap (SPO_TBLPTRU, 0xff, 0x00, 1, 0, pc, 0, list);
11070 list = newDefmap (SPO_TABLAT, 0x00, 0xff, 0, 1, pc, newValnum(), list);
11073 case POC_TBLRD_POSTINC:
11074 case POC_TBLRD_POSTDEC:
11075 case POC_TBLRD_PREINC:
11076 list = newDefmap (SPO_TBLPTRL, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11077 list = newDefmap (SPO_TBLPTRH, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11078 list = newDefmap (SPO_TBLPTRU, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11079 list = newDefmap (SPO_TABLAT, 0x00, 0xff, 0, 1, pc, newValnum(), list);
11083 list = newDefmap (SPO_TBLPTRL, 0xff, 0x00, 1, 0, pc, 0, list);
11084 list = newDefmap (SPO_TBLPTRH, 0xff, 0x00, 1, 0, pc, 0, list);
11085 list = newDefmap (SPO_TBLPTRU, 0xff, 0x00, 1, 0, pc, 0, list);
11086 list = newDefmap (SPO_TABLAT, 0xff, 0x00, 1, 0, pc, 0, list);
11089 case POC_TBLWT_POSTINC:
11090 case POC_TBLWT_POSTDEC:
11091 case POC_TBLWT_PREINC:
11092 list = newDefmap (SPO_TBLPTRL, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11093 list = newDefmap (SPO_TBLPTRH, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11094 list = newDefmap (SPO_TBLPTRU, 0xff, 0xff, 1, 1, pc, newValnum(), list);
11095 list = newDefmap (SPO_TABLAT, 0xff, 0x00, 1, 0, pc, 0, list);
11099 /* many instruction implicitly read BSR... -- THIS IS IGNORED! */
11103 /* handle explicit arguments */
11104 inCond = pci->inCond;
11105 outCond = pci->outCond;
11106 cond = inCond | outCond;
11107 if (cond & PCC_W) {
11108 list = newDefmap (symFromStr ("WREG"), mask, mask, inCond & PCC_W, outCond & PCC_W, pc, newValnum (), list);
11111 /* keep STATUS read BEFORE STATUS write in the list (still neccessary?) */
11112 if (inCond & PCC_STATUS) {
11114 if (inCond & PCC_C) smask |= 1U << PIC_C_BIT;
11115 if (inCond & PCC_DC) smask |= 1U << PIC_DC_BIT;
11116 if (inCond & PCC_Z) smask |= 1U << PIC_Z_BIT;
11117 if (inCond & PCC_OV) smask |= 1U << PIC_OV_BIT;
11118 if (inCond & PCC_N) smask |= 1U << PIC_N_BIT;
11120 list = newDefmap (symFromStr ("STATUS"), smask, 0x00, 1, 0, pc, 0, list);
11121 //fprintf (stderr, "pc %p: def STATUS & %02x\n", pc, smask);
11124 if (outCond & PCC_STATUS) {
11126 if (outCond & PCC_C) smask |= 1U << PIC_C_BIT;
11127 if (outCond & PCC_DC) smask |= 1U << PIC_DC_BIT;
11128 if (outCond & PCC_Z) smask |= 1U << PIC_Z_BIT;
11129 if (outCond & PCC_OV) smask |= 1U << PIC_OV_BIT;
11130 if (outCond & PCC_N) smask |= 1U << PIC_N_BIT;
11132 list = newDefmap (symFromStr ("STATUS"), 0x00, smask, 0, 1, pc, newValnum (), list);
11133 //fprintf (stderr, "pc %p: def STATUS & %02x\n", pc, smask);
11136 isSpecial = isSpecial2 = 0;
11138 if (cond & PCC_REGISTER) {
11139 name = pic16_get_op (pci->pcop, NULL, 0);
11140 sym = symFromStr (name);
11141 isSpecial = fixupSpecialOperands (sym, mask, mask, pc, newValnum(), &list, inCond & PCC_REGISTER, outCond & PCC_REGISTER);
11142 //fprintf (stderr, "pc %p: def REG %s(%x) & %02x\n", pc, name, sym, mask);
11145 if (cond & PCC_REGISTER2) {
11146 name = pic16_get_op2 (pci->pcop, NULL, 0);
11147 sym2 = symFromStr (name);
11148 isSpecial2 = fixupSpecialOperands (sym2, mask, mask, pc, newValnum(), &list, inCond & PCC_REGISTER2, outCond & PCC_REGISTER2);
11149 //fprintf (stderr, "pc %p: def REG2 %s(%x) & %02x\n", pc, name, sym2, mask);
11153 /* make sure there is at least one entry for each pc (needed by list traversal routines) */
11154 list = newDefmap (0, 0x00, 0x00, 0, 0, pc, 0, list);
11156 mergeDefmapSymbols (list);
11162 static void printDefmap (defmap_t *map) {
11166 fprintf (stderr, "defmap @ %p:\n", curr);
11168 fprintf (stderr, "%s%s: %4x|%4x / %02x|%02x, sym %s(%x) @ pc %p\n",
11169 curr->acc.access.isRead ? "R" : " ",
11170 curr->acc.access.isWrite ? "W": " ",
11171 curr->in_val, curr->val,
11172 curr->acc.access.in_mask, curr->acc.access.mask,
11173 strFromSym(curr->sym), curr->sym,
11177 fprintf (stderr, "<EOL>\n");
11181 /* Add "additional" definitions to uniq.
11182 * This can be used to merge the in_values and the flow's defmap to create an in_value-list for the flow's successors.
11183 * This can also be used to create a uniq (out)list from a flow's defmap by passing *uniq==NULL.
11185 * If symbols defined in additional are not present in uniq, a definition is created.
11186 * Otherwise the present definition is altered to reflect the newer assignments.
11188 * flow: <uniq> --> assign1 --> assign2 --> assign3 --> ... --> <uniq'>
11189 * before `------- noted in additional --------' after
11191 * I assume that each symbol occurs AT MOST ONCE in uniq.
11194 static int defmapUpdateUniqueSym (defmap_t **uniq, defmap_t *additional) {
11199 //fprintf (stderr, "%s: merging %p & %p\n", __FUNCTION__, *uniq, additional);
11200 /* find tail of additional list (holds the first assignment) */
11202 while (curr && curr->next) curr = curr->next;
11206 /* find next assignment in additionals */
11207 while (curr && !curr->acc.access.isWrite) curr = curr->prev;
11211 /* find item in uniq */
11213 //printDefmap (*uniq);
11214 while (old && (old->sym != curr->sym)) old = old->next;
11217 /* definition found -- replace */
11218 if (old->val != curr->val) {
11219 old->val = curr->val;
11223 /* new definition */
11224 *uniq = newDefmap (curr->sym, 0x00, 0xff, 0, 1, NULL, curr->val, *uniq);
11231 /* return 0 iff uniq remained unchanged */
11235 /* Creates the in_value list of a flow by (iteratively) merging the out_value
11236 * lists of its predecessor flows.
11237 * Initially *combined should be NULL, alt_in will be copied to combined.
11238 * If *combined != NULL, combined will be altered:
11239 * - for symbols defined in *combined but not in alt_in,
11240 * *combined is altered to 0 (value unknown, either *combined or INIT).
11241 * - for symbols defined in alt_in but not in *combined,
11242 * a 0 definition is created (value unknown, either INIT or alt).
11243 * - for symbols defined in both, *combined is:
11244 * > left unchanged if *combined->val == alt_in->val or
11245 * > modified to 0 otherwise (value unknown, either alt or *combined).
11247 * I assume that each symbol occurs AT MOST ONCE in each list!
11249 static int defmapCombineFlows (defmap_t **combined, defmap_t *alt_in, pBlock *pb) {
11255 //fprintf (stderr, "%s: merging %p & %p\n", __FUNCTION__, *combined, alt_in);
11257 if (!(*combined)) {
11258 return defmapUpdateUniqueSym (combined, alt_in);
11261 /* merge the two */
11264 /* find symbols definition in *combined */
11266 while (old && (old->sym != curr->sym)) old = old->next;
11269 /* definition found */
11270 if (old->val && (old->val != curr->val)) {
11271 old->val = 0; /* value unknown */
11275 /* no definition found -- can be either INIT or alt_in's value */
11276 val = pic16_pBlockAddInval (pb, curr->sym)->val;
11277 *combined = newDefmap (curr->sym, 0x00, 0xff, 0, 1, NULL, (val == curr->val) ? val : 0, *combined);
11278 if (val != curr->val) change++;
11284 /* update symbols from *combined that are NOT defined in alt_in -- can be either *combined's value or INIT */
11287 if (old->val != 0) {
11288 /* find definition in alt_in */
11290 while (curr && curr->sym != old->sym) curr = curr->next;
11292 /* symbol defined in *combined only -- can be either INIT or *combined */
11293 val = pic16_pBlockAddInval (pb, old->sym)->val;
11294 if (old->val != val) {
11307 static int defmapCompareUnique (defmap_t *map1, defmap_t *map2) {
11308 defmap_t *curr1, *curr2;
11311 /* identical maps are equal */
11312 if (map1 == map2) return 0;
11314 if (!map1) return -1;
11315 if (!map2) return 1;
11317 //fprintf (stderr, "%s: comparing %p & %p\n", __FUNCTION__, map1, map2);
11322 while (curr1 && curr2) {
11323 curr1 = curr1->next;
11324 curr2 = curr2->next;
11327 /* one of them longer? */
11328 if (curr1) return 1;
11329 if (curr2) return -1;
11331 /* both lists are of equal length -- compare (in O(n^2)) */
11336 while (curr2 && curr2->sym != sym) curr2 = curr2->next;
11337 if (!curr2) return 1; // symbol not found in curr2
11338 if (curr2->val != curr1->val) return 1; // values differ
11340 /* compare next symbol */
11341 curr1 = curr1->next;
11344 /* no difference found */
11349 /* Prepare a list of all reaching definitions per flow.
11350 * This is done using a forward dataflow analysis.
11352 static void createReachingDefinitions (pBlock *pb) {
11353 defmap_t *out_vals, *in_vals;
11356 pCodeFlowLink *link;
11360 /* initialize out_vals to unique'fied defmaps per pCodeFlow */
11361 for (pc = pic16_findNextInstruction (pb->pcHead); pc; pc = pic16_findNextInstruction (pc->next)) {
11363 deleteDefmapChain (&PCFL(pc)->in_vals);
11364 deleteDefmapChain (&PCFL(pc)->out_vals);
11365 defmapUpdateUniqueSym (&PCFL(pc)->out_vals, PCFL(pc)->defmap);
11369 pc = pic16_findNextInstruction (pb->pcHead);
11370 todo = NULL; blacklist = NULL;
11371 addSetHead (&todo, PCI(pc)->pcflow);
11373 //fprintf (stderr, "%s: function %s()\n", __FUNCTION__, pic16_pBlockGetFunctionName (pb));
11374 while (elementsInSet (todo)) {
11375 //fprintf (stderr, "%u items in todo-set\n", elementsInSet (todo));
11376 pcfl = PCFL(indexSet (todo, 0));
11377 deleteSetItem (&todo, pcfl);
11378 //fprintf (stderr, "%s: checking %p\n", __FUNCTION__, pcfl);
11382 if (isinSet (blacklist, pcfl)) {
11383 fprintf (stderr, "ignoring blacklisted flow\n");
11387 /* create in_vals from predecessors out_vals */
11388 link = setFirstItem (pcfl->from);
11390 defmapCombineFlows (&in_vals, link->pcflow->out_vals, pb);
11391 link = setNextItem (pcfl->from);
11394 //printDefmap (in_vals);
11395 //printDefmap (pcfl->in_vals);
11397 if (!pcfl->in_vals || !pcfl->out_vals || defmapCompareUnique (in_vals, pcfl->in_vals)) {
11398 //fprintf (stderr, "in_vals changed\n");
11399 /* in_vals changed -- update out_vals */
11400 deleteDefmapChain (&pcfl->in_vals);
11401 pcfl->in_vals = in_vals;
11403 /* create out_val from in_val and defmap */
11405 defmapUpdateUniqueSym (&out_vals, in_vals);
11406 defmapUpdateUniqueSym (&out_vals, pcfl->defmap);
11408 /* is out_vals different from pcfl->out_vals */
11409 if (!pcfl->out_vals || defmapCompareUnique (out_vals, pcfl->out_vals)) {
11410 //fprintf (stderr, "out_vals changed\n");
11411 deleteDefmapChain (&pcfl->out_vals);
11412 pcfl->out_vals = out_vals;
11414 if (pcfl->out_vals == NULL && pcfl->in_vals == NULL) {
11415 addSet (&blacklist, pcfl);
11418 /* reschedule all successors */
11419 link = setFirstItem (pcfl->to);
11421 //fprintf (stderr, " %p --> %p\n", pcfl, link->pcflow);
11422 addSetIfnotP (&todo, link->pcflow);
11423 link = setNextItem (pcfl->to);
11426 deleteDefmapChain (&out_vals);
11429 deleteDefmapChain (&in_vals);
11435 static void showAllDefs (symbol_t sym, pCode *pc) {
11439 assert (isPCI(pc));
11440 count = defmapFindAll (sym, pc, &map);
11442 fprintf (stderr, "sym %s(%x) @ %p defined as (val@pc): ", strFromSym(sym), sym, pc);
11445 fprintf (stderr, "(%x @ %p) ", map->val, map->pc);
11448 pic16_pCode2str (buf, 256, map->pc);
11449 fprintf (stderr, "\n (%x @ %p(%s)) ", map->val, map->pc, buf);
11453 deleteDefmapChain (&map);
11457 /* safepCodeUnlink and remove pc from defmap. */
11458 static int pic16_safepCodeRemove (pCode *pc, char *comment) {
11459 defmap_t *map, *next, **head;
11463 map = isPCI(pc) ? PCI(pc)->pcflow->defmap : NULL;
11464 head = isPCI(pc) ? &PCI(pc)->pcflow->defmap : NULL;
11465 res = pic16_safepCodeUnlink (pc, comment);
11468 /* remove pc from defmap */
11471 if (map->pc == pc) {
11472 if (!map->prev && head) *head = map->next;
11473 deleteDefmap (map);
11482 void pic16_fixDefmap (pCode *pc, pCode *newpc) {
11484 /* This breaks the defmap chain's references to pCodes... fix it! */
11485 map = PCI(pc)->pcflow->defmap;
11487 while (map && map->pc != pc) map = map->next;
11489 while (map && map->pc == pc) {
11495 /* Replace a defmap entry for sym with newsym for read accesses (isRead == 1) or
11496 * write accesses (isRead == 0). */
11497 void defmapReplaceSymRef (pCode *pc, symbol_t sym, symbol_t newsym, int isRead) {
11498 defmap_t *map, *map_start;
11500 if (!isPCI(pc)) return;
11501 if (sym == newsym) return;
11503 map = PCI(pc)->pcflow->defmap;
11505 while (map && map->pc != pc) map = map->next;
11507 while (map && map->pc == pc) {
11508 if (map->sym == sym) {
11509 assert ((isRead && map->acc.access.isRead) || ((!isRead) && (map->acc.access.isWrite)));
11510 if (!(map->acc.access.isRead && map->acc.access.isWrite)) {
11511 /* only one kind of access handled... this is easy */
11514 /* must copy defmap entry before replacing symbol... */
11515 copy = copyDefmap (map);
11517 map->acc.access.isRead = 0;
11518 copy->acc.access.isWrite = 0;
11520 map->acc.access.isWrite = 0;
11521 copy->acc.access.isRead = 0;
11523 copy->sym = newsym;
11524 /* insert copy into defmap chain */
11525 defmapInsertAfter (map, copy);
11531 /* as this might introduce multiple defmap entries for newsym... */
11532 mergeDefmapSymbols (map_start);
11535 /* Assign "better" valnums to results. */
11536 static void assignValnums (pCode *pc) {
11537 pCodeInstruction *pci;
11539 symbol_t sym1, sym2;
11540 int cond, isSpecial1, isSpecial2, count, mask, lit;
11541 defmap_t *list, *val, *oldval, *dummy;
11542 regs *reg1 = NULL, *reg2 = NULL;
11545 /* only works for pCodeInstructions... */
11546 if (!isPCI(pc)) return;
11549 cond = pci->inCond | pci->outCond;
11550 list = pci->pcflow->defmap;
11551 sym1 = sym2 = isSpecial1 = isSpecial2 = 0;
11553 if (cond & PCC_REGISTER) {
11554 sym1 = symFromStr (pic16_get_op (pci->pcop, NULL, 0));
11555 reg1 = pic16_getRegFromInstruction (pc);
11556 isSpecial1 = pic16_symIsSpecial (sym1);
11558 if (cond & PCC_REGISTER2) {
11559 sym2 = symFromStr (pic16_get_op2 (pci->pcop, NULL, 0));
11560 reg2 = pic16_getRegFromInstruction (pc);
11561 isSpecial2 = pic16_symIsSpecial (sym2);
11564 /* determine input values */
11566 while (val && val->pc != pc) val = val->next;
11567 //list = val; /* might save some time later... */
11568 while (val && val->pc == pc) {
11570 if (val->sym != 0 && (1 || val->acc.access.isRead)) {
11571 /* get valnum for sym */
11572 count = defmapFindAll (val->sym, pc, &oldval);
11573 //fprintf (stderr, "%d defs for sym %s\n", count, strFromSym (val->sym));
11575 if ((val->acc.access.in_mask & oldval->acc.access.mask) == val->acc.access.in_mask) {
11576 val->in_val = oldval->val;
11580 } else if (count == 0) {
11581 /* no definition found */
11584 /* multiple definition(s) found -- value not known (unless always the same valnum) */
11586 dummy = oldval->next;
11587 mask = oldval->acc.access.mask;
11588 val->in_val = oldval->val;
11589 while (dummy && (dummy->val == val->in_val)) {
11590 mask &= dummy->acc.access.mask;
11591 dummy = dummy->next;
11594 /* found other values or to restictive mask */
11595 if (dummy || ((mask & val->acc.access.in_mask) != val->acc.access.in_mask)) {
11599 if (count > 0) deleteDefmapChain (&oldval);
11604 /* handle valnum assignment */
11606 case POC_CLRF: /* modifies STATUS (Z) */
11607 if (!isSpecial1 && pic16_regIsLocal (reg1)) {
11608 oldval = defmapCurr (list, sym1, pc);
11609 if (oldval && (litFromValnum (oldval->in_val) == 0)) {
11610 //fprintf (stderr, "%s: REG (%s) already set up correctly (%x)\n", pci->mnemonic, strFromSym(sym1), oldval->in_val);
11611 if (!pic16_isAlive (SPO_STATUS, pc)) pic16_safepCodeRemove (pc, "=DF= redundant CLRF removed");
11613 defmapUpdate (list, sym1, pc, valnumFromLit(0));
11617 case POC_SETF: /* SETF does not touch STATUS */
11618 if (!isSpecial1 && pic16_regIsLocal (reg1)) {
11619 oldval = defmapCurr (list, sym1, pc);
11620 if (oldval && (litFromValnum (oldval->in_val) == 0x00FF)) {
11621 //fprintf (stderr, "%s: REG (%s) already set up correctly (%x)\n", pci->mnemonic, strFromSym(sym1), oldval->in_val);
11622 pic16_safepCodeRemove (pc, "=DF= redundant SETF removed");
11624 defmapUpdate (list, sym1, pc, valnumFromLit (0x00FF));
11628 case POC_MOVLW: /* does not touch STATUS */
11629 oldval = defmapCurr (list, SPO_WREG, pc);
11630 if (pci->pcop->type == PO_LITERAL) {
11631 //fprintf (stderr, "MOVLW: literal %u\n", PCOL(pci->pcop)->lit);
11632 litnum = valnumFromLit ((unsigned char)PCOL(pci->pcop)->lit);
11634 //fprintf (stderr, "MOVLW: %s\n", pic16_get_op (pci->pcop, NULL, 0));
11635 litnum = valnumFromStr (pic16_get_op (pci->pcop, NULL, 0));
11637 if (oldval && oldval->in_val == litnum) {
11638 //fprintf (stderr, "%s: W already set up correctly (%x)\n", PCI(pc)->mnemonic, oldval->in_val);
11639 pic16_safepCodeRemove (pc, "=DF= redundant MOVLW removed");
11641 defmapUpdate (list, SPO_WREG, pc, litnum);
11644 case POC_ANDLW: /* modifies STATUS (Z,N) */
11645 case POC_IORLW: /* modifies STATUS (Z,N) */
11646 case POC_XORLW: /* modifies STATUS (Z,N) */
11647 /* can be optimized iff WREG contains a known literal (0x100 - 0x1FF) */
11648 if (pci->pcop->type == PO_LITERAL) {
11650 lit = (unsigned char) PCOL(pci->pcop)->lit;
11651 val = defmapCurr (list, SPO_WREG, pc);
11652 if (val) vallit = litFromValnum (val->in_val);
11653 if (vallit != -1) {
11654 /* xxxLW <literal>, WREG contains a known literal */
11655 //fprintf (stderr, "%s 0x%02x, WREG: 0x%x\n", pci->mnemonic, lit, vallit);
11656 if (pci->op == POC_ANDLW) {
11658 } else if (pci->op == POC_IORLW) {
11660 } else if (pci->op == POC_XORLW) {
11663 assert (0 && "invalid operation");
11665 if (vallit == lit) {
11666 //fprintf (stderr, "%s: W already set up correctly (%x = val %x)\n", pci->mnemonic, vallit, val->in_val);
11667 if (!pic16_isAlive (SPO_STATUS, pc)) pic16_safepCodeRemove (pc, "=DF= redundant ANDLW/IORLW/XORLW removed");
11669 defmapUpdate (list, SPO_WREG, pc, valnumFromLit (lit));
11676 /* check if old value matches new value */
11679 assert (pci->pcop->type == PO_LITERAL);
11681 lit = PCOL(pci->pcop)->lit;
11683 val = defmapCurr (list, pic16_fsrsym_idx[lit][0], pc);
11685 if (val && (val->in_val != 0) && (val->in_val == val->val)) {
11686 //fprintf (stderr, "FSR%dL already set up correctly at %p (%x)\n", lit, pc, val->val);
11688 /* cannot remove this LFSR */
11692 val = defmapCurr (list, pic16_fsrsym_idx[lit][1], pc);
11693 if (val && (val->in_val != 0) && (val->in_val == val->val)) {
11694 //fprintf (stderr, "FSR%dH already set up correctly at %p (%x)\n", lit, pc, val->val);
11700 pic16_safepCodeRemove (pc, "=DF= redundant LFSR removed");
11705 case POC_MOVWF: /* does not touch flags */
11706 /* find value of WREG */
11707 val = defmapCurr (list, SPO_WREG, pc);
11708 oldval = defmapCurr (list, sym1, pc);
11709 if (val) lit = litFromValnum (val->in_val);
11711 //fprintf (stderr, "MOVWF: lit: %i (%x, %x)\n", lit, lit, val->in_val);
11713 if ((lit == 0 || lit == 0x0ff) && !pic16_isAlive (SPO_STATUS, pc)) {
11714 /* might replace with CLRF/SETF (will possibly make previous MOVLW 0x00/0xff unneccessary --> dead code elimination) */
11715 //fprintf (stderr, "replacing MOVWF with CLRF/SETF\n");
11717 newpc = pic16_newpCode (POC_CLRF, pic16_pCodeOpCopy (pci->pcop));
11719 assert (lit == 0x0ff);
11720 newpc = pic16_newpCode (POC_SETF, pic16_pCodeOpCopy (pci->pcop));
11722 if (pic16_debug_verbose || pic16_pcode_verbose) pic16_InsertCommentAfter (pc->prev, "=DF= MOVWF: replaced by CLRF/SETF");
11723 pic16_pCodeReplace (pc, newpc);
11724 defmapReplaceSymRef (pc, SPO_WREG, 0, 1);
11725 pic16_fixDefmap (pc, newpc);
11728 /* This breaks the defmap chain's references to pCodes... fix it! */
11729 if (!val->prev) PCI(pc)->pcflow->defmap = val->next;
11730 if (!val->acc.access.isWrite) {
11731 deleteDefmap (val); // delete reference to WREG as in value
11734 val->acc.access.isRead = 0; // delete reference to WREG as in value
11736 oldval = PCI(pc)->pcflow->defmap;
11738 if (oldval->pc == pc) oldval->pc = newpc;
11739 oldval = oldval->next;
11741 } else if (!isSpecial1 && pic16_regIsLocal (reg1) && val && oldval && (val->in_val != 0) && (val->in_val == oldval->in_val)) {
11742 //fprintf (stderr, "MOVWF: F (%s) already set up correctly (%x) at %p\n", strFromSym (sym1), oldval->in_val, pc);
11743 pic16_safepCodeRemove (pc, "=DF= redundant MOVWF removed");
11745 if (val) defmapUpdate (list, sym1, pc, val->in_val);
11748 case POC_MOVFW: /* modifies STATUS (Z,N) */
11749 /* find value of REG */
11750 if (!isSpecial1 && pic16_regIsLocal (reg1)) {
11751 val = defmapCurr (list, sym1, pc);
11752 oldval = defmapCurr (list, SPO_WREG, pc);
11753 if (val && oldval && (val->in_val != 0) && (val->in_val == oldval->in_val)) {
11754 //fprintf (stderr, "MOVFW: W already set up correctly (%x) at %p\n", oldval->in_val, pc);
11755 if (!pic16_isAlive (SPO_STATUS, pc)) pic16_safepCodeRemove (pc, "=DF= redundant MOVFW removed");
11757 if (val) defmapUpdate (list, SPO_WREG, pc, val->in_val);
11761 case POC_MOVFF: /* does not touch STATUS */
11762 /* find value of REG */
11763 val = defmapCurr (list, sym1, pc);
11764 oldval = defmapCurr (list, sym2, pc);
11765 if (val) lit = litFromValnum (val->in_val);
11768 if (!isSpecial1 && pic16_regIsLocal (reg1) && val && oldval && !pic16_isAlive (SPO_STATUS, pc)) {
11769 //pc->print (stderr, pc); fprintf (stderr, "lit: %d (%x, %x)\n", lit, lit, val->in_val);
11771 newpc = pic16_newpCode (POC_CLRF, PCOR2(pci->pcop)->pcop2);
11772 } else if (lit == 0x00ff) {
11773 newpc = pic16_newpCode (POC_SETF, PCOR2(pci->pcop)->pcop2);
11778 pic16_InsertCommentAfter (pc->prev, "=DF= MOVFF: replaced by CRLF/SETF");
11779 pic16_df_saved_bytes += PCI(pc)->isize - PCI(newpc)->isize;
11780 pic16_pCodeReplace (pc, newpc);
11781 defmapReplaceSymRef (pc, sym1, 0, 1);
11782 pic16_fixDefmap (pc, newpc);
11784 break; // do not process instruction as MOVFF...
11786 } else if (!isSpecial1 && !isSpecial2
11787 && pic16_regIsLocal (reg1) && pic16_regIsLocal (reg2)
11788 && val && oldval && (val->in_val != 0)) {
11789 if (val->in_val == oldval->in_val) {
11790 //fprintf (stderr, "MOVFF: F2 (%s) already set up correctly (%x) at %p\n", strFromSym (sym2), oldval->in_val, pc);
11791 pic16_safepCodeRemove (pc, "=DF= redundant MOVFF removed");
11793 if (!pic16_isAlive (sym1, pc)) {
11794 defmap_t *copy = NULL;
11795 /* If there is another symbol S storing sym1's value we should assign from S thus shortening the liferange of sym1.
11796 * This should help eliminate
11798 * <do something not changing A or using B>
11800 * <B is not alive anymore>
11802 * <do something not changing A or using B>
11806 /* scan defmap for symbols storing sym1's value */
11807 while (oldval && (oldval->pc == pc || oldval->in_val != val->in_val)) oldval = oldval->next;
11808 if (oldval && (oldval->sym != sym1) && defmapFindAll (oldval->sym, pc, ©) == 1) {
11809 /* unique reaching definition for sym found */
11810 if (copy->val && copy->val == val->in_val) {
11811 //fprintf (stderr, "found replacement symbol for %s (val %x) <-- %s (assigned %x @ %p)\n", strFromSym(sym1), val->in_val, strFromSym(copy->sym), copy->val, copy->pc);
11812 if (copy->sym == SPO_WREG) {
11813 newpc = pic16_newpCode (POC_MOVWF, pic16_pCodeOpCopy (PCOR2(pci->pcop)->pcop2));
11815 pCodeOp *pcop = NULL;
11816 /* the code below fails if we try to replace
11817 * MOVFF PRODL, r0x03
11818 * MOVFF r0x03, PCLATU
11820 * MOVFF PRODL, PCLATU
11821 * as copy(PRODL) contains has pc==NULL, by name fails...
11823 if (!copy->pc || !PCI(copy->pc)->pcop) break;
11825 if (copy->pc && PCI(copy->pc)->pcop)
11826 pcop = PCI(copy->pc)->pcop;
11828 /* This code is broken--see above. */
11831 const char *symname = strFromSym(copy->sym);
11834 pic16_InsertCommentAfter (pc->prev, "BUG-ME");
11835 pic16_InsertCommentAfter (pc->prev, "=DF= MOVFF: newpCodeOpregFromStr(%s)", (char *)symname);
11836 //pcop = pic16_newpCodeOpRegFromStr((char *)symname);
11840 newpc = pic16_newpCode(POC_MOVFF, pic16_popGet2p(
11842 pic16_pCodeOpCopy (PCOR2(pci->pcop)->pcop2)));
11844 pic16_InsertCommentAfter (pc->prev, "=DF= MOVFF: SRC op %s replaced by %s", strFromSym(sym1), strFromSym(copy->sym));
11845 pic16_df_saved_bytes += PCI(pc)->isize - PCI(newpc)->isize;
11846 pic16_pCodeReplace (pc, newpc);
11847 assert (val->sym == sym1 && val->acc.access.isRead && !val->acc.access.isWrite);
11848 defmapReplaceSymRef (pc, sym1, copy->sym, 1);
11849 pic16_fixDefmap (pc, newpc);
11853 deleteDefmapChain (©);
11856 if (val) defmapUpdate (list, sym2, pc, val->in_val);
11861 /* cannot optimize */
11866 static void pic16_destructDF (pBlock *pb) {
11869 /* remove old defmaps */
11870 pc = pic16_findNextInstruction (pb->pcHead);
11872 next = pic16_findNextInstruction (pc->next);
11874 assert (isPCI(pc) || isPCAD(pc));
11875 assert (PCI(pc)->pcflow);
11876 deleteDefmapChain (&PCI(pc)->pcflow->defmap);
11877 deleteDefmapChain (&PCI(pc)->pcflow->in_vals);
11878 deleteDefmapChain (&PCI(pc)->pcflow->out_vals);
11883 if (defmap_free || defmap_free_count) {
11884 //fprintf (stderr, "released defmaps: %u -- freeing up memory\n", defmap_free_count);
11885 freeDefmap (&defmap_free);
11886 defmap_free_count = 0;
11890 /* Checks whether a pBlock contains ASMDIRs. */
11891 static int pic16_pBlockHasAsmdirs (pBlock *pb) {
11894 pc = pic16_findNextInstruction (pb->pcHead);
11896 if (isPCAD(pc)) return 1;
11898 pc = pic16_findNextInstruction (pc->next);
11901 /* no PCADs found */
11906 /* Remove MOVFF r0x??, POSTDEC1 and MOVFF PREINC1, r0x?? for otherwise unused registers. */
11907 static int pic16_removeUnusedRegistersDF () {
11910 regs *reg1, *reg2, *reg3;
11911 set *seenRegs = NULL;
11913 int islocal, change = 0;
11916 if (!the_pFile || !the_pFile->pbHead) return 0;
11918 for (pb = the_pFile->pbHead; pb; pb = pb->next) {
11919 //fprintf (stderr, "%s: examining function %s\n", __FUNCTION__, pic16_pBlockGetFunctionName (pb));
11921 /* find set of using pCodes per register */
11922 for (pc = pic16_findNextInstruction (pb->pcHead); pc;
11923 pc = pic16_findNextInstruction(pc->next)) {
11925 cond = PCI(pc)->inCond | PCI(pc)->outCond;
11926 reg1 = reg2 = NULL;
11927 if (cond & PCC_REGISTER) reg1 = pic16_getRegFromInstruction (pc);
11928 if (cond & PCC_REGISTER2) reg2 = pic16_getRegFromInstruction2 (pc);
11931 if (!isinSet (seenRegs, reg1)) reg1->reglives.usedpCodes = NULL;
11932 addSetIfnotP (&seenRegs, reg1);
11933 addSetIfnotP (®1->reglives.usedpCodes, pc);
11936 if (!isinSet (seenRegs, reg2)) reg2->reglives.usedpCodes = NULL;
11937 addSetIfnotP (&seenRegs, reg2);
11938 addSetIfnotP (®2->reglives.usedpCodes, pc);
11942 for (reg1 = setFirstItem (seenRegs); reg1; reg1 = setNextItem (seenRegs)) {
11943 /* may not use pic16_regIsLocal() here -- in interrupt routines
11944 * WREG, PRODx, FSR0x must be saved */
11945 islocal = (reg1->isLocal || reg1->rIdx == pic16_framepnt_lo->rIdx || reg1->rIdx == pic16_framepnt_hi->rIdx);
11946 if (islocal && elementsInSet (reg1->reglives.usedpCodes) == 2) {
11948 for (i=0; i < 2; i++) {
11949 pc = (pCode *) indexSet(reg1->reglives.usedpCodes, i);
11950 if (!pc2) pc2 = pc;
11951 if (!isPCI(pc) || !PCI(pc)->op == POC_MOVFF) continue;
11952 reg2 = pic16_getRegFromInstruction (pc);
11953 reg3 = pic16_getRegFromInstruction2 (pc);
11955 || (reg2->rIdx != pic16_stack_preinc->rIdx
11956 && reg3->rIdx != pic16_stack_postdec->rIdx)) break;
11958 /* both pCodes are MOVFF R,POSTDEC1 / MOVFF PREINC1,R */
11959 //fprintf (stderr, "%s: removing local register %s from %s\n", __FUNCTION__, reg1->name, pic16_pBlockGetFunctionName (pb));
11960 pic16_safepCodeRemove (pc, "removed unused local reg IN");
11961 pic16_safepCodeRemove (pc2, "removed unused local reg OUT");
11965 deleteSet (®1->reglives.usedpCodes);
11968 deleteSet (&seenRegs);
11975 /* Set up pCodeFlow's defmap_ts.
11976 * Needs correctly set up to/from fields. */
11977 static void pic16_createDF (pBlock *pb) {
11981 //fprintf (stderr, "creating DF for pb %p (%s)\n", pb, pic16_pBlockGetFunctionName (pb));
11983 pic16_destructDF (pb);
11985 /* check pBlock: do not analyze pBlocks with ASMDIRs (for now...) */
11986 if (pic16_pBlockHasAsmdirs (pb)) {
11987 //fprintf (stderr, "%s: pBlock contains ASMDIRs -- data flow analysis not performed!\n", __FUNCTION__);
11991 /* integrity check -- we need to reach all flows to guarantee
11992 * correct data flow analysis (reaching definitions, aliveness) */
11994 if (!verifyAllFlowsReachable (pb)) {
11995 fprintf (stderr, "not all flows reachable -- aborting dataflow analysis for %s!\n", pic16_pBlockGetFunctionName (pb));
12000 /* establish new defmaps */
12001 pc = pic16_findNextInstruction (pb->pcHead);
12003 next = pic16_findNextInstruction (pc->next);
12005 assert (PCI(pc)->pcflow);
12006 PCI(pc)->pcflow->defmap = createDefmap (pc, PCI(pc)->pcflow->defmap);
12011 //fprintf (stderr, "%s: creating reaching definitions...\n", __FUNCTION__);
12012 createReachingDefinitions (pb);
12015 /* assign better valnums */
12016 //fprintf (stderr, "assigning valnums for pb %p\n", pb);
12017 pc = pic16_findNextInstruction (pb->pcHead);
12019 next = pic16_findNextInstruction (pc->next);
12021 assert (PCI(pc)->pcflow);
12022 assignValnums (pc);
12029 /* remove dead pCodes */
12030 //fprintf (stderr, "removing dead pCodes in %p (%s)\n", pb, pic16_pBlockGetFunctionName (pb));
12033 pc = pic16_findNextInstruction (pb->pcHead);
12035 next = pic16_findNextInstruction (pc->next);
12037 if (isPCI(pc) && !isPCI_BRANCH(pc) && !pic16_pCodeIsAlive (pc)) {
12038 change += pic16_safepCodeRemove (pc, "=DF= removed dead pCode");
12047 /* ======================================================================== */
12048 /* === VCG DUMPER ROUTINES ================================================ */
12049 /* ======================================================================== */
12050 #if defined (DUMP_DF_GRAPHS) && DUMP_DF_GRAPHS > 0
12051 hTab *dumpedNodes = NULL;
12053 /** Dump VCG header into of. */
12054 static void pic16_vcg_init (FILE *of) {
12055 /* graph defaults */
12056 fprintf (of, "graph:{\n");
12057 fprintf (of, "title:\"graph1\"\n");
12058 fprintf (of, "label:\"graph1\"\n");
12059 fprintf (of, "color:white\n");
12060 fprintf (of, "textcolor:black\n");
12061 fprintf (of, "bordercolor:black\n");
12062 fprintf (of, "borderwidth:1\n");
12063 fprintf (of, "textmode:center\n");
12065 fprintf (of, "layoutalgorithm:dfs\n");
12066 fprintf (of, "late_edge_labels:yes\n");
12067 fprintf (of, "display_edge_labels:yes\n");
12068 fprintf (of, "dirty_edge_labels:yes\n");
12069 fprintf (of, "finetuning:yes\n");
12070 fprintf (of, "ignoresingles:no\n");
12071 fprintf (of, "straight_phase:yes\n");
12072 fprintf (of, "priority_phase:yes\n");
12073 fprintf (of, "manhattan_edges:yes\n");
12074 fprintf (of, "smanhattan_edges:no\n");
12075 fprintf (of, "nearedges:no\n");
12076 fprintf (of, "node_alignment:center\n"); // bottom|top|center
12077 fprintf (of, "port_sharing:no\n");
12078 fprintf (of, "arrowmode:free\n"); // fixed|free
12079 fprintf (of, "crossingphase2:yes\n");
12080 fprintf (of, "crossingoptimization:yes\n");
12081 fprintf (of, "edges:yes\n");
12082 fprintf (of, "nodes:yes\n");
12083 fprintf (of, "splines:no\n");
12085 /* node defaults */
12086 fprintf (of, "node.color:lightyellow\n");
12087 fprintf (of, "node.textcolor:black\n");
12088 fprintf (of, "node.textmode:center\n");
12089 fprintf (of, "node.shape:box\n");
12090 fprintf (of, "node.bordercolor:black\n");
12091 fprintf (of, "node.borderwidth:1\n");
12093 /* edge defaults */
12094 fprintf (of, "edge.textcolor:black\n");
12095 fprintf (of, "edge.color:black\n");
12096 fprintf (of, "edge.thickness:1\n");
12097 fprintf (of, "edge.arrowcolor:black\n");
12098 fprintf (of, "edge.backarrowcolor:black\n");
12099 fprintf (of, "edge.arrowsize:15\n");
12100 fprintf (of, "edge.backarrowsize:15\n");
12101 fprintf (of, "edge.arrowstyle:line\n"); // none|solid|line
12102 fprintf (of, "edge.backarrowstyle:none\n"); // none|solid|line
12103 fprintf (of, "edge.linestyle:continuous\n"); // continuous|solid|dotted|dashed|invisible
12105 fprintf (of, "\n");
12107 /* prepare data structures */
12109 hTabDeleteAll (dumpedNodes);
12110 dumpedNodes = NULL;
12112 dumpedNodes = newHashTable (128);
12115 /** Dump VCG footer into of. */
12116 static void pic16_vcg_close (FILE *of) {
12117 fprintf (of, "}\n");
12120 #define BUF_SIZE 128
12121 #define pcTitle(pc) (SNPRINTF (buf, BUF_SIZE, "n_%p, %p/%u", PCODE(pc), isPCI(pc) ? PCI(pc)->pcflow : NULL, PCODE(pc)->seq), &buf[0])
12124 static int ptrcmp (const void *p1, const void *p2) {
12129 /** Dump a pCode node as VCG to of. */
12130 static void pic16_vcg_dumpnode (pCode *pc, FILE *of) {
12131 char buf[BUF_SIZE];
12133 if (hTabFindByKey (dumpedNodes, (((char *) pc - (char *) 0)>>2) % 128, pc, ptrcmp)) {
12137 hTabAddItemLong (&dumpedNodes, (((char *) pc - (char *) 0)>>2) % 128, pc, pc);
12138 //fprintf (stderr, "dumping %p\n", pc);
12140 /* only dump pCodeInstructions and Flow nodes */
12141 if (!isPCI(pc) && !isPCAD(pc) && !isPCFL(pc)) return;
12144 fprintf (of, "node:{");
12145 fprintf (of, "title:\"%s\" ", pcTitle(pc));
12146 fprintf (of, "label:\"%s\n", pcTitle(pc));
12148 fprintf (of, "<PCFLOW>");
12149 } else if (isPCI(pc) || isPCAD(pc)) {
12150 pc->print (of, pc);
12152 fprintf (of, "<!PCI>");
12154 fprintf (of, "\" ");
12155 fprintf (of, "}\n");
12157 if (1 && isPCFL(pc)) {
12158 defmap_t *map, *prev;
12160 map = PCFL(pc)->defmap;
12163 if (map->sym != 0) {
12166 /* emit definition node */
12167 fprintf (of, "node:{title:\"%s_def%u\" ", pcTitle(pc), i);
12168 fprintf (of, "label:\"");
12172 fprintf (of, "%s%c%c: val %4x|%4x & %02x|%02x, sym %s", (prev == map) ? "" : "\n", map->acc.access.isRead ? 'R' : ' ', map->acc.access.isWrite ? 'W' : ' ', map->in_val, map->val, map->acc.access.in_mask, map->acc.access.mask, strFromSym (map->sym));
12175 } while (map && prev->pc == map->pc);
12178 fprintf (of, "\" ");
12180 fprintf (of, "color:green ");
12181 fprintf (of, "}\n");
12183 /* emit edge to previous definition */
12184 fprintf (of, "edge:{sourcename:\"%s_def%u\" ", pcTitle(pc), i);
12186 fprintf (of, "targetname:\"%s\" ", pcTitle(pc));
12188 fprintf (of, "targetname:\"%s_def%u\" ", pcTitle(pc), i-1);
12190 fprintf (of, "color:green ");
12191 fprintf (of, "}\n");
12194 pic16_vcg_dumpnode (map->pc, of);
12195 fprintf (of, "edge:{sourcename:\"%s_def%u\" ", pcTitle(pc), i);
12196 fprintf (of, "targetname:\"%s\" linestyle:dashed color:lightgreen}\n", pcTitle(map->pc));
12203 /* emit additional nodes (e.g. operands) */
12206 /** Dump a pCode's edges (control flow/data flow) as VCG to of. */
12207 static void pic16_vcg_dumpedges (pCode *pc, FILE *of) {
12208 char buf[BUF_SIZE];
12209 pCodeInstruction *pci;
12213 if (1 && isPCFL(pc)) {
12214 /* emit edges to flow successors */
12216 //fprintf (stderr, "PCFLOWe @ %p\n", pc);
12217 pcfl = setFirstItem (PCFL(pc)->to);
12219 pcfl = ((pCodeFlowLink *) (pcfl))->pcflow;
12220 pic16_vcg_dumpnode (pc, of);
12221 pic16_vcg_dumpnode ((pCode *) pcfl, of);
12222 fprintf (of, "edge:{sourcename:\"%s\" ", pcTitle(pc));
12223 fprintf (of, "targetname:\"%s\" color:lightred linestyle:dashed}\n", pcTitle(pcfl));
12224 pcfl = setNextItem (PCFL(pc)->to);
12228 if (!isPCI(pc) && !isPCAD(pc)) return;
12232 /* emit control flow edges (forward only) */
12236 pic16_vcg_dumpnode (curr->pc, of);
12237 fprintf (of, "edge:{");
12238 fprintf (of, "sourcename:\"%s\" ", pcTitle(pc));
12239 fprintf (of, "targetname:\"%s\" ", pcTitle(curr->pc));
12240 fprintf (of, "color:red ");
12241 fprintf (of, "}\n");
12246 /* dump "flow" edge (link pCode according to pBlock order) */
12249 pcnext = pic16_findNextInstruction (pc->next);
12251 pic16_vcg_dumpnode (pcnext, of);
12252 fprintf (of, "edge:{sourcename:\"%s\" ", pcTitle(pc));
12253 fprintf (of, "targetname:\"%s\" color:red linestyle:solid}\n", pcTitle(pcnext));
12261 pic16_vcg_dumpnode (&pci->pcflow->pc, of);
12262 fprintf (of, "edge:{sourcename:\"%s\" ", pcTitle(pc));
12263 fprintf (of, "targetname:\"%s\" color:lightblue linestyle:dashed}\n", pcTitle (pci->pcflow));
12267 /* emit data flow edges (backward only) */
12268 /* TODO: gather data flow information... */
12271 static void pic16_vcg_dump (FILE *of, pBlock *pb) {
12274 /* check pBlock: do not analyze pBlocks with ASMDIRs (for now...) */
12275 if (pic16_pBlockHasAsmdirs (pb)) {
12276 //fprintf (stderr, "%s: pBlock contains ASMDIRs -- data flow analysis not performed!\n", __FUNCTION__);
12280 for (pc=pb->pcHead; pc; pc = pc->next) {
12281 pic16_vcg_dumpnode (pc, of);
12284 for (pc=pb->pcHead; pc; pc = pc->next) {
12285 pic16_vcg_dumpedges (pc, of);
12289 static void pic16_vcg_dump_default (pBlock *pb) {
12291 char buf[BUF_SIZE];
12294 /* get function name */
12296 while (pc && !isPCF(pc)) pc = pc->next;
12298 SNPRINTF (buf, BUF_SIZE, "%s_%s.vcg", PCF(pc)->modname, PCF(pc)->fname);
12300 SNPRINTF (buf, BUF_SIZE, "pb_%p.vcg", pb);
12303 //fprintf (stderr, "now dumping %s\n", buf);
12304 of = fopen (buf, "w");
12305 pic16_vcg_init (of);
12306 pic16_vcg_dump (of, pb);
12307 pic16_vcg_close (of);
12312 /*** END of helpers for pCode dataflow optimizations ***/