1 /*-------------------------------------------------------------------------
3 pcode.c - post code generation
4 Written By - Scott Dattalo scott@dattalo.com
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 -------------------------------------------------------------------------*/
23 #include "common.h" // Include everything in the SDCC src directory
28 #include "pcodeflow.h"
32 pCode *findFunction(char *fname);
34 static void FixRegisterBanking(pBlock *pb,int cur_bank);
36 #if defined(__BORLANDC__) || defined(_MSC_VER)
37 #define STRCASECMP stricmp
39 #define STRCASECMP strcasecmp
42 /****************************************************************/
43 /****************************************************************/
45 peepCommand peepCommands[] = {
47 {NOTBITSKIP, "_NOTBITSKIP_"},
48 {BITSKIP, "_BITSKIP_"},
49 {INVERTBITSKIP, "_INVERTBITSKIP_"},
56 // Eventually this will go into device dependent files:
57 pCodeOpReg pc_status = {{PO_STATUS, "STATUS"}, -1, NULL,0,NULL};
58 pCodeOpReg pc_indf = {{PO_INDF, "INDF"}, -1, NULL,0,NULL};
59 pCodeOpReg pc_fsr = {{PO_FSR, "FSR"}, -1, NULL,0,NULL};
60 pCodeOpReg pc_intcon = {{PO_INTCON, "INTCON"}, -1, NULL,0,NULL};
61 pCodeOpReg pc_pcl = {{PO_PCL, "PCL"}, -1, NULL,0,NULL};
62 pCodeOpReg pc_pclath = {{PO_PCLATH, "PCLATH"}, -1, NULL,0,NULL};
64 pCodeOpReg pc_wsave = {{PO_GPR_REGISTER, "WSAVE"}, -1, NULL,0,NULL};
65 pCodeOpReg pc_ssave = {{PO_GPR_REGISTER, "SSAVE"}, -1, NULL,0,NULL};
66 pCodeOpReg pc_psave = {{PO_GPR_REGISTER, "PSAVE"}, -1, NULL,0,NULL};
68 static int mnemonics_initialized = 0;
70 static hTab *pic14MnemonicsHash = NULL;
71 static hTab *pic14pCodePeepCommandsHash = NULL;
74 static pFile *the_pFile = NULL;
75 static pBlock *pb_dead_pcodes = NULL;
77 /* Hardcoded flags to change the behavior of the PIC port */
78 static int peepOptimizing = 1; /* run the peephole optimizer if nonzero */
79 static int functionInlining = 1; /* inline functions if nonzero */
80 int debug_verbose = 0; /* Set true to inundate .asm file */
82 // static int GpCodeSequenceNumber = 1;
85 unsigned maxIdx; /* This keeps track of the maximum register index for call tree register reuse */
86 unsigned peakIdx; /* This keeps track of the peak register index for call tree register reuse */
88 extern void RemoveUnusedRegisters(void);
89 extern void RegsUnMapLiveRanges(void);
90 extern void BuildFlowTree(pBlock *pb);
91 extern void pCodeRegOptimizeRegUsage(int level);
92 extern int picIsInitialized(void);
93 extern const char *pCodeOpType(pCodeOp *pcop);
95 /****************************************************************/
96 /* Forward declarations */
97 /****************************************************************/
99 void unlinkpCode(pCode *pc);
101 static void genericAnalyze(pCode *pc);
102 static void AnalyzeGOTO(pCode *pc);
103 static void AnalyzeSKIP(pCode *pc);
104 static void AnalyzeRETURN(pCode *pc);
107 static void genericDestruct(pCode *pc);
108 static void genericPrint(FILE *of,pCode *pc);
110 static void pCodePrintLabel(FILE *of, pCode *pc);
111 static void pCodePrintFunction(FILE *of, pCode *pc);
112 static void pCodeOpPrint(FILE *of, pCodeOp *pcop);
113 static char *get_op_from_instruction( pCodeInstruction *pcc);
114 char *get_op( pCodeOp *pcop,char *buff,size_t buf_size);
115 int pCodePeepMatchLine(pCodePeep *peepBlock, pCode *pcs, pCode *pcd);
116 int pCodePeepMatchRule(pCode *pc);
117 void pBlockStats(FILE *of, pBlock *pb);
118 pBlock *newpBlock(void);
119 pCodeOp *popCopyGPR2Bit(pCodeOp *pc, int bitval);
120 void pCodeRegMapLiveRanges(pBlock *pb);
123 /****************************************************************/
124 /* PIC Instructions */
125 /****************************************************************/
127 pCodeInstruction pciADDWF = {
128 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
141 1,0, // dest, bit instruction
143 0, // literal operand
145 (PCC_W | PCC_REGISTER), // inCond
146 (PCC_REGISTER | PCC_Z) // outCond
149 pCodeInstruction pciADDFW = {
150 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
163 0,0, // dest, bit instruction
165 0, // literal operand
167 (PCC_W | PCC_REGISTER), // inCond
168 (PCC_W | PCC_Z) // outCond
171 pCodeInstruction pciADDLW = {
172 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
185 0,0, // dest, bit instruction
187 1, // literal operand
189 (PCC_W | PCC_LITERAL), // inCond
190 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
193 pCodeInstruction pciANDLW = {
194 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
207 0,0, // dest, bit instruction
209 1, // literal operand
211 (PCC_W | PCC_LITERAL), // inCond
212 (PCC_W | PCC_Z) // outCond
215 pCodeInstruction pciANDWF = {
216 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
229 1,0, // dest, bit instruction
231 0, // literal operand
233 (PCC_W | PCC_REGISTER), // inCond
234 (PCC_REGISTER | PCC_Z) // outCond
237 pCodeInstruction pciANDFW = {
238 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
251 0,0, // dest, bit instruction
253 0, // literal operand
255 (PCC_W | PCC_REGISTER), // inCond
256 (PCC_W | PCC_Z) // outCond
259 pCodeInstruction pciBCF = {
260 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
273 1,1, // dest, bit instruction
275 0, // literal operand
277 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
278 PCC_REGISTER // outCond
281 pCodeInstruction pciBSF = {
282 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
295 1,1, // dest, bit instruction
297 0, // literal operand
299 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
300 (PCC_REGISTER | PCC_EXAMINE_PCOP) // outCond
303 pCodeInstruction pciBTFSC = {
304 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
317 0,1, // dest, bit instruction
319 0, // literal operand
321 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
322 PCC_EXAMINE_PCOP // outCond
325 pCodeInstruction pciBTFSS = {
326 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
339 0,1, // dest, bit instruction
341 0, // literal operand
343 (PCC_REGISTER | PCC_EXAMINE_PCOP), // inCond
344 PCC_EXAMINE_PCOP // outCond
347 pCodeInstruction pciCALL = {
348 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
361 0,0, // dest, bit instruction
363 0, // literal operand
369 pCodeInstruction pciCOMF = {
370 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
383 1,0, // dest, bit instruction
385 0, // literal operand
387 PCC_REGISTER, // inCond
388 PCC_REGISTER // outCond
391 pCodeInstruction pciCOMFW = {
392 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
405 0,0, // dest, bit instruction
407 0, // literal operand
409 PCC_REGISTER, // inCond
413 pCodeInstruction pciCLRF = {
414 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
427 0,0, // dest, bit instruction
429 0, // literal operand
432 PCC_REGISTER // outCond
435 pCodeInstruction pciCLRW = {
436 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
449 0,0, // dest, bit instruction
451 0, // literal operand
457 pCodeInstruction pciCLRWDT = {
458 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
471 0,0, // dest, bit instruction
473 0, // literal operand
479 pCodeInstruction pciDECF = {
480 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
493 1,0, // dest, bit instruction
495 0, // literal operand
497 PCC_REGISTER, // inCond
498 PCC_REGISTER // outCond
501 pCodeInstruction pciDECFW = {
502 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
515 0,0, // dest, bit instruction
517 0, // literal operand
519 PCC_REGISTER, // inCond
523 pCodeInstruction pciDECFSZ = {
524 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
537 1,0, // dest, bit instruction
539 0, // literal operand
541 PCC_REGISTER, // inCond
542 PCC_REGISTER // outCond
545 pCodeInstruction pciDECFSZW = {
546 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
559 0,0, // dest, bit instruction
561 0, // literal operand
563 PCC_REGISTER, // inCond
567 pCodeInstruction pciGOTO = {
568 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
581 0,0, // dest, bit instruction
583 0, // literal operand
589 pCodeInstruction pciINCF = {
590 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
603 1,0, // dest, bit instruction
605 0, // literal operand
607 PCC_REGISTER, // inCond
608 PCC_REGISTER // outCond
611 pCodeInstruction pciINCFW = {
612 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
625 0,0, // dest, bit instruction
627 0, // literal operand
629 PCC_REGISTER, // inCond
633 pCodeInstruction pciINCFSZ = {
634 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
647 1,0, // dest, bit instruction
649 0, // literal operand
651 PCC_REGISTER, // inCond
652 PCC_REGISTER // outCond
655 pCodeInstruction pciINCFSZW = {
656 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
669 0,0, // dest, bit instruction
671 0, // literal operand
673 PCC_REGISTER, // inCond
677 pCodeInstruction pciIORWF = {
678 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
691 1,0, // dest, bit instruction
693 0, // literal operand
695 (PCC_W | PCC_REGISTER), // inCond
696 (PCC_REGISTER | PCC_Z) // outCond
699 pCodeInstruction pciIORFW = {
700 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
713 0,0, // dest, bit instruction
715 0, // literal operand
717 (PCC_W | PCC_REGISTER), // inCond
718 (PCC_W | PCC_Z) // outCond
721 pCodeInstruction pciIORLW = {
722 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
735 0,0, // dest, bit instruction
737 1, // literal operand
739 (PCC_W | PCC_LITERAL), // inCond
740 (PCC_W | PCC_Z) // outCond
743 pCodeInstruction pciMOVF = {
744 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
757 1,0, // dest, bit instruction
759 0, // literal operand
761 PCC_REGISTER, // inCond
765 pCodeInstruction pciMOVFW = {
766 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
779 0,0, // dest, bit instruction
781 0, // literal operand
783 PCC_REGISTER, // inCond
784 (PCC_W | PCC_Z) // outCond
787 pCodeInstruction pciMOVWF = {
788 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
801 0,0, // dest, bit instruction
803 0, // literal operand
806 PCC_REGISTER // outCond
809 pCodeInstruction pciMOVLW = {
810 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
822 0,0, // dest, bit instruction
824 1, // literal operand
826 (PCC_NONE | PCC_LITERAL), // inCond
830 pCodeInstruction pciNOP = {
831 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
843 0,0, // dest, bit instruction
845 0, // literal operand
851 pCodeInstruction pciRETFIE = {
852 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
865 0,0, // dest, bit instruction
867 0, // literal operand
870 PCC_NONE // outCond (not true... affects the GIE bit too)
873 pCodeInstruction pciRETLW = {
874 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
887 0,0, // dest, bit instruction
889 1, // literal operand
891 PCC_LITERAL, // inCond
895 pCodeInstruction pciRETURN = {
896 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
909 0,0, // dest, bit instruction
911 0, // literal operand
917 pCodeInstruction pciRLF = {
918 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
931 1,0, // dest, bit instruction
933 0, // literal operand
935 (PCC_C | PCC_REGISTER), // inCond
936 (PCC_REGISTER | PCC_Z | PCC_C | PCC_DC) // outCond
939 pCodeInstruction pciRLFW = {
940 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
953 0,0, // dest, bit instruction
955 0, // literal operand
957 (PCC_C | PCC_REGISTER), // inCond
958 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
961 pCodeInstruction pciRRF = {
962 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
975 1,0, // dest, bit instruction
977 0, // literal operand
979 (PCC_C | PCC_REGISTER), // inCond
980 (PCC_REGISTER | PCC_Z | PCC_C | PCC_DC) // outCond
983 pCodeInstruction pciRRFW = {
984 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
997 0,0, // dest, bit instruction
999 0, // literal operand
1001 (PCC_C | PCC_REGISTER), // inCond
1002 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1005 pCodeInstruction pciSUBWF = {
1006 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1012 NULL, // from branch
1019 1,0, // dest, bit instruction
1020 0,0, // branch, skip
1021 0, // literal operand
1023 (PCC_W | PCC_REGISTER), // inCond
1024 (PCC_REGISTER | PCC_Z) // outCond
1027 pCodeInstruction pciSUBFW = {
1028 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1034 NULL, // from branch
1041 0,0, // dest, bit instruction
1042 0,0, // branch, skip
1043 0, // literal operand
1045 (PCC_W | PCC_REGISTER), // inCond
1046 (PCC_W | PCC_Z) // outCond
1049 pCodeInstruction pciSUBLW = {
1050 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1056 NULL, // from branch
1063 0,0, // dest, bit instruction
1064 0,0, // branch, skip
1065 1, // literal operand
1067 (PCC_W | PCC_LITERAL), // inCond
1068 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1071 pCodeInstruction pciSWAPF = {
1072 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1078 NULL, // from branch
1085 1,0, // dest, bit instruction
1086 0,0, // branch, skip
1087 0, // literal operand
1089 (PCC_REGISTER), // inCond
1090 (PCC_REGISTER) // outCond
1093 pCodeInstruction pciSWAPFW = {
1094 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1100 NULL, // from branch
1107 0,0, // dest, bit instruction
1108 0,0, // branch, skip
1109 0, // literal operand
1111 (PCC_REGISTER), // inCond
1115 pCodeInstruction pciTRIS = {
1116 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1122 NULL, // from branch
1129 0,0, // dest, bit instruction
1130 0,0, // branch, skip
1131 0, // literal operand
1134 PCC_REGISTER // outCond
1137 pCodeInstruction pciXORWF = {
1138 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1144 NULL, // from branch
1151 1,0, // dest, bit instruction
1152 0,0, // branch, skip
1153 0, // literal operand
1155 (PCC_W | PCC_REGISTER), // inCond
1156 (PCC_REGISTER | PCC_Z) // outCond
1159 pCodeInstruction pciXORFW = {
1160 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1166 NULL, // from branch
1173 0,0, // dest, bit instruction
1174 0,0, // branch, skip
1175 0, // literal operand
1177 (PCC_W | PCC_REGISTER), // inCond
1178 (PCC_W | PCC_Z) // outCond
1181 pCodeInstruction pciXORLW = {
1182 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1188 NULL, // from branch
1195 0,0, // dest, bit instruction
1196 0,0, // branch, skip
1197 1, // literal operand
1199 (PCC_W | PCC_LITERAL), // inCond
1200 (PCC_W | PCC_Z | PCC_C | PCC_DC) // outCond
1204 pCodeInstruction pciBANKSEL = {
1205 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1211 NULL, // from branch
1218 0,0, // dest, bit instruction
1219 0,0, // branch, skip
1220 0, // literal operand
1223 PCC_REGISTER // outCond
1226 pCodeInstruction pciPAGESEL = {
1227 {PC_OPCODE, NULL, NULL, 0, 0, NULL,
1233 NULL, // from branch
1240 0,0, // dest, bit instruction
1241 0,0, // branch, skip
1242 0, // literal operand
1245 PCC_REGISTER // outCond
1248 pCodeInstruction *pic14Mnemonics[MAX_PIC14MNEMONICS];
1251 /*-----------------------------------------------------------------*/
1252 /* return a unique ID number to assist pCodes debuging */
1253 /*-----------------------------------------------------------------*/
1254 unsigned PCodeID(void) {
1255 static unsigned int pcodeId = 1; /* unique ID number to be assigned to all pCodes */
1257 static unsigned int stop;
1258 if (pcodeId == 1448)
1259 stop++; // Place break point here
1264 #ifdef HAVE_VSNPRINTF
1265 // Alas, vsnprintf is not ANSI standard, and does not exist
1266 // on Solaris (and probably other non-Gnu flavored Unixes).
1268 /*-----------------------------------------------------------------*/
1269 /* SAFE_snprintf - like snprintf except the string pointer is */
1270 /* after the string has been printed to. This is */
1271 /* useful for printing to string as though if it */
1272 /* were a stream. */
1273 /*-----------------------------------------------------------------*/
1274 void SAFE_snprintf(char **str, size_t *size, const char *format, ...)
1282 va_start(val, format);
1284 vsnprintf(*str, *size, format, val);
1289 if((size_t)len > *size) {
1290 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
1291 fprintf(stderr,"len = %d is > str size %d\n",len,(int)*size);
1299 #else // HAVE_VSNPRINTF
1301 // This version is *not* safe, despite the name.
1303 void SAFE_snprintf(char **str, size_t *size, const char *format, ...)
1307 static char buffer[1024]; /* grossly conservative, but still not inherently safe */
1312 va_start(val, format);
1314 vsprintf(buffer, format, val);
1317 len = strlen(buffer);
1319 fprintf(stderr,"WARNING, it looks like %s has overflowed\n",__FUNCTION__);
1320 fprintf(stderr,"len = %d is > str size %d\n",len,*size);
1323 strcpy(*str, buffer);
1329 #endif // HAVE_VSNPRINTF
1332 extern void initStack(int base_address, int size);
1333 extern regs *allocProcessorRegister(int rIdx, char * name, short po_type, int alias);
1334 extern regs *allocInternalRegister(int rIdx, char * name, short po_type, int alias);
1335 extern void init_pic(char *);
1337 void pCodeInitRegisters(void)
1339 static int initialized=0;
1340 int shareBankAddress,stkSize;
1346 init_pic(port->processor);
1347 shareBankAddress = 0x7f; /* FIXME - some PIC ICs like 16C7X which do not have a shared bank need a different approach. */
1348 if ((unsigned)shareBankAddress > getMaxRam()) /* If total RAM is less than 0x7f as with 16f84 then reduce shareBankAddress to fit */
1349 shareBankAddress = (int)getMaxRam();
1350 stkSize = 15; /* Set pseudo stack size to 15, on multi memory bank ICs this leaves room for WSAVE (used for interrupts) to fit into the shared portion of the memory bank */
1351 initStack(shareBankAddress, stkSize); /* Putting the pseudo stack in shared memory so all modules use the same register when passing fn parameters */
1353 pc_status.r = allocProcessorRegister(IDX_STATUS,"STATUS", PO_STATUS, 0x180);
1354 pc_pcl.r = allocProcessorRegister(IDX_PCL,"PCL", PO_PCL, 0x80);
1355 pc_pclath.r = allocProcessorRegister(IDX_PCLATH,"PCLATH", PO_PCLATH, 0x180);
1356 pc_fsr.r = allocProcessorRegister(IDX_FSR,"FSR", PO_FSR, 0x180);
1357 pc_indf.r = allocProcessorRegister(IDX_INDF,"INDF", PO_INDF, 0x180);
1358 pc_intcon.r = allocProcessorRegister(IDX_INTCON,"INTCON", PO_INTCON, 0x180);
1360 pc_status.rIdx = IDX_STATUS;
1361 pc_fsr.rIdx = IDX_FSR;
1362 pc_indf.rIdx = IDX_INDF;
1363 pc_intcon.rIdx = IDX_INTCON;
1364 pc_pcl.rIdx = IDX_PCL;
1365 pc_pclath.rIdx = IDX_PCLATH;
1367 pc_wsave.r = allocInternalRegister(IDX_WSAVE,pc_wsave.pcop.name,pc_wsave.pcop.type, 0x180); /* Interrupt storage for working register - must be same address in all banks ie section SHAREBANK. */
1368 pc_ssave.r = allocInternalRegister(IDX_SSAVE,pc_ssave.pcop.name,pc_ssave.pcop.type, 0); /* Interrupt storage for status register. */
1369 pc_psave.r = allocInternalRegister(IDX_PSAVE,pc_psave.pcop.name,pc_psave.pcop.type, 0); /* Interrupt storage for pclath register. */
1371 pc_wsave.rIdx = pc_wsave.r->rIdx;
1372 pc_ssave.rIdx = pc_ssave.r->rIdx;
1373 pc_psave.rIdx = pc_psave.r->rIdx;
1375 pc_wsave.r->isFixed = 1; /* Some PIC ICs do not have a sharebank - this register needs to be reserved across all banks. */
1376 pc_wsave.r->address = shareBankAddress-stkSize;
1377 pc_ssave.r->isFixed = 1; /* This register must be in the first bank. */
1378 pc_ssave.r->address = shareBankAddress-stkSize-1;
1379 pc_psave.r->isFixed = 1; /* This register must be in the first bank. */
1380 pc_psave.r->address = shareBankAddress-stkSize-2;
1382 /* probably should put this in a separate initialization routine */
1383 pb_dead_pcodes = newpBlock();
1387 /*-----------------------------------------------------------------*/
1388 /* mnem2key - convert a pic mnemonic into a hash key */
1389 /* (BTW - this spreads the mnemonics quite well) */
1391 /*-----------------------------------------------------------------*/
1393 int mnem2key(char const *mnem)
1402 key += toupper(*mnem++) +1;
1406 return (key & 0x1f);
1410 void pic14initMnemonics(void)
1415 pCodeInstruction *pci;
1417 if(mnemonics_initialized)
1420 //FIXME - probably should NULL out the array before making the assignments
1421 //since we check the array contents below this initialization.
1423 pic14Mnemonics[POC_ADDLW] = &pciADDLW;
1424 pic14Mnemonics[POC_ADDWF] = &pciADDWF;
1425 pic14Mnemonics[POC_ADDFW] = &pciADDFW;
1426 pic14Mnemonics[POC_ANDLW] = &pciANDLW;
1427 pic14Mnemonics[POC_ANDWF] = &pciANDWF;
1428 pic14Mnemonics[POC_ANDFW] = &pciANDFW;
1429 pic14Mnemonics[POC_BCF] = &pciBCF;
1430 pic14Mnemonics[POC_BSF] = &pciBSF;
1431 pic14Mnemonics[POC_BTFSC] = &pciBTFSC;
1432 pic14Mnemonics[POC_BTFSS] = &pciBTFSS;
1433 pic14Mnemonics[POC_CALL] = &pciCALL;
1434 pic14Mnemonics[POC_COMF] = &pciCOMF;
1435 pic14Mnemonics[POC_COMFW] = &pciCOMFW;
1436 pic14Mnemonics[POC_CLRF] = &pciCLRF;
1437 pic14Mnemonics[POC_CLRW] = &pciCLRW;
1438 pic14Mnemonics[POC_CLRWDT] = &pciCLRWDT;
1439 pic14Mnemonics[POC_DECF] = &pciDECF;
1440 pic14Mnemonics[POC_DECFW] = &pciDECFW;
1441 pic14Mnemonics[POC_DECFSZ] = &pciDECFSZ;
1442 pic14Mnemonics[POC_DECFSZW] = &pciDECFSZW;
1443 pic14Mnemonics[POC_GOTO] = &pciGOTO;
1444 pic14Mnemonics[POC_INCF] = &pciINCF;
1445 pic14Mnemonics[POC_INCFW] = &pciINCFW;
1446 pic14Mnemonics[POC_INCFSZ] = &pciINCFSZ;
1447 pic14Mnemonics[POC_INCFSZW] = &pciINCFSZW;
1448 pic14Mnemonics[POC_IORLW] = &pciIORLW;
1449 pic14Mnemonics[POC_IORWF] = &pciIORWF;
1450 pic14Mnemonics[POC_IORFW] = &pciIORFW;
1451 pic14Mnemonics[POC_MOVF] = &pciMOVF;
1452 pic14Mnemonics[POC_MOVFW] = &pciMOVFW;
1453 pic14Mnemonics[POC_MOVLW] = &pciMOVLW;
1454 pic14Mnemonics[POC_MOVWF] = &pciMOVWF;
1455 pic14Mnemonics[POC_NOP] = &pciNOP;
1456 pic14Mnemonics[POC_RETFIE] = &pciRETFIE;
1457 pic14Mnemonics[POC_RETLW] = &pciRETLW;
1458 pic14Mnemonics[POC_RETURN] = &pciRETURN;
1459 pic14Mnemonics[POC_RLF] = &pciRLF;
1460 pic14Mnemonics[POC_RLFW] = &pciRLFW;
1461 pic14Mnemonics[POC_RRF] = &pciRRF;
1462 pic14Mnemonics[POC_RRFW] = &pciRRFW;
1463 pic14Mnemonics[POC_SUBLW] = &pciSUBLW;
1464 pic14Mnemonics[POC_SUBWF] = &pciSUBWF;
1465 pic14Mnemonics[POC_SUBFW] = &pciSUBFW;
1466 pic14Mnemonics[POC_SWAPF] = &pciSWAPF;
1467 pic14Mnemonics[POC_SWAPFW] = &pciSWAPFW;
1468 pic14Mnemonics[POC_TRIS] = &pciTRIS;
1469 pic14Mnemonics[POC_XORLW] = &pciXORLW;
1470 pic14Mnemonics[POC_XORWF] = &pciXORWF;
1471 pic14Mnemonics[POC_XORFW] = &pciXORFW;
1472 pic14Mnemonics[POC_BANKSEL] = &pciBANKSEL;
1473 pic14Mnemonics[POC_PAGESEL] = &pciPAGESEL;
1475 for(i=0; i<MAX_PIC14MNEMONICS; i++)
1476 if(pic14Mnemonics[i])
1477 hTabAddItem(&pic14MnemonicsHash, mnem2key(pic14Mnemonics[i]->mnemonic), pic14Mnemonics[i]);
1478 pci = hTabFirstItem(pic14MnemonicsHash, &key);
1481 DFPRINTF((stderr, "element %d key %d, mnem %s\n",i++,key,pci->mnemonic));
1482 pci = hTabNextItem(pic14MnemonicsHash, &key);
1485 mnemonics_initialized = 1;
1488 int getpCodePeepCommand(char *cmd);
1490 int getpCode(char *mnem,unsigned dest)
1493 pCodeInstruction *pci;
1494 int key = mnem2key(mnem);
1496 if(!mnemonics_initialized)
1497 pic14initMnemonics();
1499 pci = hTabFirstItemWK(pic14MnemonicsHash, key);
1503 if(STRCASECMP(pci->mnemonic, mnem) == 0) {
1504 if((pci->num_ops <= 1) || (pci->isModReg == dest) || (pci->isBitInst))
1508 pci = hTabNextItemWK (pic14MnemonicsHash);
1515 /*-----------------------------------------------------------------*
1516 * pic14initpCodePeepCommands
1518 *-----------------------------------------------------------------*/
1519 void pic14initpCodePeepCommands(void)
1527 hTabAddItem(&pic14pCodePeepCommandsHash,
1528 mnem2key(peepCommands[i].cmd), &peepCommands[i]);
1530 } while (peepCommands[i].cmd);
1532 pcmd = hTabFirstItem(pic14pCodePeepCommandsHash, &key);
1535 //fprintf(stderr, "peep command %s key %d\n",pcmd->cmd,pcmd->id);
1536 pcmd = hTabNextItem(pic14pCodePeepCommandsHash, &key);
1541 /*-----------------------------------------------------------------
1544 *-----------------------------------------------------------------*/
1546 int getpCodePeepCommand(char *cmd)
1550 int key = mnem2key(cmd);
1553 pcmd = hTabFirstItemWK(pic14pCodePeepCommandsHash, key);
1556 // fprintf(stderr," comparing %s to %s\n",pcmd->cmd,cmd);
1557 if(STRCASECMP(pcmd->cmd, cmd) == 0) {
1561 pcmd = hTabNextItemWK (pic14pCodePeepCommandsHash);
1568 char getpBlock_dbName(pBlock *pb)
1574 return pb->cmemmap->dbName;
1578 void pBlockConvert2ISR(pBlock *pb)
1589 /*-----------------------------------------------------------------*/
1590 /* movepBlock2Head - given the dbname of a pBlock, move all */
1591 /* instances to the front of the doubly linked */
1592 /* list of pBlocks */
1593 /*-----------------------------------------------------------------*/
1595 void movepBlock2Head(char dbName)
1602 pb = the_pFile->pbHead;
1606 if(getpBlock_dbName(pb) == dbName) {
1607 pBlock *pbn = pb->next;
1608 pb->next = the_pFile->pbHead;
1609 the_pFile->pbHead->prev = pb;
1610 the_pFile->pbHead = pb;
1613 pb->prev->next = pbn;
1615 // If the pBlock that we just moved was the last
1616 // one in the link of all of the pBlocks, then we
1617 // need to point the tail to the block just before
1618 // the one we moved.
1619 // Note: if pb->next is NULL, then pb must have
1620 // been the last pBlock in the chain.
1623 pbn->prev = pb->prev;
1625 the_pFile->pbTail = pb->prev;
1636 void copypCode(FILE *of, char dbName)
1640 if(!of || !the_pFile)
1643 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
1644 if(getpBlock_dbName(pb) == dbName) {
1652 void pcode_test(void)
1655 DFPRINTF((stderr,"pcode is alive!\n"));
1665 /* create the file name */
1666 strcpy(buffer,dstFileName);
1667 strcat(buffer,".p");
1669 if( !(pFile = fopen(buffer, "w" ))) {
1670 werror(E_FILE_OPEN_ERR,buffer);
1674 fprintf(pFile,"pcode dump\n\n");
1676 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
1677 fprintf(pFile,"\n\tNew pBlock\n\n");
1679 fprintf(pFile,"%s",pb->cmemmap->sname);
1681 fprintf(pFile,"internal pblock");
1683 fprintf(pFile,", dbName =%c\n",getpBlock_dbName(pb));
1684 printpBlock(pFile,pb);
1688 /*-----------------------------------------------------------------*/
1689 /* int RegCond(pCodeOp *pcop) - if pcop points to the STATUS reg- */
1690 /* ister, RegCond will return the bit being referenced. */
1692 /* fixme - why not just OR in the pcop bit field */
1693 /*-----------------------------------------------------------------*/
1695 static int RegCond(pCodeOp *pcop)
1701 if (pcop->type == PO_GPR_BIT) {
1702 char *name = pcop->name;
1704 name = PCOR(pcop)->r->name;
1705 // if (strcmp(name, pc_status.pcop.name) != 0) { <<< This breaks the peep 2 optimisation
1706 switch(PCORB(pcop)->bit) {
1720 /*-----------------------------------------------------------------*/
1721 /* newpCode - create and return a newly initialized pCode */
1723 /* fixme - rename this */
1725 /* The purpose of this routine is to create a new Instruction */
1726 /* pCode. This is called by gen.c while the assembly code is being */
1730 /* PIC_OPCODE op - the assembly instruction we wish to create. */
1731 /* (note that the op is analogous to but not the */
1732 /* same thing as the opcode of the instruction.) */
1733 /* pCdoeOp *pcop - pointer to the operand of the instruction. */
1736 /* a pointer to the new malloc'd pCode is returned. */
1740 /*-----------------------------------------------------------------*/
1741 pCode *newpCode (PIC_OPCODE op, pCodeOp *pcop)
1743 pCodeInstruction *pci ;
1745 if(!mnemonics_initialized)
1746 pic14initMnemonics();
1748 pci = Safe_calloc(1, sizeof(pCodeInstruction));
1750 if((op>=0) && (op < MAX_PIC14MNEMONICS) && pic14Mnemonics[op]) {
1751 memcpy(pci, pic14Mnemonics[op], sizeof(pCodeInstruction));
1752 pci->pc.id = PCodeID();
1755 if(pci->inCond & PCC_EXAMINE_PCOP)
1756 pci->inCond |= RegCond(pcop);
1758 if(pci->outCond & PCC_EXAMINE_PCOP)
1759 pci->outCond |= RegCond(pcop);
1761 pci->pc.prev = pci->pc.next = NULL;
1762 return (pCode *)pci;
1765 fprintf(stderr, "pCode mnemonic error %s,%d\n",__FUNCTION__,__LINE__);
1771 /*-----------------------------------------------------------------*/
1772 /* newpCodeWild - create a "wild" as in wild card pCode */
1774 /* Wild pcodes are used during the peep hole optimizer to serve */
1775 /* as place holders for any instruction. When a snippet of code is */
1776 /* compared to a peep hole rule, the wild card opcode will match */
1777 /* any instruction. However, the optional operand and label are */
1778 /* additional qualifiers that must also be matched before the */
1779 /* line (of assembly code) is declared matched. Note that the */
1780 /* operand may be wild too. */
1782 /* Note, a wild instruction is specified just like a wild var: */
1783 /* %4 ; A wild instruction, */
1784 /* See the peeph.def file for additional examples */
1786 /*-----------------------------------------------------------------*/
1788 pCode *newpCodeWild(int pCodeID, pCodeOp *optional_operand, pCodeOp *optional_label)
1793 pcw = Safe_calloc(1,sizeof(pCodeWild));
1795 pcw->pci.pc.type = PC_WILD;
1796 pcw->pci.pc.prev = pcw->pci.pc.next = NULL;
1797 pcw->id = PCodeID();
1798 pcw->pci.from = pcw->pci.to = pcw->pci.label = NULL;
1799 pcw->pci.pc.pb = NULL;
1801 // pcw->pci.pc.analyze = genericAnalyze;
1802 pcw->pci.pc.destruct = genericDestruct;
1803 pcw->pci.pc.print = genericPrint;
1805 pcw->id = pCodeID; // this is the 'n' in %n
1806 pcw->operand = optional_operand;
1807 pcw->label = optional_label;
1809 pcw->mustBeBitSkipInst = 0;
1810 pcw->mustNotBeBitSkipInst = 0;
1811 pcw->invertBitSkipInst = 0;
1813 return ( (pCode *)pcw);
1817 /*-----------------------------------------------------------------*/
1818 /* newPcodeInlineP - create a new pCode from a char string */
1819 /*-----------------------------------------------------------------*/
1822 pCode *newpCodeInlineP(char *cP)
1827 pcc = Safe_calloc(1,sizeof(pCodeComment));
1829 pcc->pc.type = PC_INLINE;
1830 pcc->pc.prev = pcc->pc.next = NULL;
1831 pcc->pc.id = PCodeID();
1832 //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
1835 // pcc->pc.analyze = genericAnalyze;
1836 pcc->pc.destruct = genericDestruct;
1837 pcc->pc.print = genericPrint;
1840 pcc->comment = Safe_strdup(cP);
1842 pcc->comment = NULL;
1844 return ( (pCode *)pcc);
1848 /*-----------------------------------------------------------------*/
1849 /* newPcodeCharP - create a new pCode from a char string */
1850 /*-----------------------------------------------------------------*/
1852 pCode *newpCodeCharP(char *cP)
1857 pcc = Safe_calloc(1,sizeof(pCodeComment));
1859 pcc->pc.type = PC_COMMENT;
1860 pcc->pc.prev = pcc->pc.next = NULL;
1861 pcc->pc.id = PCodeID();
1862 //pcc->pc.from = pcc->pc.to = pcc->pc.label = NULL;
1865 // pcc->pc.analyze = genericAnalyze;
1866 pcc->pc.destruct = genericDestruct;
1867 pcc->pc.print = genericPrint;
1870 pcc->comment = Safe_strdup(cP);
1872 pcc->comment = NULL;
1874 return ( (pCode *)pcc);
1878 /*-----------------------------------------------------------------*/
1879 /* newpCodeFunction - */
1880 /*-----------------------------------------------------------------*/
1883 pCode *newpCodeFunction(char *mod,char *f,int isPublic)
1887 pcf = Safe_calloc(1,sizeof(pCodeFunction));
1888 //_ALLOC(pcf,sizeof(pCodeFunction));
1890 pcf->pc.type = PC_FUNCTION;
1891 pcf->pc.prev = pcf->pc.next = NULL;
1892 pcf->pc.id = PCodeID();
1893 //pcf->pc.from = pcf->pc.to = pcf->pc.label = NULL;
1896 // pcf->pc.analyze = genericAnalyze;
1897 pcf->pc.destruct = genericDestruct;
1898 pcf->pc.print = pCodePrintFunction;
1903 //_ALLOC_ATOMIC(pcf->modname,strlen(mod)+1);
1904 pcf->modname = Safe_calloc(1,strlen(mod)+1);
1905 strcpy(pcf->modname,mod);
1907 pcf->modname = NULL;
1910 //_ALLOC_ATOMIC(pcf->fname,strlen(f)+1);
1911 pcf->fname = Safe_calloc(1,strlen(f)+1);
1912 strcpy(pcf->fname,f);
1916 pcf->isPublic = (unsigned)isPublic;
1918 return ( (pCode *)pcf);
1922 /*-----------------------------------------------------------------*/
1924 /*-----------------------------------------------------------------*/
1925 void destructpCodeFlow(pCode *pc)
1927 if(!pc || !isPCFL(pc))
1936 deleteSet(&PCFL(pc)->registers);
1937 deleteSet(&PCFL(pc)->from);
1938 deleteSet(&PCFL(pc)->to);
1943 pCode *newpCodeFlow(void )
1947 //_ALLOC(pcflow,sizeof(pCodeFlow));
1948 pcflow = Safe_calloc(1,sizeof(pCodeFlow));
1950 pcflow->pc.type = PC_FLOW;
1951 pcflow->pc.prev = pcflow->pc.next = NULL;
1952 pcflow->pc.pb = NULL;
1954 // pcflow->pc.analyze = genericAnalyze;
1955 pcflow->pc.destruct = destructpCodeFlow;
1956 pcflow->pc.print = genericPrint;
1958 pcflow->pc.seq = GpcFlowSeq++;
1960 pcflow->from = pcflow->to = NULL;
1962 pcflow->inCond = PCC_NONE;
1963 pcflow->outCond = PCC_NONE;
1965 pcflow->firstBank = 'U'; /* Undetermined */
1966 pcflow->lastBank = 'U'; /* Undetermined */
1968 pcflow->FromConflicts = 0;
1969 pcflow->ToConflicts = 0;
1973 pcflow->registers = newSet();
1975 return ( (pCode *)pcflow);
1979 /*-----------------------------------------------------------------*/
1980 /*-----------------------------------------------------------------*/
1981 pCodeFlowLink *newpCodeFlowLink(pCodeFlow *pcflow)
1983 pCodeFlowLink *pcflowLink;
1985 pcflowLink = Safe_calloc(1,sizeof(pCodeFlowLink));
1987 pcflowLink->pcflow = pcflow;
1988 pcflowLink->bank_conflict = 0;
1993 /*-----------------------------------------------------------------*/
1994 /* newpCodeCSource - create a new pCode Source Symbol */
1995 /*-----------------------------------------------------------------*/
1997 pCode *newpCodeCSource(int ln, char *f, char *l)
2002 pccs = Safe_calloc(1,sizeof(pCodeCSource));
2004 pccs->pc.type = PC_CSOURCE;
2005 pccs->pc.prev = pccs->pc.next = NULL;
2006 pccs->pc.id = PCodeID();
2009 pccs->pc.destruct = genericDestruct;
2010 pccs->pc.print = genericPrint;
2012 pccs->line_number = ln;
2014 pccs->line = Safe_strdup(l);
2019 pccs->file_name = Safe_strdup(f);
2021 pccs->file_name = NULL;
2023 return ( (pCode *)pccs);
2027 /*******************************************************************/
2028 /* pic16_newpCodeAsmDir - create a new pCode Assembler Directive */
2029 /* added by VR 6-Jun-2003 */
2030 /*******************************************************************/
2032 pCode *newpCodeAsmDir(char *asdir, char *argfmt, ...)
2039 pcad = Safe_calloc(1, sizeof(pCodeAsmDir));
2040 pcad->pci.pc.type = PC_ASMDIR;
2041 pcad->pci.pc.prev = pcad->pci.pc.next = NULL;
2042 pcad->pci.pc.pb = NULL;
2043 pcad->pci.pc.destruct = genericDestruct;
2044 pcad->pci.pc.print = genericPrint;
2046 if(asdir && *asdir) {
2048 while(isspace(*asdir))asdir++; // strip any white space from the beginning
2050 pcad->directive = Safe_strdup( asdir );
2053 va_start(ap, argfmt);
2055 memset(buffer, 0, sizeof(buffer));
2056 if(argfmt && *argfmt)
2057 vsprintf(buffer, argfmt, ap);
2061 while(isspace(*lbp))lbp++;
2064 pcad->arg = Safe_strdup( lbp );
2066 return ((pCode *)pcad);
2069 /*-----------------------------------------------------------------*/
2070 /* pCodeLabelDestruct - free memory used by a label. */
2071 /*-----------------------------------------------------------------*/
2072 static void pCodeLabelDestruct(pCode *pc)
2078 if((pc->type == PC_LABEL) && PCL(pc)->label)
2079 free(PCL(pc)->label);
2085 pCode *newpCodeLabel(char *name, int key)
2091 pcl = Safe_calloc(1,sizeof(pCodeLabel) );
2093 pcl->pc.type = PC_LABEL;
2094 pcl->pc.prev = pcl->pc.next = NULL;
2095 pcl->pc.id = PCodeID();
2096 //pcl->pc.from = pcl->pc.to = pcl->pc.label = NULL;
2099 // pcl->pc.analyze = genericAnalyze;
2100 pcl->pc.destruct = pCodeLabelDestruct;
2101 pcl->pc.print = pCodePrintLabel;
2107 sprintf(s,"_%05d_DS_",key);
2112 pcl->label = Safe_strdup(s);
2114 //fprintf(stderr,"newpCodeLabel: key=%d, name=%s\n",key, ((s)?s:""));
2115 return ( (pCode *)pcl);
2120 /*-----------------------------------------------------------------*/
2121 /* newpBlock - create and return a pointer to a new pBlock */
2122 /*-----------------------------------------------------------------*/
2123 pBlock *newpBlock(void)
2128 PpB = Safe_calloc(1,sizeof(pBlock) );
2129 PpB->next = PpB->prev = NULL;
2131 PpB->function_entries = PpB->function_exits = PpB->function_calls = NULL;
2132 PpB->tregisters = NULL;
2134 PpB->FlowTree = NULL;
2140 /*-----------------------------------------------------------------*/
2141 /* newpCodeChain - create a new chain of pCodes */
2142 /*-----------------------------------------------------------------*
2144 * This function will create a new pBlock and the pointer to the
2145 * pCode that is passed in will be the first pCode in the block.
2146 *-----------------------------------------------------------------*/
2149 pBlock *newpCodeChain(memmap *cm,char c, pCode *pc)
2152 pBlock *pB = newpBlock();
2154 pB->pcHead = pB->pcTail = pc;
2161 /*-----------------------------------------------------------------*/
2162 /* newpCodeOpLabel - Create a new label given the key */
2163 /* Note, a negative key means that the label is part of wild card */
2164 /* (and hence a wild card label) used in the pCodePeep */
2165 /* optimizations). */
2166 /*-----------------------------------------------------------------*/
2168 pCodeOp *newpCodeOpLabel(char *name, int key)
2171 static int label_key=-1;
2175 pcop = Safe_calloc(1,sizeof(pCodeOpLabel) );
2176 pcop->type = PO_LABEL;
2181 sprintf(s=buffer,"_%05d_DS_",key);
2183 s = name, key = label_key--;
2185 PCOLAB(pcop)->offset = 0;
2187 pcop->name = Safe_strdup(s);
2189 ((pCodeOpLabel *)pcop)->key = key;
2191 //fprintf(stderr,"newpCodeOpLabel: key=%d, name=%s\n",key,((s)?s:""));
2195 /*-----------------------------------------------------------------*/
2196 /*-----------------------------------------------------------------*/
2197 pCodeOp *newpCodeOpLit(int lit)
2203 pcop = Safe_calloc(1,sizeof(pCodeOpLit) );
2204 pcop->type = PO_LITERAL;
2208 sprintf(s,"0x%02x",lit);
2210 pcop->name = Safe_strdup(s);
2213 ((pCodeOpLit *)pcop)->lit = lit;
2218 /*-----------------------------------------------------------------*/
2219 /*-----------------------------------------------------------------*/
2220 pCodeOp *newpCodeOpImmd(char *name, int offset, int index, int code_space, int is_func)
2224 pcop = Safe_calloc(1,sizeof(pCodeOpImmd) );
2225 pcop->type = PO_IMMEDIATE;
2228 pcop->name = Safe_strdup(name);
2231 r = dirregWithName(name);
2235 //fprintf(stderr, " newpCodeOpImmd reg %s exists\n",name);
2236 PCOI(pcop)->rIdx = r->rIdx;
2238 //fprintf(stderr, " newpCodeOpImmd reg %s doesn't exist\n",name);
2239 PCOI(pcop)->rIdx = -1;
2241 //fprintf(stderr,"%s %s %d\n",__FUNCTION__,name,offset);
2246 PCOI(pcop)->index = index;
2247 PCOI(pcop)->offset = offset;
2248 PCOI(pcop)->_const = code_space;
2249 PCOI(pcop)->_function = is_func;
2254 /*-----------------------------------------------------------------*/
2255 /*-----------------------------------------------------------------*/
2256 pCodeOp *newpCodeOpWild(int id, pCodeWildBlock *pcwb, pCodeOp *subtype)
2262 if(!pcwb || !subtype) {
2263 fprintf(stderr, "Wild opcode declaration error: %s-%d\n",__FILE__,__LINE__);
2267 pcop = Safe_calloc(1,sizeof(pCodeOpWild));
2268 pcop->type = PO_WILD;
2269 sprintf(s,"%%%d",id);
2270 pcop->name = Safe_strdup(s);
2272 PCOW(pcop)->id = id;
2273 PCOW(pcop)->pcwb = pcwb;
2274 PCOW(pcop)->subtype = subtype;
2275 PCOW(pcop)->matched = NULL;
2279 /*-----------------------------------------------------------------*/
2280 /* Find a symbol with matching name */
2281 /*-----------------------------------------------------------------*/
2282 static symbol *symFindWithName(memmap * map, const char *name)
2286 for (sym = setFirstItem(map->syms); sym; sym = setNextItem (map->syms)) {
2287 if (sym->rname && (strcmp(sym->rname,name)==0))
2293 /*-----------------------------------------------------------------*/
2294 /*-----------------------------------------------------------------*/
2295 pCodeOp *newpCodeOpBit(char *name, int ibit, int inBitSpace)
2300 pcop = Safe_calloc(1,sizeof(pCodeOpRegBit) );
2301 pcop->type = PO_GPR_BIT;
2303 PCORB(pcop)->bit = ibit;
2304 PCORB(pcop)->inBitSpace = inBitSpace;
2306 if (name) r = regFindWithName(name);
2308 // Register has not been allocated - check for symbol information
2310 sym = symFindWithName(bit, name);
2311 if (!sym) sym = symFindWithName(sfrbit, name);
2312 if (!sym) sym = symFindWithName(sfr, name);
2314 r = allocNewDirReg(sym->etype,name);
2320 PCOR(pcop)->rIdx = r->rIdx;
2322 pcop->name = Safe_strdup(name);
2323 PCOR(pcop)->r = NULL;
2324 PCOR(pcop)->rIdx = 0;
2329 /*-----------------------------------------------------------------*
2330 * pCodeOp *newpCodeOpReg(int rIdx) - allocate a new register
2332 * If rIdx >=0 then a specific register from the set of registers
2333 * will be selected. If rIdx <0, then a new register will be searched
2335 *-----------------------------------------------------------------*/
2337 pCodeOp *newpCodeOpReg(int rIdx)
2341 pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
2346 PCOR(pcop)->rIdx = rIdx;
2347 PCOR(pcop)->r = pic14_regWithIdx(rIdx);
2349 PCOR(pcop)->r = pic14_findFreeReg(REG_GPR);
2352 PCOR(pcop)->rIdx = PCOR(pcop)->r->rIdx;
2356 pcop->type = PCOR(pcop)->r->pc_type;
2361 pCodeOp *newpCodeOpRegFromStr(char *name)
2365 pcop = Safe_calloc(1,sizeof(pCodeOpReg) );
2366 PCOR(pcop)->r = allocRegByName(name, 1);
2367 PCOR(pcop)->rIdx = PCOR(pcop)->r->rIdx;
2368 pcop->type = PCOR(pcop)->r->pc_type;
2369 pcop->name = PCOR(pcop)->r->name;
2374 pCodeOp *newpCodeOpStr(char *name)
2378 pcop = Safe_calloc(1,sizeof(pCodeOpStr));
2379 pcop->type = PO_STR;
2380 pcop->name = Safe_strdup(name);
2382 PCOS(pcop)->isPublic = 0;
2388 /*-----------------------------------------------------------------*/
2389 /*-----------------------------------------------------------------*/
2391 pCodeOp *newpCodeOp(char *name, PIC_OPTYPE type)
2398 pcop = newpCodeOpBit(name, -1,0);
2402 pcop = newpCodeOpLit(-1);
2406 pcop = newpCodeOpLabel(NULL,-1);
2410 pcop = newpCodeOpReg(-1);
2413 case PO_GPR_POINTER:
2414 case PO_GPR_REGISTER:
2416 pcop = newpCodeOpRegFromStr(name);
2418 pcop = newpCodeOpReg(-1);
2422 pcop = newpCodeOpStr(name);
2426 pcop = Safe_calloc(1,sizeof(pCodeOp) );
2429 pcop->name = Safe_strdup(name);
2437 /*-----------------------------------------------------------------*/
2438 /*-----------------------------------------------------------------*/
2439 void pCodeConstString(char *name, char *value)
2444 // fprintf(stderr, " %s %s %s\n",__FUNCTION__,name,value);
2449 pb = newpCodeChain(NULL, 'P',newpCodeCharP("; Starting pCode block"));
2453 sprintf(buffer,"; %s = %s",name,value);
2454 for (i=strlen(buffer); i--; ) {
2455 unsigned char c = buffer[i];
2456 if (c=='\r' || c=='\n') {
2457 memmove(buffer+i+1,buffer+i,strlen(buffer)-i+1);
2459 if (c=='\r') buffer[i+1] = 'r';
2460 else if (c=='\n') buffer[i+1] = 'n';
2464 addpCode2pBlock(pb,newpCodeCharP(buffer));
2465 addpCode2pBlock(pb,newpCodeLabel(name,-1));
2468 addpCode2pBlock(pb,newpCode(POC_RETLW,newpCodeOpLit(*value)));
2474 /*-----------------------------------------------------------------*/
2475 /*-----------------------------------------------------------------*/
2476 void pCodeReadCodeTable(void)
2480 fprintf(stderr, " %s\n",__FUNCTION__);
2482 pb = newpCodeChain(NULL, 'P',newpCodeCharP("; Starting pCode block"));
2486 addpCode2pBlock(pb,newpCodeCharP("; ReadCodeTable - built in function"));
2487 addpCode2pBlock(pb,newpCodeCharP("; Inputs: temp1,temp2 = code pointer"));
2488 addpCode2pBlock(pb,newpCodeCharP("; Outpus: W (from RETLW at temp2:temp1)"));
2489 addpCode2pBlock(pb,newpCodeLabel("ReadCodeTable:",-1));
2491 addpCode2pBlock(pb,newpCode(POC_MOVFW,newpCodeOpRegFromStr("temp2")));
2492 addpCode2pBlock(pb,newpCode(POC_MOVWF,newpCodeOpRegFromStr("PCLATH")));
2493 addpCode2pBlock(pb,newpCode(POC_MOVFW,newpCodeOpRegFromStr("temp1")));
2494 addpCode2pBlock(pb,newpCode(POC_MOVWF,newpCodeOpRegFromStr("PCL")));
2499 /*-----------------------------------------------------------------*/
2500 /* addpCode2pBlock - place the pCode into the pBlock linked list */
2501 /*-----------------------------------------------------------------*/
2502 void addpCode2pBlock(pBlock *pb, pCode *pc)
2509 /* If this is the first pcode to be added to a block that
2510 * was initialized with a NULL pcode, then go ahead and
2511 * make this pcode the head and tail */
2512 pb->pcHead = pb->pcTail = pc;
2515 pb->pcTail->next = pc;
2517 pc->prev = pb->pcTail;
2524 /*-----------------------------------------------------------------*/
2525 /* addpBlock - place a pBlock into the pFile */
2526 /*-----------------------------------------------------------------*/
2527 void addpBlock(pBlock *pb)
2529 // fprintf(stderr," Adding pBlock: dbName =%c\n",getpBlock_dbName(pb));
2532 /* First time called, we'll pass through here. */
2533 //_ALLOC(the_pFile,sizeof(pFile));
2534 the_pFile = Safe_calloc(1,sizeof(pFile));
2535 the_pFile->pbHead = the_pFile->pbTail = pb;
2536 the_pFile->functions = NULL;
2540 the_pFile->pbTail->next = pb;
2541 pb->prev = the_pFile->pbTail;
2543 the_pFile->pbTail = pb;
2546 /*-----------------------------------------------------------------*/
2547 /* removepBlock - remove a pBlock from the pFile */
2548 /*-----------------------------------------------------------------*/
2549 void removepBlock(pBlock *pb)
2557 //fprintf(stderr," Removing pBlock: dbName =%c\n",getpBlock_dbName(pb));
2559 for(pbs = the_pFile->pbHead; pbs; pbs = pbs->next) {
2562 if(pbs == the_pFile->pbHead)
2563 the_pFile->pbHead = pbs->next;
2565 if (pbs == the_pFile->pbTail)
2566 the_pFile->pbTail = pbs->prev;
2569 pbs->next->prev = pbs->prev;
2572 pbs->prev->next = pbs->next;
2579 fprintf(stderr, "Warning: call to %s:%s didn't find pBlock\n",__FILE__,__FUNCTION__);
2583 /*-----------------------------------------------------------------*/
2584 /* printpCode - write the contents of a pCode to a file */
2585 /*-----------------------------------------------------------------*/
2586 void printpCode(FILE *of, pCode *pc)
2597 fprintf(of,"warning - unable to print pCode\n");
2600 /*-----------------------------------------------------------------*/
2601 /* printpBlock - write the contents of a pBlock to a file */
2602 /*-----------------------------------------------------------------*/
2603 void printpBlock(FILE *of, pBlock *pb)
2613 for(pc = pb->pcHead; pc; pc = pc->next)
2618 /*-----------------------------------------------------------------*/
2620 /* pCode processing */
2624 /*-----------------------------------------------------------------*/
2626 void unlinkpCode(pCode *pc)
2632 fprintf(stderr,"Unlinking: ");
2633 printpCode(stderr, pc);
2636 pc->prev->next = pc->next;
2638 pc->next->prev = pc->prev;
2640 pc->prev = pc->next = NULL;
2644 /*-----------------------------------------------------------------*/
2645 /*-----------------------------------------------------------------*/
2647 static void genericDestruct(pCode *pc)
2653 /* For instructions, tell the register (if there's one used)
2654 * that it's no longer needed */
2655 regs *reg = getRegFromInstruction(pc);
2657 deleteSetItem (&(reg->reglives.usedpCodes),pc);
2660 /* Instead of deleting the memory used by this pCode, mark
2661 * the object as bad so that if there's a pointer to this pCode
2662 * dangling around somewhere then (hopefully) when the type is
2663 * checked we'll catch it.
2668 addpCode2pBlock(pb_dead_pcodes, pc);
2675 /*-----------------------------------------------------------------*/
2676 /* Copies the pCodeInstruction flow pointer from source pCode */
2677 /*-----------------------------------------------------------------*/
2678 static void CopyFlow(pCodeInstruction *pcd, pCode *pcs) {
2680 pCodeFlow *pcflow = 0;
2681 for (p=pcs; p; p=p->prev) {
2683 pcflow = PCI(p)->pcflow;
2687 pcflow = (pCodeFlow*)p;
2691 PCI(pcd)->pcflow = pcflow;
2694 /*-----------------------------------------------------------------*/
2695 /* pCodeInsertAfter - splice in the pCode chain starting with pc2 */
2696 /* into the pCode chain containing pc1 */
2697 /*-----------------------------------------------------------------*/
2698 void pCodeInsertAfter(pCode *pc1, pCode *pc2)
2704 pc2->next = pc1->next;
2706 pc1->next->prev = pc2;
2712 /* If this is an instrution type propogate the flow */
2714 CopyFlow(PCI(pc2),pc1);
2717 /*------------------------------------------------------------------*/
2718 /* pCodeInsertBefore - splice in the pCode chain starting with pc2 */
2719 /* into the pCode chain containing pc1 */
2720 /*------------------------------------------------------------------*/
2721 void pCodeInsertBefore(pCode *pc1, pCode *pc2)
2727 pc2->prev = pc1->prev;
2729 pc1->prev->next = pc2;
2735 /* If this is an instrution type propogate the flow */
2737 CopyFlow(PCI(pc2),pc1);
2740 /*-----------------------------------------------------------------*/
2741 /* pCodeOpCopy - copy a pcode operator */
2742 /*-----------------------------------------------------------------*/
2743 pCodeOp *pCodeOpCopy(pCodeOp *pcop)
2745 pCodeOp *pcopnew=NULL;
2750 switch(pcop->type) {
2753 //DFPRINTF((stderr,"pCodeOpCopy bit\n"));
2754 pcopnew = Safe_calloc(1,sizeof(pCodeOpRegBit) );
2755 PCORB(pcopnew)->bit = PCORB(pcop)->bit;
2756 PCORB(pcopnew)->inBitSpace = PCORB(pcop)->inBitSpace;
2761 /* Here we expand the wild card into the appropriate type: */
2762 /* By recursively calling pCodeOpCopy */
2763 //DFPRINTF((stderr,"pCodeOpCopy wild\n"));
2764 if(PCOW(pcop)->matched)
2765 pcopnew = pCodeOpCopy(PCOW(pcop)->matched);
2768 pcopnew = pCodeOpCopy(PCOW(pcop)->subtype);
2769 pcopnew->name = Safe_strdup(PCOW(pcop)->pcwb->vars[PCOW(pcop)->id]);
2770 //DFPRINTF((stderr,"copied a wild op named %s\n",pcopnew->name));
2777 //DFPRINTF((stderr,"pCodeOpCopy label\n"));
2778 pcopnew = Safe_calloc(1,sizeof(pCodeOpLabel) );
2779 PCOLAB(pcopnew)->key = PCOLAB(pcop)->key;
2783 pcopnew = Safe_calloc(1,sizeof(pCodeOpImmd) );
2784 PCOI(pcopnew)->index = PCOI(pcop)->index;
2785 PCOI(pcopnew)->offset = PCOI(pcop)->offset;
2786 PCOI(pcopnew)->_const = PCOI(pcop)->_const;
2787 PCOI(pcopnew)->_function = PCOI(pcop)->_function;
2791 //DFPRINTF((stderr,"pCodeOpCopy lit\n"));
2792 pcopnew = Safe_calloc(1,sizeof(pCodeOpLit) );
2793 PCOL(pcopnew)->lit = PCOL(pcop)->lit;
2798 pcopnew = newpCodeOpBit(pcop->name, PCORB(pcop)->bit,PCORB(pcop)->inBitSpace);
2799 PCOR(pcopnew)->r = PCOR(pcop)->r;
2800 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2801 DFPRINTF((stderr," pCodeOpCopy Bit -register index\n"));
2805 case PO_GPR_POINTER:
2806 case PO_GPR_REGISTER:
2810 //DFPRINTF((stderr,"pCodeOpCopy GPR register\n"));
2811 pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
2812 PCOR(pcopnew)->r = PCOR(pcop)->r;
2813 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2814 PCOR(pcopnew)->instance = PCOR(pcop)->instance;
2815 DFPRINTF((stderr," register index %d\n", PCOR(pcop)->r->rIdx));
2819 //fprintf(stderr,"pCodeOpCopy PO_DIR\n");
2820 pcopnew = Safe_calloc(1,sizeof(pCodeOpReg) );
2821 PCOR(pcopnew)->r = PCOR(pcop)->r;
2822 PCOR(pcopnew)->rIdx = PCOR(pcop)->rIdx;
2823 PCOR(pcopnew)->instance = PCOR(pcop)->instance;
2826 DFPRINTF((stderr,"pCodeOpCopy PO_STATUS\n"));
2827 case PO_SFR_REGISTER:
2835 //DFPRINTF((stderr,"pCodeOpCopy register type %d\n", pcop->type));
2836 pcopnew = Safe_calloc(1,sizeof(pCodeOp) );
2840 pcopnew->type = pcop->type;
2842 pcopnew->name = Safe_strdup(pcop->name);
2844 pcopnew->name = NULL;
2849 /*-----------------------------------------------------------------*/
2850 /* popCopyReg - copy a pcode operator */
2851 /*-----------------------------------------------------------------*/
2852 pCodeOp *popCopyReg(pCodeOpReg *pc)
2856 pcor = Safe_calloc(1,sizeof(pCodeOpReg) );
2857 pcor->pcop.type = pc->pcop.type;
2859 if(!(pcor->pcop.name = Safe_strdup(pc->pcop.name)))
2860 fprintf(stderr,"oops %s %d",__FILE__,__LINE__);
2862 pcor->pcop.name = NULL;
2864 if (pcor->pcop.type == PO_IMMEDIATE){
2865 PCOL(pcor)->lit = PCOL(pc)->lit;
2868 pcor->rIdx = pc->rIdx;
2872 //DEBUGpic14_emitcode ("; ***","%s , copying %s, rIdx=%d",__FUNCTION__,pc->pcop.name,pc->rIdx);
2877 /*-----------------------------------------------------------------*/
2878 /* pCodeInstructionCopy - copy a pCodeInstructionCopy */
2879 /*-----------------------------------------------------------------*/
2880 pCode *pCodeInstructionCopy(pCodeInstruction *pci,int invert)
2882 pCodeInstruction *new_pci;
2885 new_pci = PCI(newpCode(pci->inverted_op,pci->pcop));
2887 new_pci = PCI(newpCode(pci->op,pci->pcop));
2889 new_pci->pc.pb = pci->pc.pb;
2890 new_pci->from = pci->from;
2891 new_pci->to = pci->to;
2892 new_pci->label = pci->label;
2893 new_pci->pcflow = pci->pcflow;
2895 return PCODE(new_pci);
2898 /*-----------------------------------------------------------------*/
2899 /*-----------------------------------------------------------------*/
2900 void pCodeDeleteChain(pCode *f,pCode *t)
2905 DFPRINTF((stderr,"delete pCode:\n"));
2907 //f->print(stderr,f);
2908 //f->delete(f); this dumps core...
2913 /*-----------------------------------------------------------------*/
2914 /*-----------------------------------------------------------------*/
2915 void pBlockRegs(FILE *of, pBlock *pb)
2920 r = setFirstItem(pb->tregisters);
2922 r = setNextItem(pb->tregisters);
2927 /*-----------------------------------------------------------------*/
2928 /*-----------------------------------------------------------------*/
2929 char *get_op(pCodeOp *pcop,char *buffer, size_t size)
2934 int use_buffer = 1; // copy the string to the passed buffer pointer
2939 use_buffer = 0; // Don't bother copying the string to the buffer.
2943 switch(pcop->type) {
2947 SAFE_snprintf(&buffer,&size,"%s",PCOR(pcop)->r->name);
2950 //return PCOR(pcop)->r->name;
2954 if (PCOR(pcop)->r->type == REG_STK)
2955 r = typeRegWithIdx(PCOR(pcop)->r->rIdx,REG_STK,1);
2957 r = pic14_regWithIdx(PCOR(pcop)->r->rIdx);
2960 SAFE_snprintf(&buffer,&size,"%s",r->name);
2970 if(PCOI(pcop)->_const) {
2972 if( PCOI(pcop)->offset && PCOI(pcop)->offset<4) {
2973 switch(PCOI(pcop)->offset) {
2975 SAFE_snprintf(&s,&size,"low %s",pcop->name);
2978 SAFE_snprintf(&s,&size,"high %s",pcop->name);
2981 SAFE_snprintf(&s,&size,"(((%s+%d) >> %d)&0xff)",
2984 8 * PCOI(pcop)->offset );
2987 SAFE_snprintf(&s,&size,"LOW(%s+%d)",pcop->name,PCOI(pcop)->index);
2990 if( PCOI(pcop)->index) { // && PCOI(pcc->pcop)->offset<4) {
2991 SAFE_snprintf(&s,&size,"(%s + %d)",
2993 PCOI(pcop)->index );
2995 switch(PCOI(pcop)->offset) {
2997 SAFE_snprintf(&s,&size,"%s",pcop->name);
3000 SAFE_snprintf(&s,&size,"high %s",pcop->name);
3003 SAFE_snprintf(&s,&size,"(%s >> %d)&0xff",pcop->name, 8*PCOI(pcop)->offset);
3012 //size = sizeof(buffer);
3013 if( PCOR(pcop)->instance) {
3014 SAFE_snprintf(&s,&size,"(%s + %d)",
3016 PCOR(pcop)->instance );
3017 //fprintf(stderr,"PO_DIR %s\n",buffer);
3019 SAFE_snprintf(&s,&size,"%s",pcop->name);
3025 if(PCOLAB(pcop)->offset == 1)
3026 SAFE_snprintf(&s,&size,"HIGH(%s)",pcop->name);
3028 SAFE_snprintf(&s,&size,"%s",pcop->name);
3035 SAFE_snprintf(&buffer,&size,"%s",PCOR(pcop)->r->name);
3038 return PCOR(pcop)->r->name;
3041 /* fall through to the default case */
3045 SAFE_snprintf(&buffer,&size,"%s",pcop->name);
3053 printf("PIC port internal warning: (%s:%d) %s not found\n",
3058 return "NO operand";
3062 /*-----------------------------------------------------------------*/
3063 /*-----------------------------------------------------------------*/
3064 static char *get_op_from_instruction( pCodeInstruction *pcc)
3068 return get_op(pcc->pcop,NULL,0);
3070 return ("ERROR Null: get_op_from_instruction");
3074 /*-----------------------------------------------------------------*/
3075 /*-----------------------------------------------------------------*/
3076 static void pCodeOpPrint(FILE *of, pCodeOp *pcop)
3078 fprintf(of,"pcodeopprint- not implemented\n");
3081 /*-----------------------------------------------------------------*/
3082 /* pCode2str - convert a pCode instruction to string */
3083 /*-----------------------------------------------------------------*/
3084 char *pCode2str(char *str, size_t size, pCode *pc)
3092 SAFE_snprintf(&s,&size, "\t%s\t", PCI(pc)->mnemonic);
3094 if( (PCI(pc)->num_ops >= 1) && (PCI(pc)->pcop)) {
3096 if(PCI(pc)->isBitInst) {
3097 if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3098 char *name = PCI(pc)->pcop->name;
3100 name = PCOR(PCI(pc)->pcop)->r->name;
3101 if( (((pCodeOpRegBit *)(PCI(pc)->pcop))->inBitSpace) )
3102 SAFE_snprintf(&s,&size,"(%s >> 3), (%s & 7)", name, name);
3104 SAFE_snprintf(&s,&size,"%s,%d", name,
3105 (((pCodeOpRegBit *)(PCI(pc)->pcop))->bit)&7);
3106 } else if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3107 SAFE_snprintf(&s,&size,"%s,%d", get_op_from_instruction(PCI(pc)),PCORB(PCI(pc)->pcop)->bit);
3109 SAFE_snprintf(&s,&size,"%s,0 ; ?bug", get_op_from_instruction(PCI(pc)));
3110 //PCI(pc)->pcop->t.bit );
3112 if(PCI(pc)->pcop->type == PO_GPR_BIT) {
3113 if( PCI(pc)->num_ops == 2)
3114 SAFE_snprintf(&s,&size,"(%s >> 3),%c",get_op_from_instruction(PCI(pc)),((PCI(pc)->isModReg) ? 'F':'W'));
3116 SAFE_snprintf(&s,&size,"(1 << (%s & 7))",get_op_from_instruction(PCI(pc)));
3118 SAFE_snprintf(&s,&size,"%s",get_op_from_instruction(PCI(pc)));
3119 if( PCI(pc)->num_ops == 2)
3120 SAFE_snprintf(&s,&size,",%c", ( (PCI(pc)->isModReg) ? 'F':'W'));
3127 /* assuming that comment ends with a \n */
3128 SAFE_snprintf(&s,&size,";%s", ((pCodeComment *)pc)->comment);
3132 /* assuming that inline code ends with a \n */
3133 SAFE_snprintf(&s,&size,"%s", ((pCodeComment *)pc)->comment);
3137 SAFE_snprintf(&s,&size,";label=%s, key=%d\n",PCL(pc)->label,PCL(pc)->key);
3140 SAFE_snprintf(&s,&size,";modname=%s,function=%s: id=%d\n",PCF(pc)->modname,PCF(pc)->fname);
3143 SAFE_snprintf(&s,&size,";\tWild opcode: id=%d\n",PCW(pc)->id);
3146 SAFE_snprintf(&s,&size,";\t--FLOW change\n");
3149 SAFE_snprintf(&s,&size,";#CSRC\t%s %d\n; %s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
3152 if(PCAD(pc)->directive) {
3153 SAFE_snprintf(&s,&size,"\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
3154 } else if(PCAD(pc)->arg) {
3155 /* special case to handle inline labels without a tab */
3156 SAFE_snprintf(&s,&size,"%s\n", PCAD(pc)->arg);
3161 SAFE_snprintf(&s,&size,";A bad pCode is being used\n");
3167 /*-----------------------------------------------------------------*/
3168 /* genericPrint - the contents of a pCode to a file */
3169 /*-----------------------------------------------------------------*/
3170 static void genericPrint(FILE *of, pCode *pc)
3177 fprintf(of,";%s\n", ((pCodeComment *)pc)->comment);
3181 fprintf(of,"%s\n", ((pCodeComment *)pc)->comment);
3185 // If the opcode has a label, print that first
3188 pCodeInstruction *pci = PCI(pc);
3189 pBranch *pbl = pci->label;
3190 while(pbl && pbl->pc) {
3191 if(pbl->pc->type == PC_LABEL)
3192 pCodePrintLabel(of, pbl->pc);
3197 genericPrint(of,PCODE(pci->cline));
3200 pCode2str(str, 256, pc);
3202 fprintf(of,"%s",str);
3206 pCodeOpReg *pcor = PCOR(pci->pcop);
3207 fprintf(of, "\t;id=%u,key=%03x",pc->id,pc->seq);
3209 fprintf(of,",flow seq=%03x",pci->pcflow->pc.seq);
3210 if (pcor && pcor->pcop.type==PO_GPR_TEMP && !pcor->r->isFixed)
3211 fprintf(of,",rIdx=r0x%X",pcor->rIdx);
3216 pBranch *dpb = pc->to; // debug
3218 switch ( dpb->pc->type) {
3220 fprintf(of, "\t;%s", PCI(dpb->pc)->mnemonic);
3223 fprintf(of, "\t;label %d", PCL(dpb->pc)->key);
3226 fprintf(of, "\t;function %s", ( (PCF(dpb->pc)->fname) ? (PCF(dpb->pc)->fname) : "[END]"));
3229 fprintf(of, "\t;flow");
3243 fprintf(of,";\tWild opcode: id=%d\n",PCW(pc)->id);
3244 if(PCW(pc)->pci.label)
3245 pCodePrintLabel(of, PCW(pc)->pci.label->pc);
3247 if(PCW(pc)->operand) {
3248 fprintf(of,";\toperand ");
3249 pCodeOpPrint(of,PCW(pc)->operand );
3255 fprintf(of,";<>Start of new flow, seq=0x%x",pc->seq);
3256 if(PCFL(pc)->ancestor)
3257 fprintf(of," ancestor = 0x%x", PCODE(PCFL(pc)->ancestor)->seq);
3263 fprintf(of,";#CSRC\t%s %d\n; %s\n", PCCS(pc)->file_name, PCCS(pc)->line_number, PCCS(pc)->line);
3268 pBranch *pbl = PCAD(pc)->pci.label;
3269 while(pbl && pbl->pc) {
3270 if(pbl->pc->type == PC_LABEL)
3271 pCodePrintLabel(of, pbl->pc);
3275 if(PCAD(pc)->directive) {
3276 fprintf(of, "\t%s%s%s\n", PCAD(pc)->directive, PCAD(pc)->arg?"\t":"", PCAD(pc)->arg?PCAD(pc)->arg:"");
3279 /* special case to handle inline labels without tab */
3280 fprintf(of, "%s\n", PCAD(pc)->arg);
3286 fprintf(of,"unknown pCode type %d\n",pc->type);
3290 /*-----------------------------------------------------------------*/
3291 /* pCodePrintFunction - prints function begin/end */
3292 /*-----------------------------------------------------------------*/
3294 static void pCodePrintFunction(FILE *of, pCode *pc)
3300 if( ((pCodeFunction *)pc)->modname)
3301 fprintf(of,"F_%s",((pCodeFunction *)pc)->modname);
3303 if(PCF(pc)->fname) {
3304 pBranch *exits = PCF(pc)->to;
3306 fprintf(of,"%s\t;Function start\n",PCF(pc)->fname);
3309 exits = exits->next;
3312 fprintf(of,"; %d exit point%c\n",i, ((i==1) ? ' ':'s'));
3315 if((PCF(pc)->from &&
3316 PCF(pc)->from->pc->type == PC_FUNCTION &&
3317 PCF(PCF(pc)->from->pc)->fname) )
3318 fprintf(of,"; exit point of %s\n",PCF(PCF(pc)->from->pc)->fname);
3320 fprintf(of,"; exit point [can't find entry point]\n");
3323 /*-----------------------------------------------------------------*/
3324 /* pCodePrintLabel - prints label */
3325 /*-----------------------------------------------------------------*/
3327 static void pCodePrintLabel(FILE *of, pCode *pc)
3334 fprintf(of,"%s\n",PCL(pc)->label);
3335 else if (PCL(pc)->key >=0)
3336 fprintf(of,"_%05d_DS_:\n",PCL(pc)->key);
3338 fprintf(of,";wild card label: id=%d\n",-PCL(pc)->key);
3342 /*-----------------------------------------------------------------*/
3343 /* unlinkpCodeFromBranch - Search for a label in a pBranch and */
3344 /* remove it if it is found. */
3345 /*-----------------------------------------------------------------*/
3346 static void unlinkpCodeFromBranch(pCode *pcl , pCode *pc)
3352 if(pcl->type == PC_OPCODE || pcl->type == PC_INLINE || pcl->type == PC_ASMDIR)
3353 b = PCI(pcl)->label;
3355 fprintf(stderr, "LINE %d. can't unlink from non opcode\n",__LINE__);
3359 //fprintf (stderr, "%s \n",__FUNCTION__);
3360 //pcl->print(stderr,pcl);
3361 //pc->print(stderr,pc);
3364 //fprintf (stderr, "found label\n");
3368 bprev->next = b->next; /* Not first pCode in chain */
3372 PCI(pcl)->label = b->next; /* First pCode in chain */
3375 return; /* A label can't occur more than once */
3382 /*-----------------------------------------------------------------*/
3383 /*-----------------------------------------------------------------*/
3384 pBranch * pBranchAppend(pBranch *h, pBranch *n)
3403 /*-----------------------------------------------------------------*/
3404 /* pBranchLink - given two pcodes, this function will link them */
3405 /* together through their pBranches */
3406 /*-----------------------------------------------------------------*/
3407 static void pBranchLink(pCodeFunction *f, pCodeFunction *t)
3411 // Declare a new branch object for the 'from' pCode.
3413 //_ALLOC(b,sizeof(pBranch));
3414 b = Safe_calloc(1,sizeof(pBranch));
3415 b->pc = PCODE(t); // The link to the 'to' pCode.
3418 f->to = pBranchAppend(f->to,b);
3420 // Now do the same for the 'to' pCode.
3422 //_ALLOC(b,sizeof(pBranch));
3423 b = Safe_calloc(1,sizeof(pBranch));
3427 t->from = pBranchAppend(t->from,b);
3432 /*-----------------------------------------------------------------*/
3433 /* pBranchFind - find the pBranch in a pBranch chain that contains */
3435 /*-----------------------------------------------------------------*/
3436 static pBranch *pBranchFind(pBranch *pb,pCode *pc)
3449 /*-----------------------------------------------------------------*/
3450 /* pCodeUnlink - Unlink the given pCode from its pCode chain. */
3451 /*-----------------------------------------------------------------*/
3452 static void pCodeUnlink(pCode *pc)
3457 if(!pc->prev || !pc->next) {
3458 fprintf(stderr,"unlinking bad pCode in %s:%d\n",__FILE__,__LINE__);
3462 /* first remove the pCode from the chain */
3463 pc->prev->next = pc->next;
3464 pc->next->prev = pc->prev;
3466 /* Now for the hard part... */
3468 /* Remove the branches */
3472 pc1 = pb1->pc; /* Get the pCode that branches to the
3473 * one we're unlinking */
3475 /* search for the link back to this pCode (the one we're
3477 if(pb2 = pBranchFind(pc1->to,pc)) {
3478 pb2->pc = pc->to->pc; // make the replacement
3480 /* if the pCode we're unlinking contains multiple 'to'
3481 * branches (e.g. this a skip instruction) then we need
3482 * to copy these extra branches to the chain. */
3484 pBranchAppend(pb2, pc->to->next);
3493 /*-----------------------------------------------------------------*/
3494 /*-----------------------------------------------------------------*/
3496 static void genericAnalyze(pCode *pc)
3506 // Go through the pCodes that are in pCode chain and link
3507 // them together through the pBranches. Note, the pCodes
3508 // are linked together as a contiguous stream like the
3509 // assembly source code lines. The linking here mimics this
3510 // except that comments are not linked in.
3512 pCode *npc = pc->next;
3514 if(npc->type == PC_OPCODE || npc->type == PC_LABEL) {
3515 pBranchLink(pc,npc);
3520 /* reached the end of the pcode chain without finding
3521 * an instruction we could link to. */
3525 fprintf(stderr,"analyze PC_FLOW\n");
3529 fprintf(stderr,";A bad pCode is being used\n");
3535 /*-----------------------------------------------------------------*/
3536 /*-----------------------------------------------------------------*/
3537 int compareLabel(pCode *pc, pCodeOpLabel *pcop_label)
3541 if(pc->type == PC_LABEL) {
3542 if( ((pCodeLabel *)pc)->key == pcop_label->key)
3545 if(pc->type == PC_OPCODE || pc->type == PC_ASMDIR) {
3546 pbr = PCI(pc)->label;
3548 if(pbr->pc->type == PC_LABEL) {
3549 if( ((pCodeLabel *)(pbr->pc))->key == pcop_label->key)
3559 /*-----------------------------------------------------------------*/
3560 /*-----------------------------------------------------------------*/
3561 int checkLabel(pCode *pc)
3565 if(pc && isPCI(pc)) {
3566 pbr = PCI(pc)->label;
3568 if(isPCL(pbr->pc) && (PCL(pbr->pc)->key >= 0))
3578 /*-----------------------------------------------------------------*/
3579 /* findLabelinpBlock - Search the pCode for a particular label */
3580 /*-----------------------------------------------------------------*/
3581 pCode * findLabelinpBlock(pBlock *pb,pCodeOpLabel *pcop_label)
3588 for(pc = pb->pcHead; pc; pc = pc->next)
3589 if(compareLabel(pc,pcop_label))
3595 /*-----------------------------------------------------------------*/
3596 /* findLabel - Search the pCode for a particular label */
3597 /*-----------------------------------------------------------------*/
3598 pCode * findLabel(pCodeOpLabel *pcop_label)
3606 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
3607 if( (pc = findLabelinpBlock(pb,pcop_label)) != NULL)
3611 fprintf(stderr,"Couldn't find label %s\n", pcop_label->pcop.name);
3615 /*-----------------------------------------------------------------*/
3616 /* findNextpCode - given a pCode, find the next of type 'pct' */
3617 /* in the linked list */
3618 /*-----------------------------------------------------------------*/
3619 pCode * findNextpCode(pCode *pc, PC_TYPE pct)
3632 /*-----------------------------------------------------------------*/
3633 /* findPrevpCode - given a pCode, find the previous of type 'pct' */
3634 /* in the linked list */
3635 /*-----------------------------------------------------------------*/
3636 pCode * findPrevpCode(pCode *pc, PC_TYPE pct)
3640 if(pc->type == pct) {
3642 static unsigned int stop;
3644 stop++; // Place break point here
3655 /*-----------------------------------------------------------------*/
3656 /* findNextInstruction - given a pCode, find the next instruction */
3657 /* in the linked list */
3658 /*-----------------------------------------------------------------*/
3659 pCode * findNextInstruction(pCode *pci)
3664 if((pc->type == PC_OPCODE)
3665 || (pc->type == PC_WILD)
3666 || (pc->type == PC_ASMDIR))
3670 fprintf(stderr,"findNextInstruction: ");
3671 printpCode(stderr, pc);
3676 //fprintf(stderr,"Couldn't find instruction\n");
3680 /*-----------------------------------------------------------------*/
3681 /* findNextInstruction - given a pCode, find the next instruction */
3682 /* in the linked list */
3683 /*-----------------------------------------------------------------*/
3684 pCode * findPrevInstruction(pCode *pci)
3690 if((pc->type == PC_OPCODE)
3691 || (pc->type == PC_WILD)
3692 || (pc->type == PC_ASMDIR))
3697 fprintf(stderr,"pic16_findPrevInstruction: ");
3698 printpCode(stderr, pc);
3703 //fprintf(stderr,"Couldn't find instruction\n");
3707 /*-----------------------------------------------------------------*/
3708 /* findFunctionEnd - given a pCode find the end of the function */
3709 /* that contains it */
3710 /*-----------------------------------------------------------------*/
3711 pCode * findFunctionEnd(pCode *pc)
3714 if(pc->type == PC_FUNCTION && !(PCF(pc)->fname))
3720 fprintf(stderr,"Couldn't find function end\n");
3725 /*-----------------------------------------------------------------*/
3726 /* AnalyzeLabel - if the pCode is a label, then merge it with the */
3727 /* instruction with which it is associated. */
3728 /*-----------------------------------------------------------------*/
3729 static void AnalyzeLabel(pCode *pc)
3738 static void AnalyzeGOTO(pCode *pc)
3741 pBranchLink(pc,findLabel( (pCodeOpLabel *) (PCI(pc)->pcop) ));
3745 static void AnalyzeSKIP(pCode *pc)
3748 pBranchLink(pc,findNextInstruction(pc->next));
3749 pBranchLink(pc,findNextInstruction(pc->next->next));
3753 static void AnalyzeRETURN(pCode *pc)
3756 // branch_link(pc,findFunctionEnd(pc->next));
3762 /*-----------------------------------------------------------------*/
3763 /*-----------------------------------------------------------------*/
3764 regs * getRegFromInstruction(pCode *pc)
3770 PCI(pc)->num_ops == 0 )
3773 switch(PCI(pc)->pcop->type) {
3776 return PCOR(PCI(pc)->pcop)->r;
3780 return PCOR(PCI(pc)->pcop)->r;
3783 r = PCOI(PCI(pc)->pcop)->r;
3786 return dirregWithName(PCI(pc)->pcop->name);
3789 r = PCOR(PCI(pc)->pcop)->r;
3792 return dirregWithName(PCI(pc)->pcop->name);
3794 case PO_GPR_REGISTER:
3796 r = PCOR(PCI(pc)->pcop)->r;
3799 return dirregWithName(PCI(pc)->pcop->name);
3811 /*-----------------------------------------------------------------*/
3812 /*-----------------------------------------------------------------*/
3814 void AnalyzepBlock(pBlock *pb)
3821 /* Find all of the registers used in this pBlock
3822 * by looking at each instruction and examining it's
3825 for(pc = pb->pcHead; pc; pc = pc->next) {
3827 /* Is this an instruction with operands? */
3828 if(pc->type == PC_OPCODE && PCI(pc)->pcop) {
3830 if((PCI(pc)->pcop->type == PO_GPR_TEMP)
3831 || ((PCI(pc)->pcop->type == PO_GPR_BIT) && PCOR(PCI(pc)->pcop)->r && (PCOR(PCI(pc)->pcop)->r->pc_type == PO_GPR_TEMP))) {
3833 /* Loop through all of the registers declared so far in
3834 this block and see if we find this one there */
3836 regs *r = setFirstItem(pb->tregisters);
3839 if((r->rIdx == PCOR(PCI(pc)->pcop)->r->rIdx) && (r->type == PCOR(PCI(pc)->pcop)->r->type)) {
3840 PCOR(PCI(pc)->pcop)->r = r;
3843 r = setNextItem(pb->tregisters);
3847 /* register wasn't found */
3848 //r = Safe_calloc(1, sizeof(regs));
3849 //memcpy(r,PCOR(PCI(pc)->pcop)->r, sizeof(regs));
3850 //addSet(&pb->tregisters, r);
3851 addSet(&pb->tregisters, PCOR(PCI(pc)->pcop)->r);
3852 //PCOR(PCI(pc)->pcop)->r = r;
3853 //fprintf(stderr,"added register to pblock: reg %d\n",r->rIdx);
3855 fprintf(stderr,"found register in pblock: reg %d\n",r->rIdx);
3858 if(PCI(pc)->pcop->type == PO_GPR_REGISTER) {
3859 if(PCOR(PCI(pc)->pcop)->r) {
3860 pic14_allocWithIdx (PCOR(PCI(pc)->pcop)->r->rIdx);
3861 DFPRINTF((stderr,"found register in pblock: reg 0x%x\n",PCOR(PCI(pc)->pcop)->r->rIdx));
3863 if(PCI(pc)->pcop->name)
3864 fprintf(stderr,"ERROR: %s is a NULL register\n",PCI(pc)->pcop->name );
3866 fprintf(stderr,"ERROR: NULL register\n");
3875 /*-----------------------------------------------------------------*/
3877 /*-----------------------------------------------------------------*/
3878 void InsertpFlow(pCode *pc, pCode **pflow)
3881 PCFL(*pflow)->end = pc;
3883 if(!pc || !pc->next)
3886 *pflow = newpCodeFlow();
3887 pCodeInsertAfter(pc, *pflow);
3890 /*-----------------------------------------------------------------*/
3891 /* BuildFlow(pBlock *pb) - examine the code in a pBlock and build */
3892 /* the flow blocks. */
3894 * BuildFlow inserts pCodeFlow objects into the pCode chain at each
3895 * point the instruction flow changes.
3897 /*-----------------------------------------------------------------*/
3898 void BuildFlow(pBlock *pb)
3901 pCode *last_pci=NULL;
3908 //fprintf (stderr,"build flow start seq %d ",GpcFlowSeq);
3909 /* Insert a pCodeFlow object at the beginning of a pBlock */
3911 InsertpFlow(pb->pcHead, &pflow);
3913 //pflow = newpCodeFlow(); /* Create a new Flow object */
3914 //pflow->next = pb->pcHead; /* Make the current head the next object */
3915 //pb->pcHead->prev = pflow; /* let the current head point back to the flow object */
3916 //pb->pcHead = pflow; /* Make the Flow object the head */
3919 for( pc = findNextInstruction(pb->pcHead);
3921 pc=findNextInstruction(pc)) {
3924 PCI(pc)->pcflow = PCFL(pflow);
3926 //fprintf(stderr," build: ");
3927 //pflow->print(stderr,pflow);
3929 if( PCI(pc)->isSkip) {
3931 /* The two instructions immediately following this one
3932 * mark the beginning of a new flow segment */
3934 while(pc && PCI(pc)->isSkip) {
3936 PCI(pc)->pcflow = PCFL(pflow);
3940 InsertpFlow(pc, &pflow);
3941 pc=findNextInstruction(pc->next);
3949 PCI(pc)->pcflow = PCFL(pflow);
3951 InsertpFlow(pc, &pflow);
3953 } else if ( PCI(pc)->isBranch && !checkLabel(findNextInstruction(pc->next))) {
3955 InsertpFlow(pc, &pflow);
3958 } else if (checkLabel(pc)) {
3960 /* This instruction marks the beginning of a
3961 * new flow segment */
3966 /* If the previous pCode is not a flow object, then
3967 * insert a new flow object. (This check prevents
3968 * two consecutive flow objects from being insert in
3969 * the case where a skip instruction preceeds an
3970 * instruction containing a label.) */
3972 if(last_pci && (PCI(last_pci)->pcflow == PCFL(pflow)))
3973 InsertpFlow(findPrevInstruction(pc->prev), &pflow);
3975 PCI(pc)->pcflow = PCFL(pflow);
3982 //fprintf (stderr,",end seq %d",GpcFlowSeq);
3984 PCFL(pflow)->end = pb->pcTail;
3987 /*-------------------------------------------------------------------*/
3988 /* unBuildFlow(pBlock *pb) - examine the code in a pBlock and build */
3989 /* the flow blocks. */
3991 * unBuildFlow removes pCodeFlow objects from a pCode chain
3993 /*-----------------------------------------------------------------*/
3994 void unBuildFlow(pBlock *pb)
4009 if(PCI(pc)->pcflow) {
4010 //free(PCI(pc)->pcflow);
4011 PCI(pc)->pcflow = NULL;
4014 } else if(isPCFL(pc) )
4023 /*-----------------------------------------------------------------*/
4024 /*-----------------------------------------------------------------*/
4025 void dumpCond(int cond)
4028 static char *pcc_str[] = {
4042 int ncond = sizeof(pcc_str) / sizeof(char *);
4045 fprintf(stderr, "0x%04X\n",cond);
4047 for(i=0,j=1; i<ncond; i++, j<<=1)
4049 fprintf(stderr, " %s\n",pcc_str[i]);
4053 /*-----------------------------------------------------------------*/
4054 /*-----------------------------------------------------------------*/
4055 void FlowStats(pCodeFlow *pcflow)
4063 fprintf(stderr, " FlowStats - flow block (seq=%d)\n", pcflow->pc.seq);
4065 pc = findNextpCode(PCODE(pcflow), PC_OPCODE);
4068 fprintf(stderr, " FlowStats - empty flow (seq=%d)\n", pcflow->pc.seq);
4073 fprintf(stderr, " FlowStats inCond: ");
4074 dumpCond(pcflow->inCond);
4075 fprintf(stderr, " FlowStats outCond: ");
4076 dumpCond(pcflow->outCond);
4080 /*-----------------------------------------------------------------*
4081 * int isBankInstruction(pCode *pc) - examine the pCode *pc to determine
4082 * if it affects the banking bits.
4084 * return: -1 == Banking bits are unaffected by this pCode.
4086 * return: > 0 == Banking bits are affected.
4088 * If the banking bits are affected, then the returned value describes
4089 * which bits are affected and how they're affected. The lower half
4090 * of the integer maps to the bits that are affected, the upper half
4091 * to whether they're set or cleared.
4093 *-----------------------------------------------------------------*/
4095 #define SET_BANK_BIT (1 << 16)
4096 #define CLR_BANK_BIT 0
4098 static int isBankInstruction(pCode *pc)
4106 if( ( (reg = getRegFromInstruction(pc)) != NULL) && isSTATUS_REG(reg)) {
4108 // Check to see if the register banks are changing
4109 if(PCI(pc)->isModReg) {
4111 pCodeOp *pcop = PCI(pc)->pcop;
4112 switch(PCI(pc)->op) {
4115 if(PCORB(pcop)->bit == PIC_RP0_BIT) {
4116 //fprintf(stderr, " isBankInstruction - Set RP0\n");
4117 return SET_BANK_BIT | PIC_RP0_BIT;
4120 if(PCORB(pcop)->bit == PIC_RP1_BIT) {
4121 //fprintf(stderr, " isBankInstruction - Set RP1\n");
4122 return CLR_BANK_BIT | PIC_RP0_BIT;
4127 if(PCORB(pcop)->bit == PIC_RP0_BIT) {
4128 //fprintf(stderr, " isBankInstruction - Clr RP0\n");
4129 return CLR_BANK_BIT | PIC_RP1_BIT;
4131 if(PCORB(pcop)->bit == PIC_RP1_BIT) {
4132 //fprintf(stderr, " isBankInstruction - Clr RP1\n");
4133 return CLR_BANK_BIT | PIC_RP1_BIT;
4137 //fprintf(stderr, " isBankInstruction - Status register is getting Modified by:\n");
4138 //genericPrint(stderr, pc);
4149 /*-----------------------------------------------------------------*/
4150 /*-----------------------------------------------------------------*/
4152 static void FillFlow(pCodeFlow *pcflow)
4160 // fprintf(stderr, " FillFlow - flow block (seq=%d)\n", pcflow->pc.seq);
4162 pc = findNextpCode(PCODE(pcflow), PC_OPCODE);
4165 //fprintf(stderr, " FillFlow - empty flow (seq=%d)\n", pcflow->pc.seq);
4172 isBankInstruction(pc);
4174 } while (pc && (pc != pcflow->end) && !isPCFL(pc));
4177 fprintf(stderr, " FillFlow - Bad end of flow\n");
4179 fprintf(stderr, " FillFlow - Ending flow with\n ");
4180 pc->print(stderr,pc);
4183 fprintf(stderr, " FillFlow inCond: ");
4184 dumpCond(pcflow->inCond);
4185 fprintf(stderr, " FillFlow outCond: ");
4186 dumpCond(pcflow->outCond);
4191 /*-----------------------------------------------------------------*/
4192 /*-----------------------------------------------------------------*/
4193 void LinkFlow_pCode(pCodeInstruction *from, pCodeInstruction *to)
4195 pCodeFlowLink *fromLink, *toLink;
4197 if(!from || !to || !to->pcflow || !from->pcflow)
4200 fromLink = newpCodeFlowLink(from->pcflow);
4201 toLink = newpCodeFlowLink(to->pcflow);
4203 addSetIfnotP(&(from->pcflow->to), toLink); //to->pcflow);
4204 addSetIfnotP(&(to->pcflow->from), fromLink); //from->pcflow);
4208 /*-----------------------------------------------------------------*
4209 * void LinkFlow(pBlock *pb)
4211 * In BuildFlow, the PIC code has been partitioned into contiguous
4212 * non-branching segments. In LinkFlow, we determine the execution
4213 * order of these segments. For example, if one of the segments ends
4214 * with a skip, then we know that there are two possible flow segments
4215 * to which control may be passed.
4216 *-----------------------------------------------------------------*/
4217 void LinkFlow(pBlock *pb)
4223 //fprintf(stderr,"linkflow \n");
4225 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4227 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4230 fprintf(stderr, "LinkFlow - pcflow is not a flow object ");
4232 //fprintf(stderr," link: ");
4233 //pcflow->print(stderr,pcflow);
4235 //FillFlow(PCFL(pcflow));
4237 pc = PCFL(pcflow)->end;
4239 //fprintf(stderr, "LinkFlow - flow block (seq=%d) ", pcflow->seq);
4240 if(isPCI_SKIP(pc)) {
4241 //fprintf(stderr, "ends with skip\n");
4242 //pc->print(stderr,pc);
4243 pct=findNextInstruction(pc->next);
4244 LinkFlow_pCode(PCI(pc),PCI(pct));
4245 pct=findNextInstruction(pct->next);
4246 LinkFlow_pCode(PCI(pc),PCI(pct));
4250 if(isPCI_BRANCH(pc)) {
4251 pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
4253 //fprintf(stderr, "ends with branch\n ");
4254 //pc->print(stderr,pc);
4256 if(!(pcol && isPCOLAB(pcol))) {
4257 if((PCI(pc)->op != POC_RETLW) && (PCI(pc)->op != POC_RETURN) && (PCI(pc)->op != POC_CALL) && (PCI(pc)->op != POC_RETFIE) ) {
4258 pc->print(stderr,pc);
4259 fprintf(stderr, "ERROR: %s, branch instruction doesn't have label\n",__FUNCTION__);
4264 if( (pct = findLabelinpBlock(pb,pcol)) != NULL)
4265 LinkFlow_pCode(PCI(pc),PCI(pct));
4267 fprintf(stderr, "ERROR: %s, couldn't find label. key=%d,lab=%s\n",
4268 __FUNCTION__,pcol->key,((PCOP(pcol)->name)?PCOP(pcol)->name:"-"));
4269 //fprintf(stderr,"newpCodeOpLabel: key=%d, name=%s\n",key,((s)?s:""));
4275 //fprintf(stderr, "ends with non-branching instruction:\n");
4276 //pc->print(stderr,pc);
4278 LinkFlow_pCode(PCI(pc),PCI(findNextInstruction(pc->next)));
4284 //fprintf(stderr, "ends with unknown\n");
4285 //pc->print(stderr,pc);
4289 //fprintf(stderr, "ends with nothing: ERROR\n");
4293 /*-----------------------------------------------------------------*/
4294 /*-----------------------------------------------------------------*/
4296 /*-----------------------------------------------------------------*/
4297 /*-----------------------------------------------------------------*/
4298 int isPCinFlow(pCode *pc, pCode *pcflow)
4304 if(!isPCI(pc) || !PCI(pc)->pcflow || !isPCFL(pcflow) )
4307 if( PCI(pc)->pcflow->pc.seq == pcflow->seq)
4313 /*-----------------------------------------------------------------*/
4314 /*-----------------------------------------------------------------*/
4316 static void BanksUsedFlow2(pCode *pcflow)
4325 if(!isPCFL(pcflow)) {
4326 fprintf(stderr, "BanksUsed - pcflow is not a flow object ");
4330 pc = findNextInstruction(pcflow->next);
4332 PCFL(pcflow)->lastBank = -1;
4334 while(isPCinFlow(pc,pcflow)) {
4336 int bank_selected = isBankInstruction(pc);
4338 //if(PCI(pc)->pcflow)
4339 //fprintf(stderr,"BanksUsedFlow2, looking at seq %d\n",PCI(pc)->pcflow->pc.seq);
4341 if(bank_selected > 0) {
4342 //fprintf(stderr,"BanksUsed - mucking with bank %d\n",bank_selected);
4344 // This instruction is modifying banking bits before accessing registers
4346 PCFL(pcflow)->firstBank = -1;
4348 if(PCFL(pcflow)->lastBank == -1)
4349 PCFL(pcflow)->lastBank = 0;
4351 bank = (1 << (bank_selected & (PIC_RP0_BIT | PIC_RP1_BIT)));
4352 if(bank_selected & SET_BANK_BIT)
4353 PCFL(pcflow)->lastBank |= bank;
4357 reg = getRegFromInstruction(pc);
4359 if(reg && !isREGinBank(reg, bank)) {
4360 int allbanks = REGallBanks(reg);
4362 PCFL(pcflow)->firstBank = allbanks;
4364 PCFL(pcflow)->lastBank = allbanks;
4371 pc = findNextInstruction(pc->next);
4374 // fprintf(stderr,"BanksUsedFlow2 flow seq=%3d, first bank = 0x%03x, Last bank 0x%03x\n",
4375 // pcflow->seq,PCFL(pcflow)->firstBank,PCFL(pcflow)->lastBank);
4378 /*-----------------------------------------------------------------*/
4379 /*-----------------------------------------------------------------*/
4381 static void BanksUsedFlow(pBlock *pb)
4386 //pb->pcHead->print(stderr, pb->pcHead);
4388 pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4389 //pcflow->print(stderr,pcflow);
4391 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4393 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4395 BanksUsedFlow2(pcflow);
4401 /*-----------------------------------------------------------------*/
4402 /* Inserts a new pCodeInstruction before an existing one */
4403 /*-----------------------------------------------------------------*/
4404 static void insertPCodeInstruction(pCodeInstruction *pci, pCodeInstruction *new_pci)
4407 pCodeInsertAfter(pci->pc.prev, &new_pci->pc);
4409 /* Move the label, if there is one */
4412 new_pci->label = pci->label;
4416 /* Move the C code comment, if there is one */
4419 new_pci->cline = pci->cline;
4423 /* The new instruction has the same pcflow block */
4424 new_pci->pcflow = pci->pcflow;
4428 /*-----------------------------------------------------------------*/
4429 /*-----------------------------------------------------------------*/
4430 static void insertBankSwitch(pCodeInstruction *pci, int Set_Clear, int RP_BankBit)
4434 new_pc = newpCode((Set_Clear?POC_BSF:POC_BCF),popCopyGPR2Bit(PCOP(&pc_status),RP_BankBit));
4436 insertPCodeInstruction(pci, PCI(new_pc));
4439 /*-----------------------------------------------------------------*/
4440 /*-----------------------------------------------------------------*/
4441 static void insertBankSel(pCodeInstruction *pci, const char *name)
4445 pCodeOp *pcop = popCopyReg(PCOR(pci->pcop));
4446 pcop->type = PO_GPR_REGISTER; // Sometimes the type is set to legacy 8051 - so override it
4447 if (pcop->name == 0)
4448 pcop->name = strdup(name);
4449 new_pc = newpCode(POC_BANKSEL, pcop);
4451 insertPCodeInstruction(pci, PCI(new_pc));
4454 /*-----------------------------------------------------------------*/
4455 /* If the register is a fixed known addess then we can assign the */
4456 /* bank selection bits. Otherwise the linker is going to assign */
4457 /* the register location and thus has to set bank selection bits */
4458 /* through the banksel directive. */
4459 /* One critical assumption here is that within this C module all */
4460 /* the locally allocated registers are in the same udata sector. */
4461 /* Therefore banksel is only called for external registers or the */
4462 /* first time a local register is encountered. */
4463 /*-----------------------------------------------------------------*/
4464 static int LastRegIdx; /* If the previous register is the same one again then no need to change bank. */
4465 static int BankSelect(pCodeInstruction *pci, int cur_bank, regs *reg)
4468 int a = reg->alias>>7;
4470 return cur_bank; // This register is available in all banks
4471 } else if ((a&1)&&((cur_bank==0)||(cur_bank==1))) {
4472 return cur_bank; // This register is available in banks 0 & 1
4474 if (reg->address&0x80) {
4475 if ((cur_bank==1)||(cur_bank==3)) {
4476 return cur_bank; // This register is available in banks 1 & 3
4479 if ((cur_bank==0)||(cur_bank==1)) {
4480 return cur_bank; // This register is available in banks 0 & 2
4485 if (LastRegIdx == reg->rIdx) // If this is the same register as last time then it is in same bank
4487 LastRegIdx = reg->rIdx;
4490 bank = REG_BANK(reg);
4491 } else if (reg->isExtern) {
4492 bank = 'E'; // Unfixed extern registers are allocated by the linker therefore its bank is unknown
4494 bank = 'L'; // Unfixed local registers are allocated by the linker therefore its bank is unknown
4496 if ((cur_bank == 'L')&&(bank == 'L')) { // If current bank and new bank are both allocated locally by the linker, then assume it is in same bank.
4497 return 'L'; // Local registers are presumed to be in same linker assigned bank
4498 } else if ((bank == 'L')&&(cur_bank != 'L')) { // Reg is now local and linker to assign bank
4499 insertBankSel(pci, reg->name); // Let linker choose the bank selection
4500 } else if (bank == 'E') { // Reg is now extern and linker to assign bank
4501 insertBankSel(pci, reg->name); // Let linker choose the bank selection
4502 } else if ((cur_bank == -1)||(cur_bank == 'L')||(cur_bank == 'E')) { // Current bank unknown and new register bank is known then can set bank bits
4503 insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4504 if (getMaxRam()&0x100)
4505 insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4506 } else { // Current bank and new register banks known - can set bank bits
4507 switch((cur_bank^bank) & 3) {
4511 insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4514 insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4517 insertBankSwitch(pci, bank&1, PIC_RP0_BIT);
4518 if (getMaxRam()&0x100)
4519 insertBankSwitch(pci, bank&2, PIC_RP1_BIT);
4527 /*-----------------------------------------------------------------*/
4528 /* Check for bank selection pcodes instructions and modify */
4529 /* cur_bank to match. */
4530 /*-----------------------------------------------------------------*/
4531 static int IsBankChange(pCode *pc, regs *reg, int *cur_bank) {
4533 if (isSTATUS_REG(reg)) {
4535 if (PCI(pc)->op == POC_BCF) {
4536 int old_bank = *cur_bank;
4537 if (PCORB(PCI(pc)->pcop)->bit == PIC_RP0_BIT) {
4538 /* If current bank is unknown or linker assigned then set to 0 else just change the bit */
4539 if (*cur_bank & ~(0x3))
4542 *cur_bank = *cur_bank&0x2;
4543 LastRegIdx = reg->rIdx;
4544 } else if (PCORB(PCI(pc)->pcop)->bit == PIC_RP1_BIT) {
4545 /* If current bank is unknown or linker assigned then set to 0 else just change the bit */
4546 if (*cur_bank & ~(0x3))
4549 *cur_bank = *cur_bank&0x1;
4550 LastRegIdx = reg->rIdx;
4552 return old_bank != *cur_bank;
4555 if (PCI(pc)->op == POC_BSF) {
4556 int old_bank = *cur_bank;
4557 if (PCORB(PCI(pc)->pcop)->bit == PIC_RP0_BIT) {
4558 /* If current bank is unknown or linker assigned then set to bit else just change the bit */
4559 if (*cur_bank & ~(0x3))
4562 *cur_bank = (*cur_bank&0x2) | 0x1;
4563 LastRegIdx = reg->rIdx;
4564 } else if (PCORB(PCI(pc)->pcop)->bit == PIC_RP1_BIT) {
4565 /* If current bank is unknown or linker assigned then set to bit else just change the bit */
4566 if (*cur_bank & ~(0x3))
4569 *cur_bank = (*cur_bank&0x1) | 0x2;
4570 LastRegIdx = reg->rIdx;
4572 return old_bank != *cur_bank;
4575 } else if (PCI(pc)->op == POC_BANKSEL) {
4576 int old_bank = *cur_bank;
4577 regs *r = PCOR(PCI(pc)->pcop)->r;
4578 *cur_bank = (!r || r->isExtern) ? 'E' : 'L';
4579 LastRegIdx = reg->rIdx;
4580 return old_bank != *cur_bank;
4586 /*-----------------------------------------------------------------*/
4587 /* Set bank selection if necessary */
4588 /*-----------------------------------------------------------------*/
4589 static int DoBankSelect(pCode *pc, int cur_bank) {
4597 pCode *pcf = findFunction(get_op_from_instruction(PCI(pc)));
4598 if (pcf && isPCF(pcf)) {
4600 int rbank = 'U'; // Undetermined
4601 FixRegisterBanking(pcf->pb,cur_bank); // Ensure this block has had its banks selection done
4602 // Check all the returns to work out what bank is selected
4603 for (pcfr=pcf->pb->pcHead; pcfr; pcfr=pcfr->next) {
4605 if ((PCI(pcfr)->op==POC_RETURN) || (PCI(pcfr)->op==POC_RETLW)) {
4607 rbank = PCFL(pcfr)->lastBank;
4609 if (rbank != PCFL(pcfr)->lastBank)
4610 return -1; // Unknown bank - multiple returns with different banks
4615 return -1; // Unknown bank
4617 } else if (isPCOS(PCI(pc)->pcop) && PCOS(PCI(pc)->pcop)->isPublic) {
4618 /* Extern functions may use registers in different bank - must call banksel */
4619 return -1; /* Unknown bank */
4623 if ((isPCI(pc)) && (PCI(pc)->op == POC_BANKSEL)) {
4624 return -1; /* New bank unknown - linkers choice. */
4627 reg = getRegFromInstruction(pc);
4629 if (IsBankChange(pc,reg,&cur_bank))
4631 if (!isPCI_LIT(pc)) {
4633 /* Examine the instruction before this one to make sure it is
4634 * not a skip type instruction */
4635 pcprev = findPrevpCode(pc->prev, PC_OPCODE);
4637 if(!pcprev || (pcprev && !isPCI_SKIP(pcprev))) {
4638 cur_bank = BankSelect(PCI(pc),cur_bank,reg);
4640 cur_bank = BankSelect(PCI(pcprev),cur_bank,reg);
4642 if (!PCI(pc)->pcflow)
4643 fprintf(stderr,"PCI ID=%d missing flow pointer ???\n",pc->id);
4645 PCI(pc)->pcflow->lastBank = cur_bank; /* Maintain pCodeFlow lastBank state */
4651 /*-----------------------------------------------------------------*/
4652 /*-----------------------------------------------------------------*/
4654 static void FixRegisterBankingInFlow(pCodeFlow *pcfl, int cur_bank)
4662 pc = findNextInstruction(pcfl->pc.next);
4664 while(isPCinFlow(pc,PCODE(pcfl))) {
4666 cur_bank = DoBankSelect(pc,cur_bank);
4668 pc = findNextInstruction(pc->next);
4672 if(pcprev && cur_bank) {
4673 // Set bank state to unknown at the end of each flow block
4679 /*-----------------------------------------------------------------*/
4680 /*int compareBankFlow - compare the banking requirements between */
4682 /*-----------------------------------------------------------------*/
4684 int compareBankFlow(pCodeFlow *pcflow, pCodeFlowLink *pcflowLink, int toORfrom)
4687 if(!pcflow || !pcflowLink || !pcflowLink->pcflow)
4690 if(!isPCFL(pcflow) || !isPCFL(pcflowLink->pcflow))
4693 if(pcflow->firstBank == -1)
4697 if(pcflowLink->pcflow->firstBank == -1) {
4698 pCodeFlowLink *pctl = setFirstItem( toORfrom ?
4699 pcflowLink->pcflow->to :
4700 pcflowLink->pcflow->from);
4701 return compareBankFlow(pcflow, pctl, toORfrom);
4705 if(pcflow->lastBank == pcflowLink->pcflow->firstBank)
4708 pcflowLink->bank_conflict++;
4709 pcflowLink->pcflow->FromConflicts++;
4710 pcflow->ToConflicts++;
4713 if(pcflow->firstBank == pcflowLink->pcflow->lastBank)
4716 pcflowLink->bank_conflict++;
4717 pcflowLink->pcflow->ToConflicts++;
4718 pcflow->FromConflicts++;
4722 fprintf(stderr,"compare flow found conflict: seq %d from conflicts %d, to conflicts %d\n",
4723 pcflowLink->pcflow->pc.seq,
4724 pcflowLink->pcflow->FromConflicts,
4725 pcflowLink->pcflow->ToConflicts);
4731 /*-----------------------------------------------------------------*/
4732 /*-----------------------------------------------------------------*/
4734 void FixBankFlow(pBlock *pb)
4738 pCodeFlowLink *pcfl;
4740 pCode *pcflow_max_To=NULL;
4741 pCode *pcflow_max_From=NULL;
4742 int max_ToConflicts=0;
4743 int max_FromConflicts=0;
4745 /fprintf(stderr,"Fix Bank flow \n");
4746 pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4750 First loop through all of the flow objects in this pcode block
4751 and fix the ones that have banking conflicts between the
4755 //fprintf(stderr, "FixBankFlow - Phase 1\n");
4757 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4759 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4761 if(!isPCFL(pcflow)) {
4762 fprintf(stderr, "FixBankFlow - pcflow is not a flow object ");
4766 if(PCFL(pcflow)->firstBank != PCFL(pcflow)->lastBank &&
4767 PCFL(pcflow)->firstBank >= 0 &&
4768 PCFL(pcflow)->lastBank >= 0 ) {
4770 int cur_bank = (PCFL(pcflow)->firstBank < PCFL(pcflow)->lastBank) ?
4771 PCFL(pcflow)->firstBank : PCFL(pcflow)->lastBank;
4773 FixRegisterBankingInFlow(PCFL(pcflow),cur_bank);
4774 BanksUsedFlow2(pcflow);
4779 //fprintf(stderr, "FixBankFlow - Phase 2\n");
4781 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4783 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4788 if(!isPCFL(pcflow)) {
4789 fprintf(stderr, "FixBankFlow - pcflow is not a flow object ");
4793 PCFL(pcflow)->FromConflicts = 0;
4794 PCFL(pcflow)->ToConflicts = 0;
4799 //fprintf(stderr, " FixBankFlow flow seq %d\n",pcflow->seq);
4800 pcfl = setFirstItem(PCFL(pcflow)->from);
4803 pc = PCODE(pcfl->pcflow);
4806 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4807 pc->print(stderr,pc);
4810 nConflicts += compareBankFlow(PCFL(pcflow), pcfl, 0);
4813 pcfl=setNextItem(PCFL(pcflow)->from);
4816 if((nFlows >= 2) && nConflicts && (PCFL(pcflow)->firstBank>0)) {
4817 //fprintf(stderr, " From conflicts flow seq %d, nflows %d ,nconflicts %d\n",pcflow->seq,nFlows, nConflicts);
4819 FixRegisterBankingInFlow(PCFL(pcflow),-1);
4820 BanksUsedFlow2(pcflow);
4822 continue; / * Don't need to check the flow from here - it's already been fixed * /
4829 pcfl = setFirstItem(PCFL(pcflow)->to);
4832 pc = PCODE(pcfl->pcflow);
4834 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4835 pc->print(stderr,pc);
4838 nConflicts += compareBankFlow(PCFL(pcflow), pcfl, 1);
4841 pcfl=setNextItem(PCFL(pcflow)->to);
4844 if((nFlows >= 2) && nConflicts &&(nConflicts != nFlows) && (PCFL(pcflow)->lastBank>0)) {
4845 //fprintf(stderr, " To conflicts flow seq %d, nflows %d ,nconflicts %d\n",pcflow->seq,nFlows, nConflicts);
4847 FixRegisterBankingInFlow(PCFL(pcflow),-1);
4848 BanksUsedFlow2(pcflow);
4853 Loop through the flow objects again and find the ones with the
4857 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4859 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4861 if(PCFL(pcflow)->ToConflicts > max_ToConflicts)
4862 pcflow_max_To = pcflow;
4864 if(PCFL(pcflow)->FromConflicts > max_FromConflicts)
4865 pcflow_max_From = pcflow;
4869 fprintf(stderr,"compare flow Max To conflicts: seq %d conflicts %d\n",
4870 PCFL(pcflow_max_To)->pc.seq,
4871 PCFL(pcflow_max_To)->ToConflicts);
4874 fprintf(stderr,"compare flow Max From conflicts: seq %d conflicts %d\n",
4875 PCFL(pcflow_max_From)->pc.seq,
4876 PCFL(pcflow_max_From)->FromConflicts);
4881 /*-----------------------------------------------------------------*/
4882 /*-----------------------------------------------------------------*/
4883 void DumpFlow(pBlock *pb)
4887 pCodeFlowLink *pcfl;
4890 fprintf(stderr,"Dump flow \n");
4891 pb->pcHead->print(stderr, pb->pcHead);
4893 pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4894 pcflow->print(stderr,pcflow);
4896 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
4898 pcflow = findNextpCode(pcflow->next, PC_FLOW) ) {
4900 if(!isPCFL(pcflow)) {
4901 fprintf(stderr, "DumpFlow - pcflow is not a flow object ");
4904 fprintf(stderr,"dumping: ");
4905 pcflow->print(stderr,pcflow);
4906 FlowStats(PCFL(pcflow));
4908 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
4910 pc = PCODE(pcfl->pcflow);
4912 fprintf(stderr, " from seq %d:\n",pc->seq);
4914 fprintf(stderr,"oops dumpflow - from is not a pcflow\n");
4915 pc->print(stderr,pc);
4920 for(pcfl = setFirstItem(PCFL(pcflow)->to); pcfl; pcfl=setNextItem(PCFL(pcflow)->to)) {
4922 pc = PCODE(pcfl->pcflow);
4924 fprintf(stderr, " to seq %d:\n",pc->seq);
4926 fprintf(stderr,"oops dumpflow - to is not a pcflow\n");
4927 pc->print(stderr,pc);
4936 /*-----------------------------------------------------------------*/
4937 /*-----------------------------------------------------------------*/
4938 int OptimizepBlock(pBlock *pb)
4943 if(!pb || !peepOptimizing)
4946 DFPRINTF((stderr," Optimizing pBlock: %c\n",getpBlock_dbName(pb)));
4948 for(pc = pb->pcHead; pc; pc = pc->next)
4949 matches += pCodePeepMatchRule(pc);
4952 pc = findNextInstruction(pb->pcHead);
4960 if(pCodePeepMatchRule(pc)) {
4965 pc = findNextInstruction(pcprev->next);
4967 pc = findNextInstruction(pb->pcHead);
4969 pc = findNextInstruction(pc->next);
4973 DFPRINTF((stderr," Optimizing pBlock: %c - matches=%d\n",getpBlock_dbName(pb),matches));
4978 /*-----------------------------------------------------------------*/
4979 /* pBlockRemoveUnusedLabels - remove the pCode labels from the */
4980 /*-----------------------------------------------------------------*/
4981 pCode * findInstructionUsingLabel(pCodeLabel *pcl, pCode *pcs)
4985 for(pc = pcs; pc; pc = pc->next) {
4987 if(((pc->type == PC_OPCODE) || (pc->type == PC_INLINE) || (pc->type == PC_ASMDIR)) &&
4989 (PCI(pc)->pcop->type == PO_LABEL) &&
4990 (PCOLAB(PCI(pc)->pcop)->key == pcl->key))
4997 /*-----------------------------------------------------------------*/
4998 /*-----------------------------------------------------------------*/
4999 void exchangeLabels(pCodeLabel *pcl, pCode *pc)
5006 (PCI(pc)->pcop->type == PO_LABEL)) {
5008 pCodeOpLabel *pcol = PCOLAB(PCI(pc)->pcop);
5010 //fprintf(stderr,"changing label key from %d to %d\n",pcol->key, pcl->key);
5012 free(pcol->pcop.name);
5014 /* If the key is negative, then we (probably) have a label to
5015 * a function and the name is already defined */
5018 sprintf(s=buffer,"_%05d_DS_",pcl->key);
5022 //sprintf(buffer,"_%05d_DS_",pcl->key);
5024 fprintf(stderr, "ERROR %s:%d function label is null\n",__FUNCTION__,__LINE__);
5026 pcol->pcop.name = Safe_strdup(s);
5027 pcol->key = pcl->key;
5028 //pc->print(stderr,pc);
5035 /*-----------------------------------------------------------------*/
5036 /* pBlockRemoveUnusedLabels - remove the pCode labels from the */
5037 /* pCode chain if they're not used. */
5038 /*-----------------------------------------------------------------*/
5039 void pBlockRemoveUnusedLabels(pBlock *pb)
5041 pCode *pc; pCodeLabel *pcl;
5046 for(pc = pb->pcHead; (pc=findNextInstruction(pc->next)) != NULL; ) {
5048 pBranch *pbr = PCI(pc)->label;
5049 if(pbr && pbr->next) {
5050 pCode *pcd = pb->pcHead;
5052 //fprintf(stderr, "multiple labels\n");
5053 //pc->print(stderr,pc);
5058 while ( (pcd = findInstructionUsingLabel(PCL(PCI(pc)->label->pc), pcd)) != NULL) {
5059 //fprintf(stderr,"Used by:\n");
5060 //pcd->print(stderr,pcd);
5062 exchangeLabels(PCL(pbr->pc),pcd);
5071 for(pc = pb->pcHead; pc; pc = pc->next) {
5073 if(isPCL(pc)) // Label pcode
5075 else if (isPCI(pc) && PCI(pc)->label) // pcode instruction with a label
5076 pcl = PCL(PCI(pc)->label->pc);
5079 //fprintf(stderr," found A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
5081 /* This pCode is a label, so search the pBlock to see if anyone
5084 if( (pcl->key>0) && (!findInstructionUsingLabel(pcl, pb->pcHead))) {
5085 //if( !findInstructionUsingLabel(pcl, pb->pcHead)) {
5086 /* Couldn't find an instruction that refers to this label
5087 * So, unlink the pCode label from it's pCode chain
5088 * and destroy the label */
5089 //fprintf(stderr," removed A LABEL !!! key = %d, %s\n", pcl->key,pcl->label);
5091 DFPRINTF((stderr," !!! REMOVED A LABEL !!! key = %d, %s\n", pcl->key,pcl->label));
5092 if(pc->type == PC_LABEL) {
5094 pCodeLabelDestruct(pc);
5096 unlinkpCodeFromBranch(pc, PCODE(pcl));
5097 /*if(pc->label->next == NULL && pc->label->pc == NULL) {
5108 /*-----------------------------------------------------------------*/
5109 /* pBlockMergeLabels - remove the pCode labels from the pCode */
5110 /* chain and put them into pBranches that are */
5111 /* associated with the appropriate pCode */
5113 /*-----------------------------------------------------------------*/
5114 void pBlockMergeLabels(pBlock *pb)
5117 pCode *pc, *pcnext=NULL;
5122 /* First, Try to remove any unused labels */
5123 //pBlockRemoveUnusedLabels(pb);
5125 /* Now loop through the pBlock and merge the labels with the opcodes */
5128 // for(pc = pb->pcHead; pc; pc = pc->next) {
5131 pCode *pcn = pc->next;
5133 if(pc->type == PC_LABEL) {
5135 //fprintf(stderr," checking merging label %s\n",PCL(pc)->label);
5136 //fprintf(stderr,"Checking label key = %d\n",PCL(pc)->key);
5137 if((pcnext = findNextInstruction(pc) )) {
5139 // Unlink the pCode label from it's pCode chain
5142 //fprintf(stderr,"Merged label key = %d\n",PCL(pc)->key);
5143 // And link it into the instruction's pBranch labels. (Note, since
5144 // it's possible to have multiple labels associated with one instruction
5145 // we must provide a means to accomodate the additional labels. Thus
5146 // the labels are placed into the singly-linked list "label" as
5147 // opposed to being a single member of the pCodeInstruction.)
5149 //_ALLOC(pbr,sizeof(pBranch));
5150 pbr = Safe_calloc(1,sizeof(pBranch));
5154 PCI(pcnext)->label = pBranchAppend(PCI(pcnext)->label,pbr);
5157 fprintf(stderr, "WARNING: couldn't associate label %s with an instruction\n",PCL(pc)->label);
5159 } else if(pc->type == PC_CSOURCE) {
5161 /* merge the source line symbolic info into the next instruction */
5162 if((pcnext = findNextInstruction(pc) )) {
5164 // Unlink the pCode label from it's pCode chain
5166 PCI(pcnext)->cline = PCCS(pc);
5167 //fprintf(stderr, "merging CSRC\n");
5168 //genericPrint(stderr,pcnext);
5174 pBlockRemoveUnusedLabels(pb);
5178 /*-----------------------------------------------------------------*/
5179 /*-----------------------------------------------------------------*/
5180 int OptimizepCode(char dbName)
5182 #define MAX_PASSES 4
5191 DFPRINTF((stderr," Optimizing pCode\n"));
5195 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5196 if('*' == dbName || getpBlock_dbName(pb) == dbName)
5197 matches += OptimizepBlock(pb);
5200 while(matches && ++passes < MAX_PASSES);
5205 /*-----------------------------------------------------------------*/
5206 /* popCopyGPR2Bit - copy a pcode operator */
5207 /*-----------------------------------------------------------------*/
5209 pCodeOp *popCopyGPR2Bit(pCodeOp *pc, int bitval)
5213 pcop = newpCodeOpBit(pc->name, bitval, 0);
5215 if( !( (pcop->type == PO_LABEL) ||
5216 (pcop->type == PO_LITERAL) ||
5217 (pcop->type == PO_STR) ))
5218 PCOR(pcop)->r = PCOR(pc)->r; /* This is dangerous... */
5224 /*-----------------------------------------------------------------*/
5225 /*-----------------------------------------------------------------*/
5226 static void FixRegisterBanking(pBlock *pb,int cur_bank)
5229 int firstBank = 'U';
5234 for (pc=pb->pcHead; pc; pc=pc->next) {
5236 firstBank = PCFL(pc)->firstBank;
5240 if (firstBank != 'U') {
5241 /* This block has already been done */
5242 if (firstBank != cur_bank) {
5243 /* This block has started with a different bank - must adjust it */
5244 if ((firstBank != -1)&&(firstBank != 'E')) { /* The first bank start off unknown or extern then need not worry as banksel will be called */
5247 regs *reg = getRegFromInstruction(pc);
5249 DoBankSelect(pc,cur_bank);
5259 /* loop through all of the pCodes within this pblock setting the bank selection, ignoring any branching */
5262 for (pc=pb->pcHead; pc; pc=pc->next) {
5264 PCFL(pc)->firstBank = cur_bank;
5267 cur_bank = DoBankSelect(pc,cur_bank);
5270 /* Trace through branches and set the bank selection as required. */
5273 for (pc=pb->pcHead; pc; pc=pc->next) {
5275 PCFL(pc)->firstBank = cur_bank;
5279 if (PCI(pc)->op == POC_GOTO) {
5280 int lastRegIdx = LastRegIdx;
5282 /* Trace through branch */
5283 pCode *pcl = findLabel(PCOLAB(PCI(pcb)->pcop));
5286 regs *reg = getRegFromInstruction(pcl);
5288 int bankUnknown = -1;
5289 if (IsBankChange(pcl,reg,&bankUnknown)) /* Look for any bank change */
5291 if (cur_bank != DoBankSelect(pcl,cur_bank)) /* Set bank selection if necessary */
5297 LastRegIdx = lastRegIdx;
5299 /* Keep track out current bank */
5300 regs *reg = getRegFromInstruction(pc);
5302 IsBankChange(pc,reg,&cur_bank);
5309 /*-----------------------------------------------------------------*/
5310 /*-----------------------------------------------------------------*/
5311 void pBlockDestruct(pBlock *pb)
5322 /*-----------------------------------------------------------------*/
5323 /* void mergepBlocks(char dbName) - Search for all pBlocks with the*/
5324 /* name dbName and combine them */
5325 /* into one block */
5326 /*-----------------------------------------------------------------*/
5327 void mergepBlocks(char dbName)
5330 pBlock *pb, *pbmerged = NULL,*pbn;
5332 pb = the_pFile->pbHead;
5334 //fprintf(stderr," merging blocks named %c\n",dbName);
5338 //fprintf(stderr,"looking at %c\n",getpBlock_dbName(pb));
5339 if( getpBlock_dbName(pb) == dbName) {
5341 //fprintf(stderr," merged block %c\n",dbName);
5346 addpCode2pBlock(pbmerged, pb->pcHead);
5347 /* addpCode2pBlock doesn't handle the tail: */
5348 pbmerged->pcTail = pb->pcTail;
5350 pb->prev->next = pbn;
5352 pbn->prev = pb->prev;
5357 //printpBlock(stderr, pbmerged);
5364 /*-----------------------------------------------------------------*/
5365 /* AnalyzeFlow - Examine the flow of the code and optimize */
5367 /* level 0 == minimal optimization */
5368 /* optimize registers that are used only by two instructions */
5369 /* level 1 == maximal optimization */
5370 /* optimize by looking at pairs of instructions that use the */
5372 /*-----------------------------------------------------------------*/
5374 void AnalyzeFlow(int level)
5376 static int times_called=0;
5384 /* if this is not the first time this function has been called,
5385 then clean up old flow information */
5386 if(times_called++) {
5387 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5390 RegsUnMapLiveRanges();
5396 /* Phase 2 - Flow Analysis - Register Banking
5398 * In this phase, the individual flow blocks are examined
5399 * and register banking is fixed.
5402 //for(pb = the_pFile->pbHead; pb; pb = pb->next)
5403 //FixRegisterBanking(pb);
5405 /* Phase 2 - Flow Analysis
5407 * In this phase, the pCode is partition into pCodeFlow
5408 * blocks. The flow blocks mark the points where a continuous
5409 * stream of instructions changes flow (e.g. because of
5410 * a call or goto or whatever).
5413 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5417 /* Phase 2 - Flow Analysis - linking flow blocks
5419 * In this phase, the individual flow blocks are examined
5420 * to determine their order of excution.
5423 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5426 /* Phase 3 - Flow Analysis - Flow Tree
5428 * In this phase, the individual flow blocks are examined
5429 * to determine their order of excution.
5432 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5436 /* Phase x - Flow Analysis - Used Banks
5438 * In this phase, the individual flow blocks are examined
5439 * to determine the Register Banks they use
5442 // for(pb = the_pFile->pbHead; pb; pb = pb->next)
5446 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5447 pCodeRegMapLiveRanges(pb);
5449 RemoveUnusedRegisters();
5451 // for(pb = the_pFile->pbHead; pb; pb = pb->next)
5452 pCodeRegOptimizeRegUsage(level);
5458 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5463 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5465 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
5466 (pcflow = findNextpCode(pcflow, PC_FLOW)) != NULL;
5467 pcflow = pcflow->next) {
5469 FillFlow(PCFL(pcflow));
5474 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5476 for( pcflow = findNextpCode(pb->pcHead, PC_FLOW);
5477 (pcflow = findNextpCode(pcflow, PC_FLOW)) != NULL;
5478 pcflow = pcflow->next) {
5480 FlowStats(PCFL(pcflow));
5486 /*-----------------------------------------------------------------*/
5487 /* AnalyzeBanking - Called after the memory addresses have been */
5488 /* assigned to the registers. */
5490 /*-----------------------------------------------------------------*/
5492 void AnalyzeBanking(void)
5496 if(!picIsInitialized()) {
5497 setDefMaxRam(); // Max RAM has not been included, so use default setting
5500 /* Phase x - Flow Analysis - Used Banks
5502 * In this phase, the individual flow blocks are examined
5503 * to determine the Register Banks they use
5509 // for(pb = the_pFile->pbHead; pb; pb = pb->next)
5510 // BanksUsedFlow(pb);
5511 for(pb = the_pFile->pbHead; pb; pb = pb->next)
5512 FixRegisterBanking(pb,-1); // cur_bank is unknown
5516 /*-----------------------------------------------------------------*/
5517 /*-----------------------------------------------------------------*/
5518 DEFSETFUNC (resetrIdx)
5520 regs *r = (regs *)item;
5528 /*-----------------------------------------------------------------*/
5529 /* InitRegReuse - Initialises variables for code analyzer */
5530 /*-----------------------------------------------------------------*/
5532 void InitReuseReg(void)
5534 /* Find end of statically allocated variables for start idx */
5535 unsigned maxIdx = 0x20; /* Start from begining of GPR. Note may not be 0x20 on some PICs */
5537 for (r = setFirstItem(dynDirectRegs); r; r = setNextItem(dynDirectRegs)) {
5538 if (r->type != REG_SFR) {
5539 maxIdx += r->size; /* Increment for all statically allocated variables */
5543 applyToSet(dynAllocRegs,resetrIdx); /* Reset all rIdx to zero. */
5546 /*-----------------------------------------------------------------*/
5547 /*-----------------------------------------------------------------*/
5548 static unsigned register_reassign(pBlock *pb, unsigned idx)
5552 /* check recursion */
5553 pc = setFirstItem(pb->function_entries);
5559 DFPRINTF((stderr," reassigning registers for function \"%s\"\n",PCF(pc)->fname));
5561 if (pb->tregisters) {
5563 for (r = setFirstItem(pb->tregisters); r; r = setNextItem(pb->tregisters)) {
5564 if (r->type == REG_GPR) {
5566 if (r->rIdx < (int)idx) {
5569 if (peakIdx < idx) peakIdx = idx;
5570 sprintf(s,"r0x%02X", r->rIdx);
5571 DFPRINTF((stderr," reassigning register \"%s\" to \"%s\"\n",r->name,s));
5573 r->name = Safe_strdup(s);
5579 for(pc = setFirstItem(pb->function_calls); pc; pc = setNextItem(pb->function_calls)) {
5581 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5582 char *dest = get_op_from_instruction(PCI(pc));
5584 pCode *pcn = findFunction(dest);
5586 register_reassign(pcn->pb,idx);
5595 /*------------------------------------------------------------------*/
5596 /* ReuseReg were call tree permits */
5598 /* Re-allocate the GPR for optimum reuse for a given pblock */
5599 /* eg if a function m() calls function f1() and f2(), where f1 */
5600 /* allocates a local variable vf1 and f2 allocates a local */
5601 /* variable vf2. Then providing f1 and f2 do not call each other */
5602 /* they may share the same general purpose registers for vf1 and */
5604 /* This is done by first setting the the regs rIdx to start after */
5605 /* all the global variables, then walking through the call tree */
5606 /* renaming the registers to match their new idx and incrementng */
5607 /* it as it goes. If a function has already been called it will */
5608 /* only rename the registers if it has already used up those */
5609 /* registers ie rIdx of the function's registers is lower than the */
5610 /* current rIdx. That way the register will not be reused while */
5611 /* still being used by an eariler function call. */
5613 /* Note for this to work the functions need to be declared static. */
5615 /*------------------------------------------------------------------*/
5620 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5621 /* Non static functions can be called from other modules so their registers must reassign */
5622 if (pb->function_entries&&(PCF(setFirstItem(pb->function_entries))->isPublic||!pb->visited))
5623 register_reassign(pb,peakIdx);
5627 /*-----------------------------------------------------------------*/
5628 /* buildCallTree - look at the flow and extract all of the calls */
5630 /*-----------------------------------------------------------------*/
5632 void buildCallTree(void )
5641 /* Now build the call tree.
5642 First we examine all of the pCodes for functions.
5643 Keep in mind that the function boundaries coincide
5644 with pBlock boundaries.
5646 The algorithm goes something like this:
5647 We have two nested loops. The outer loop iterates
5648 through all of the pBlocks/functions. The inner
5649 loop iterates through all of the pCodes for
5650 a given pBlock. When we begin iterating through
5651 a pBlock, the variable pc_fstart, pCode of the start
5652 of a function, is cleared. We then search for pCodes
5653 of type PC_FUNCTION. When one is encountered, we
5654 initialize pc_fstart to this and at the same time
5655 associate a new pBranch object that signifies a
5656 branch entry. If a return is found, then this signifies
5657 a function exit point. We'll link the pCodes of these
5658 returns to the matching pc_fstart.
5660 When we're done, a doubly linked list of pBranches
5661 will exist. The head of this list is stored in
5662 `the_pFile', which is the meta structure for all
5663 of the pCode. Look at the printCallTree function
5664 on how the pBranches are linked together.
5667 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5668 pCode *pc_fstart=NULL;
5669 for(pc = pb->pcHead; pc; pc = pc->next) {
5671 pCodeFunction *pcf = PCF(pc);
5674 if(STRCASECMP(pcf->fname, "_main") == 0) {
5675 //fprintf(stderr," found main \n");
5676 pb->cmemmap = NULL; /* FIXME do we need to free ? */
5680 pbr = Safe_calloc(1,sizeof(pBranch));
5681 pbr->pc = pc_fstart = pc;
5684 the_pFile->functions = pBranchAppend(the_pFile->functions,pbr);
5686 // Here's a better way of doing the same:
5687 addSet(&pb->function_entries, pc);
5690 // Found an exit point in a function, e.g. return
5691 // (Note, there may be more than one return per function)
5693 pBranchLink(PCF(pc_fstart), pcf);
5695 addSet(&pb->function_exits, pc);
5697 } else if(isCALL(pc)) {
5698 addSet(&pb->function_calls,pc);
5704 /*-----------------------------------------------------------------*/
5705 /* AnalyzepCode - parse the pCode that has been generated and form */
5706 /* all of the logical connections. */
5708 /* Essentially what's done here is that the pCode flow is */
5710 /*-----------------------------------------------------------------*/
5712 void AnalyzepCode(char dbName)
5723 /* Phase 1 - Register allocation and peep hole optimization
5725 * The first part of the analysis is to determine the registers
5726 * that are used in the pCode. Once that is done, the peep rules
5727 * are applied to the code. We continue to loop until no more
5728 * peep rule optimizations are found (or until we exceed the
5729 * MAX_PASSES threshold).
5731 * When done, the required registers will be determined.
5737 DFPRINTF((stderr," Analyzing pCode: PASS #%d\n",i+1));
5739 /* First, merge the labels with the instructions */
5740 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5741 if('*' == dbName || getpBlock_dbName(pb) == dbName) {
5743 DFPRINTF((stderr," analyze and merging block %c\n",dbName));
5744 pBlockMergeLabels(pb);
5747 DFPRINTF((stderr," skipping block analysis dbName=%c blockname=%c\n",dbName,getpBlock_dbName));
5751 changes = OptimizepCode(dbName);
5753 } while(changes && (i++ < MAX_PASSES));
5758 /*-----------------------------------------------------------------*/
5759 /* ispCodeFunction - returns true if *pc is the pCode of a */
5761 /*-----------------------------------------------------------------*/
5762 bool ispCodeFunction(pCode *pc)
5765 if(pc && pc->type == PC_FUNCTION && PCF(pc)->fname)
5771 /*-----------------------------------------------------------------*/
5772 /* findFunction - Search for a function by name (given the name) */
5773 /* in the set of all functions that are in a pBlock */
5774 /* (note - I expect this to change because I'm planning to limit */
5775 /* pBlock's to just one function declaration */
5776 /*-----------------------------------------------------------------*/
5777 pCode *findFunction(char *fname)
5784 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5786 pc = setFirstItem(pb->function_entries);
5789 if((pc->type == PC_FUNCTION) &&
5791 (strcmp(fname, PCF(pc)->fname)==0))
5794 pc = setNextItem(pb->function_entries);
5802 void MarkUsedRegisters(set *regset)
5807 for(r1=setFirstItem(regset); r1; r1=setNextItem(regset)) {
5808 r2 = pic14_regWithIdx(r1->rIdx);
5816 void pBlockStats(FILE *of, pBlock *pb)
5822 fprintf(of,";***\n; pBlock Stats: dbName = %c\n;***\n",getpBlock_dbName(pb));
5824 // for now just print the first element of each set
5825 pc = setFirstItem(pb->function_entries);
5827 fprintf(of,";entry: ");
5830 pc = setFirstItem(pb->function_exits);
5832 fprintf(of,";has an exit\n");
5836 pc = setFirstItem(pb->function_calls);
5838 fprintf(of,";functions called:\n");
5841 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5842 fprintf(of,"; %s\n",get_op_from_instruction(PCI(pc)));
5844 pc = setNextItem(pb->function_calls);
5848 r = setFirstItem(pb->tregisters);
5850 int n = elementsInSet(pb->tregisters);
5852 fprintf(of,";%d compiler assigned register%c:\n",n, ( (n!=1) ? 's' : ' '));
5855 fprintf(of,"; %s\n",r->name);
5856 r = setNextItem(pb->tregisters);
5861 /*-----------------------------------------------------------------*/
5862 /*-----------------------------------------------------------------*/
5864 static void sequencepCode(void)
5870 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
5872 pb->seq = GpCodeSequenceNumber+1;
5874 for( pc = pb->pcHead; pc; pc = pc->next)
5875 pc->seq = ++GpCodeSequenceNumber;
5881 /*-----------------------------------------------------------------*/
5882 /*-----------------------------------------------------------------*/
5884 set *register_usage(pBlock *pb)
5887 set *registers=NULL;
5888 set *registersInCallPath = NULL;
5890 / * check recursion * /
5892 pc = setFirstItem(pb->function_entries);
5899 if(pc->type != PC_FUNCTION)
5900 fprintf(stderr,"%s, first pc is not a function???\n",__FUNCTION__);
5902 pc = setFirstItem(pb->function_calls);
5903 for( ; pc; pc = setNextItem(pb->function_calls)) {
5905 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
5906 char *dest = get_op_from_instruction(PCI(pc));
5908 pcn = findFunction(dest);
5910 registersInCallPath = register_usage(pcn->pb);
5912 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
5917 pBlockStats(stderr,pb); // debug
5920 // Mark the registers in this block as used.
5922 MarkUsedRegisters(pb->tregisters);
5923 if(registersInCallPath) {
5924 / * registers were used in the functions this pBlock has called * /
5925 / * so now, we need to see if these collide with the ones we are * /
5928 regs *r1,*r2, *newreg;
5930 DFPRINTF((stderr,"comparing registers\n"));
5932 r1 = setFirstItem(registersInCallPath);
5934 if (r1->type != REG_STK) {
5935 r2 = setFirstItem(pb->tregisters);
5937 while(r2 && (r2->type != REG_STK)) {
5939 if(r2->rIdx == r1->rIdx) {
5940 newreg = pic14_findFreeReg(REG_GPR);
5944 DFPRINTF((stderr,"Bummer, no more registers.\n"));
5948 DFPRINTF((stderr,"Cool found register collision nIdx=%d moving to %d\n",
5949 r1->rIdx, newreg->rIdx));
5950 r2->rIdx = newreg->rIdx;
5952 r2->name = Safe_strdup(newreg->name);
5956 newreg->wasUsed = 1;
5958 r2 = setNextItem(pb->tregisters);
5962 r1 = setNextItem(registersInCallPath);
5965 / * Collisions have been resolved. Now free the registers in the call path * /
5966 r1 = setFirstItem(registersInCallPath);
5968 newreg = pic14_regWithIdx(r1->rIdx);
5969 if (newreg) newreg->isFree = 1;
5970 r1 = setNextItem(registersInCallPath);
5974 // MarkUsedRegisters(pb->registers);
5976 registers = unionSets(pb->tregisters, registersInCallPath, THROW_NONE);
5979 DFPRINTF((stderr,"returning regs\n"));
5981 DFPRINTF((stderr,"not returning regs\n"));
5983 DFPRINTF((stderr,"pBlock after register optim.\n"));
5984 pBlockStats(stderr,pb); // debug
5991 /*-----------------------------------------------------------------*/
5992 /* printCallTree - writes the call tree to a file */
5994 /*-----------------------------------------------------------------*/
5995 void pct2(FILE *of,pBlock *pb,int indent)
5999 // set *registersInCallPath = NULL;
6005 return; //recursion ?
6007 pc = setFirstItem(pb->function_entries);
6014 for(i=0;i<indent;i++) // Indentation
6017 if(pc->type == PC_FUNCTION)
6018 fprintf(of,"%s\n",PCF(pc)->fname);
6023 pc = setFirstItem(pb->function_calls);
6024 for( ; pc; pc = setNextItem(pb->function_calls)) {
6026 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL) {
6027 char *dest = get_op_from_instruction(PCI(pc));
6029 pcn = findFunction(dest);
6031 pct2(of,pcn->pb,indent+1);
6033 fprintf(of,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6041 /*-----------------------------------------------------------------*/
6042 /* printCallTree - writes the call tree to a file */
6044 /*-----------------------------------------------------------------*/
6046 void printCallTree(FILE *of)
6058 fprintf(of, "\npBlock statistics\n");
6059 for(pb = the_pFile->pbHead; pb; pb = pb->next )
6064 fprintf(of,"Call Tree\n");
6065 pbr = the_pFile->functions;
6069 if(!ispCodeFunction(pc))
6070 fprintf(of,"bug in call tree");
6073 fprintf(of,"Function: %s\n", PCF(pc)->fname);
6075 while(pc->next && !ispCodeFunction(pc->next)) {
6077 if(pc->type == PC_OPCODE && PCI(pc)->op == POC_CALL)
6078 fprintf(of,"\t%s\n",get_op_from_instruction(PCI(pc)));
6086 fprintf(of,"\n**************\n\na better call tree\n");
6087 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6092 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6093 fprintf(of,"block dbname: %c\n", getpBlock_dbName(pb));
6099 /*-----------------------------------------------------------------*/
6101 /*-----------------------------------------------------------------*/
6103 void InlineFunction(pBlock *pb)
6111 pc = setFirstItem(pb->function_calls);
6113 for( ; pc; pc = setNextItem(pb->function_calls)) {
6116 pCode *pcn = findFunction(get_op_from_instruction(PCI(pc)));
6117 pCode *pcp = pc->prev;
6123 if(pcn && isPCF(pcn) && (PCF(pcn)->ncalled == 1) && !PCF(pcn)->isPublic && (pcp && (isPCI_BITSKIP(pcp)||!isPCI_SKIP(pcp)))) { /* Bit skips can be inverted other skips can not */
6125 InlineFunction(pcn->pb);
6128 At this point, *pc points to a CALL mnemonic, and
6129 *pcn points to the function that is being called.
6131 To in-line this call, we need to remove the CALL
6132 and RETURN(s), and link the function pCode in with
6139 /* Check if previous instruction was a bit skip */
6140 if (isPCI_BITSKIP(pcp)) {
6142 /* Invert skip instruction and add a goto */
6143 PCI(pcp)->op = (PCI(pcp)->op == POC_BTFSS) ? POC_BTFSC : POC_BTFSS;
6145 if(isPCL(pc_call->next)) { // Label pcode
6146 pcl = PCL(pc_call->next);
6147 } else if (isPCI(pc_call->next) && PCI(pc_call->next)->label) { // pcode instruction with a label
6148 pcl = PCL(PCI(pc_call->next)->label->pc);
6150 pcl = PCL(newpCodeLabel(NULL, newiTempLabel(NULL)->key+100));
6151 PCI(pc_call->next)->label->pc = (struct pCode*)pcl;
6153 pCodeInsertAfter(pcp, newpCode(POC_GOTO, newpCodeOp(pcl->label,PO_STR)));
6156 /* remove callee pBlock from the pBlock linked list */
6157 removepBlock(pcn->pb);
6165 /* Remove the Function pCode */
6166 pct = findNextInstruction(pcn->next);
6168 /* Link the function with the callee */
6169 if (pcp) pcp->next = pcn->next;
6170 pcn->next->prev = pcp;
6172 /* Convert the function name into a label */
6174 pbr = Safe_calloc(1,sizeof(pBranch));
6175 pbr->pc = newpCodeLabel(PCF(pcn)->fname, -1);
6177 PCI(pct)->label = pBranchAppend(PCI(pct)->label,pbr);
6178 PCI(pct)->label = pBranchAppend(PCI(pct)->label,PCI(pc_call)->label);
6180 /* turn all of the return's except the last into goto's */
6181 /* check case for 2 instruction pBlocks */
6182 pce = findNextInstruction(pcn->next);
6184 pCode *pce_next = findNextInstruction(pce->next);
6186 if(pce_next == NULL) {
6187 /* found the last return */
6188 pCode *pc_call_next = findNextInstruction(pc_call->next);
6190 //fprintf(stderr,"found last return\n");
6191 //pce->print(stderr,pce);
6192 pce->prev->next = pc_call->next;
6193 pc_call->next->prev = pce->prev;
6194 PCI(pc_call_next)->label = pBranchAppend(PCI(pc_call_next)->label,
6203 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6209 /*-----------------------------------------------------------------*/
6211 /*-----------------------------------------------------------------*/
6213 void InlinepCode(void)
6222 if(!functionInlining)
6225 /* Loop through all of the function definitions and count the
6226 * number of times each one is called */
6227 //fprintf(stderr,"inlining %d\n",__LINE__);
6229 for(pb = the_pFile->pbHead; pb; pb = pb->next) {
6231 pc = setFirstItem(pb->function_calls);
6233 for( ; pc; pc = setNextItem(pb->function_calls)) {
6236 pCode *pcn = findFunction(get_op_from_instruction(PCI(pc)));
6237 if(pcn && isPCF(pcn)) {
6238 PCF(pcn)->ncalled++;
6241 fprintf(stderr,"BUG? pCode isn't a POC_CALL %d\n",__LINE__);
6246 //fprintf(stderr,"inlining %d\n",__LINE__);
6248 /* Now, Loop through the function definitions again, but this
6249 * time inline those functions that have only been called once. */
6251 InlineFunction(the_pFile->pbHead);
6252 //fprintf(stderr,"inlining %d\n",__LINE__);
6254 for(pb = the_pFile->pbHead; pb; pb = pb->next)