cda45d656521e7791b5a941127daf6a5ea244772
[deliverable/binutils-gdb.git] / sim / mips / interp.c
1 /*> interp.c <*/
2 /* Simulator for the MIPS architecture.
3
4 This file is part of the MIPS sim
5
6 THIS SOFTWARE IS NOT COPYRIGHTED
7
8 Cygnus offers the following for use in the public domain. Cygnus
9 makes no warranty with regard to the software or it's performance
10 and the user accepts the software "AS IS" with all faults.
11
12 CYGNUS DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO
13 THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
15
16 $Revision$
17 $Author$
18 $Date$
19
20 NOTEs:
21
22 We only need to take account of the target endianness when moving data
23 between the simulator and the host. We do not need to worry about the
24 endianness of the host, since this sim code and GDB are executing in
25 the same process.
26
27 The IDT monitor (found on the VR4300 board), seems to lie about
28 register contents. It seems to treat the registers as sign-extended
29 32-bit values. This cause *REAL* problems when single-stepping 64-bit
30 code on the hardware.
31
32 */
33
34 /* The TRACE and PROFILE manifests enable the provision of extra
35 features. If they are not defined then a simpler (quicker)
36 simulator is constructed without the required run-time checks,
37 etc. */
38 #if 1 /* 0 to allow user build selection, 1 to force inclusion */
39 #define TRACE (1)
40 #define PROFILE (1)
41 #endif
42
43 #include <stdio.h>
44 #include <stdarg.h>
45 #include <ansidecl.h>
46 #include <signal.h>
47 #include <ctype.h>
48 #include <limits.h>
49 #include <math.h>
50
51 #include "getopt.h"
52 #include "libiberty.h"
53
54 #include "remote-sim.h" /* GDB simulator interface */
55 #include "callback.h" /* GDB simulator callback interface */
56
57 #include "support.h" /* internal support manifests */
58
59 /* Get the simulator engine description, without including the code: */
60 #define SIM_MANIFESTS
61 #include "engine.c"
62 #undef SIM_MANIFESTS
63
64 /* The following reserved instruction value is used when a simulator
65 trap is required. NOTE: Care must be taken, since this value may be
66 used in later revisions of the MIPS ISA. */
67 #define RSVD_INSTRUCTION (0x7C000000)
68 #define RSVD_INSTRUCTION_AMASK (0x03FFFFFF)
69
70 /* NOTE: These numbers depend on the processor architecture being
71 simulated: */
72 #define Interrupt (0)
73 #define TLBModification (1)
74 #define TLBLoad (2)
75 #define TLBStore (3)
76 #define AddressLoad (4)
77 #define AddressStore (5)
78 #define InstructionFetch (6)
79 #define DataReference (7)
80 #define SystemCall (8)
81 #define BreakPoint (9)
82 #define ReservedInstruction (10)
83 #define CoProcessorUnusable (11)
84 #define IntegerOverflow (12) /* Arithmetic overflow (IDT monitor raises SIGFPE) */
85 #define Trap (13)
86 #define FPE (15)
87 #define Watch (23)
88
89 /* The following exception code is actually private to the simulator
90 world. It is *NOT* a processor feature, and is used to signal
91 run-time errors in the simulator. */
92 #define SimulatorFault (0xFFFFFFFF)
93
94 /* The following are generic to all versions of the MIPS architecture
95 to date: */
96 /* Memory Access Types (for CCA): */
97 #define Uncached (0)
98 #define CachedNoncoherent (1)
99 #define CachedCoherent (2)
100 #define Cached (3)
101
102 #define isINSTRUCTION (1 == 0) /* FALSE */
103 #define isDATA (1 == 1) /* TRUE */
104
105 #define isLOAD (1 == 0) /* FALSE */
106 #define isSTORE (1 == 1) /* TRUE */
107
108 #define isREAL (1 == 0) /* FALSE */
109 #define isRAW (1 == 1) /* TRUE */
110
111 #define isTARGET (1 == 0) /* FALSE */
112 #define isHOST (1 == 1) /* TRUE */
113
114 /* The "AccessLength" specifications for Loads and Stores. NOTE: This
115 is the number of bytes minus 1. */
116 #define AccessLength_BYTE (0)
117 #define AccessLength_HALFWORD (1)
118 #define AccessLength_TRIPLEBYTE (2)
119 #define AccessLength_WORD (3)
120 #define AccessLength_QUINTIBYTE (4)
121 #define AccessLength_SEXTIBYTE (5)
122 #define AccessLength_SEPTIBYTE (6)
123 #define AccessLength_DOUBLEWORD (7)
124
125 #if defined(HASFPU)
126 /* FPU registers must be one of the following types. All other values
127 are reserved (and undefined). */
128 typedef enum {
129 fmt_single = 0,
130 fmt_double = 1,
131 fmt_word = 4,
132 fmt_long = 5,
133 /* The following are well outside the normal acceptable format
134 range, and are used in the register status vector. */
135 fmt_unknown = 0x10000000,
136 fmt_uninterpreted = 0x20000000,
137 } FP_formats;
138 #endif /* HASFPU */
139
140 /* NOTE: We cannot avoid globals, since the GDB "sim_" interface does
141 not allow a private variable to be passed around. This means that
142 simulators under GDB can only be single-threaded. However, it would
143 be possible for the simulators to be multi-threaded if GDB allowed
144 for a private pointer to be maintained. i.e. a general "void **ptr"
145 variable that GDB passed around in the argument list to all of
146 sim_xxx() routines. It could be initialised to NULL by GDB, and
147 then updated by sim_open() and used by the other sim_xxx() support
148 functions. This would allow new features in the simulator world,
149 like storing a context - continuing execution to gather a result,
150 and then going back to the point where the context was saved and
151 changing some state before continuing. i.e. the ability to perform
152 UNDOs on simulations. It would also allow the simulation of
153 shared-memory multi-processor systems. */
154
155 static host_callback *callback = NULL; /* handle onto the current callback structure */
156
157 /* The warning system should be improved, to allow more information to
158 be passed about the cause: */
159 #define WARNING(m) { callback->printf_filtered(callback,"SIM Warning: %s\n",(m)); }
160
161 /* This is nasty, since we have to rely on matching the register
162 numbers used by GDB. Unfortunately, depending on the MIPS target
163 GDB uses different register numbers. We cannot just include the
164 relevant "gdb/tm.h" link, since GDB may not be configured before
165 the sim world, and also the GDB header file requires too much other
166 state. */
167 /* TODO: Sort out a scheme for *KNOWING* the mapping between real
168 registers, and the numbers that GDB uses. At the moment due to the
169 order that the tools are built, we cannot rely on a configured GDB
170 world whilst constructing the simulator. This means we have to
171 assume the GDB register number mapping. */
172 #define LAST_EMBED_REGNUM (89)
173
174 /* To keep this default simulator simple, and fast, we use a direct
175 vector of registers. The internal simulator engine then uses
176 manifests to access the correct slot. */
177 ut_reg registers[LAST_EMBED_REGNUM + 1];
178 int register_widths[LAST_EMBED_REGNUM + 1];
179
180 #define GPR (&registers[0])
181 #if defined(HASFPU)
182 #define FGRIDX (38)
183 #define FGR (&registers[FGRIDX])
184 #endif /* HASFPU */
185 #define LO (registers[33])
186 #define HI (registers[34])
187 #define PC (registers[37])
188 #define CAUSE (registers[36])
189 #define SRIDX (32)
190 #define SR (registers[SRIDX]) /* CPU status register */
191 #define FCR0IDX (71)
192 #define FCR0 (registers[FCR0IDX]) /* really a 32bit register */
193 #define FCR31IDX (70)
194 #define FCR31 (registers[FCR31IDX]) /* really a 32bit register */
195 #define FCSR (FCR31)
196 #define COCIDX (LAST_EMBED_REGNUM + 2) /* special case : outside the normal range */
197
198 /* The following are pseudonyms for standard registers */
199 #define ZERO (registers[0])
200 #define V0 (registers[2])
201 #define A0 (registers[4])
202 #define A1 (registers[5])
203 #define A2 (registers[6])
204 #define A3 (registers[7])
205 #define SP (registers[29])
206 #define RA (registers[31])
207
208 ut_reg EPC = 0; /* Exception PC */
209
210 #if defined(HASFPU)
211 /* Keep the current format state for each register: */
212 FP_formats fpr_state[32];
213 #endif /* HASFPU */
214
215 /* VR4300 CP0 configuration register: */
216 unsigned int CONFIG = 0;
217
218 /* The following are internal simulator state variables: */
219 ut_reg IPC = 0; /* internal Instruction PC */
220 ut_reg DSPC = 0; /* delay-slot PC */
221
222
223 /* TODO : these should be the bitmasks for these bits within the
224 status register. At the moment the following are VR4300
225 bit-positions: */
226 #define status_KSU_mask (0x3) /* mask for KSU bits */
227 #define status_KSU_shift (3) /* shift for field */
228 #define ksu_kernel (0x0)
229 #define ksu_supervisor (0x1)
230 #define ksu_user (0x2)
231 #define ksu_unknown (0x3)
232
233 #define status_RE (1 << 25) /* Reverse Endian in user mode */
234 #define status_FR (1 << 26) /* enables MIPS III additional FP registers */
235 #define status_SR (1 << 20) /* soft reset or NMI */
236 #define status_BEV (1 << 22) /* Location of general exception vectors */
237 #define status_TS (1 << 21) /* TLB shutdown has occurred */
238 #define status_ERL (1 << 2) /* Error level */
239 #define status_RP (1 << 27) /* Reduced Power mode */
240
241 #define config_EP_mask (0xF)
242 #define config_EP_shift (27)
243 #define config_EP_D (0x0)
244 #define config_EP_DxxDxx (0x6)
245
246 #define config_BE (1 << 15)
247
248 #define cause_BD ((unsigned)1 << 31) /* Exception in branch delay slot */
249
250 #if defined(HASFPU)
251 /* Macro to update FPSR condition-code field. This is complicated by
252 the fact that there is a hole in the index range of the bits within
253 the FCSR register. Also, the number of bits visible depends on the
254 MIPS ISA version being supported. */
255 #define SETFCC(cc,v) {\
256 int bit = ((cc == 0) ? 23 : (24 + (cc)));\
257 FCSR = ((FCSR & ~(1 << bit)) | ((v) << bit));\
258 }
259 #define GETFCC(cc) (((((cc) == 0) ? (FCSR & (1 << 23)) : (FCSR & (1 << (24 + (cc))))) != 0) ? 1 : 0)
260
261 /* This should be the COC1 value at the start of the preceding
262 instruction: */
263 #define PREVCOC1() ((state & simPCOC1) ? 1 : 0)
264 #endif /* HASFPU */
265
266 /* Standard FCRS bits: */
267 #define IR (0) /* Inexact Result */
268 #define UF (1) /* UnderFlow */
269 #define OF (2) /* OverFlow */
270 #define DZ (3) /* Division by Zero */
271 #define IO (4) /* Invalid Operation */
272 #define UO (5) /* Unimplemented Operation */
273
274 /* Get masks for individual flags: */
275 #if 1 /* SAFE version */
276 #define FP_FLAGS(b) (((unsigned)(b) < 5) ? (1 << ((b) + 2)) : 0)
277 #define FP_ENABLE(b) (((unsigned)(b) < 5) ? (1 << ((b) + 7)) : 0)
278 #define FP_CAUSE(b) (((unsigned)(b) < 6) ? (1 << ((b) + 12)) : 0)
279 #else
280 #define FP_FLAGS(b) (1 << ((b) + 2))
281 #define FP_ENABLE(b) (1 << ((b) + 7))
282 #define FP_CAUSE(b) (1 << ((b) + 12))
283 #endif
284
285 #define FP_FS (1 << 24) /* MIPS III onwards : Flush to Zero */
286
287 #define FP_MASK_RM (0x3)
288 #define FP_SH_RM (0)
289 #define FP_RM_NEAREST (0) /* Round to nearest (Round) */
290 #define FP_RM_TOZERO (1) /* Round to zero (Trunc) */
291 #define FP_RM_TOPINF (2) /* Round to Plus infinity (Ceil) */
292 #define FP_RM_TOMINF (3) /* Round to Minus infinity (Floor) */
293 #define GETRM() (int)((FCSR >> FP_SH_RM) & FP_MASK_RM)
294
295 /* Slots for delayed register updates. For the moment we just have a
296 fixed number of slots (rather than a more generic, dynamic
297 system). This keeps the simulator fast. However, we only allow for
298 the register update to be delayed for a single instruction
299 cycle. */
300 #define PSLOTS (5) /* Maximum number of instruction cycles */
301 int pending_in;
302 int pending_out;
303 int pending_total;
304 int pending_slot_count[PSLOTS];
305 int pending_slot_reg[PSLOTS];
306 ut_reg pending_slot_value[PSLOTS];
307
308 /* The following are not used for MIPS IV onwards: */
309 #define PENDING_FILL(r,v) {\
310 printf("DBG: FILL BEFORE pending_in = %d, pending_out = %d, pending_total = %d\n",pending_in,pending_out,pending_total);\
311 if (pending_slot_reg[pending_in] != (LAST_EMBED_REGNUM + 1))\
312 callback->printf_filtered(callback,"SIM Warning: Attempt to over-write pending value\n");\
313 pending_slot_count[pending_in] = 2;\
314 pending_slot_reg[pending_in] = (r);\
315 pending_slot_value[pending_in] = (uword64)(v);\
316 printf("DBG: FILL reg %d value = 0x%08X%08X\n",(r),WORD64HI(v),WORD64LO(v));\
317 pending_total++;\
318 pending_in++;\
319 if (pending_in == PSLOTS)\
320 pending_in = 0;\
321 printf("DBG: FILL AFTER pending_in = %d, pending_out = %d, pending_total = %d\n",pending_in,pending_out,pending_total);\
322 }
323
324 int LLBIT = 0;
325 /* LLBIT = Load-Linked bit. A bit of "virtual" state used by atomic
326 read-write instructions. It is set when a linked load occurs. It is
327 tested and cleared by the conditional store. It is cleared (during
328 other CPU operations) when a store to the location would no longer
329 be atomic. In particular, it is cleared by exception return
330 instructions. */
331
332 int HIACCESS = 0;
333 int LOACCESS = 0;
334 /* The HIACCESS and LOACCESS counts are used to ensure that
335 corruptions caused by using the HI or LO register to close to a
336 following operation are spotted. */
337
338 /* If either of the preceding two instructions have accessed the HI or
339 LO registers, then the values they see should be
340 undefined. However, to keep the simulator world simple, we just let
341 them use the value read and raise a warning to notify the user: */
342 #define CHECKHILO(s) {\
343 if ((HIACCESS != 0) || (LOACCESS != 0))\
344 callback->printf_filtered(callback,"SIM Warning: %s over-writing HI and LO registers values\n",(s));\
345 /* Set the access counts, since we are about\
346 to update the HI and LO registers: */\
347 HIACCESS = LOACCESS = 3; /* 3rd instruction will be safe */\
348 }
349
350 /* NOTE: We keep the following status flags as bit values (1 for true,
351 0 for false). This allows them to be used in binary boolean
352 operations without worrying about what exactly the non-zero true
353 value is. */
354
355 /* UserMode */
356 #define UserMode ((((SR & status_KSU_mask) >> status_KSU_shift) == ksu_user) ? 1 : 0)
357
358 /* BigEndianMem */
359 /* Hardware configuration. Affects endianness of LoadMemory and
360 StoreMemory and the endianness of Kernel and Supervisor mode
361 execution. The value is 0 for little-endian; 1 for big-endian. */
362 #define BigEndianMem ((CONFIG & config_BE) ? 1 : 0)
363 /* NOTE: Problems will occur if the simulator memory model does not
364 match the host program expectation. i.e. if the host is writing
365 big-endian values to a little-endian memory model. */
366
367 /* ReverseEndian */
368 /* This mode is selected if in User mode with the RE bit being set in
369 SR (Status Register). It reverses the endianness of load and store
370 instructions. */
371 #define ReverseEndian (((SR & status_RE) && UserMode) ? 1 : 0)
372
373 /* BigEndianCPU */
374 /* The endianness for load and store instructions (0=little;1=big). In
375 User mode this endianness may be switched by setting the state_RE
376 bit in the SR register. Thus, BigEndianCPU may be computed as
377 (BigEndienMem EOR ReverseEndian). */
378 #define BigEndianCPU (BigEndianMem ^ ReverseEndian) /* Already bits */
379
380 #if !defined(FASTSIM) || defined(PROFILE)
381 /* At the moment these values will be the same, since we do not have
382 access to the pipeline cycle count information from the simulator
383 engine. */
384 unsigned int instruction_fetches = 0;
385 unsigned int instruction_fetch_overflow = 0;
386 unsigned int pipeline_ticks = 0;
387 #endif
388
389 /* Flags in the "state" variable: */
390 #define simSTOP (1 << 0) /* 0 = execute; 1 = stop simulation */
391 #define simSTEP (1 << 1) /* 0 = run; 1 = single-step */
392 #define simHALTEX (1 << 2) /* 0 = run; 1 = halt on exception */
393 #define simHALTIN (1 << 3) /* 0 = run; 1 = halt on interrupt */
394 #define simTRACE (1 << 8) /* 0 = do nothing; 1 = trace address activity */
395 #define simPROFILE (1 << 9) /* 0 = do nothing; 1 = gather profiling samples */
396 #define simHOSTBE (1 << 10) /* 0 = little-endian; 1 = big-endian (host endianness) */
397 /* Whilst simSTOP is not set, the simulator control loop should just
398 keep simulating instructions. The simSTEP flag is used to force
399 single-step execution. */
400 #define simBE (1 << 16) /* 0 = little-endian; 1 = big-endian (target endianness) */
401 #define simPCOC0 (1 << 17) /* COC[1] from current */
402 #define simPCOC1 (1 << 18) /* COC[1] from previous */
403 #define simDELAYSLOT (1 << 24) /* 0 = do nothing; 1 = delay slot entry exists */
404 #define simSKIPNEXT (1 << 25) /* 0 = do nothing; 1 = skip instruction */
405 #define simEXCEPTION (1 << 26) /* 0 = no exception; 1 = exception has occurred */
406 #define simEXIT (1 << 27) /* 0 = do nothing; 1 = run-time exit() processing */
407
408 unsigned int state = (0 | simBE); /* big-endian simulator by default */
409 unsigned int rcexit = 0; /* _exit() reason code holder */
410
411 #define DELAYSLOT() {\
412 if (state & simDELAYSLOT) callback->printf_filtered(callback,"SIM Warning: Delay slot already activated (branch in delay slot?)\n");\
413 state |= simDELAYSLOT;\
414 }
415
416 #define NULLIFY() {\
417 state &= ~simDELAYSLOT;\
418 state |= simSKIPNEXT;\
419 }
420
421 #define K0BASE (0x80000000)
422 #define K0SIZE (0x20000000)
423 #define K1BASE (0xA0000000)
424 #define K1SIZE (0x20000000)
425
426 /* Very simple memory model to start with: */
427 unsigned char *membank = NULL;
428 ut_reg membank_base = K1BASE;
429 unsigned membank_size = (1 << 20); /* (16 << 20); */ /* power-of-2 */
430
431 /* Simple run-time monitor support */
432 unsigned char *monitor = NULL;
433 ut_reg monitor_base = 0xBFC00000;
434 unsigned monitor_size = (1 << 11); /* power-of-2 */
435
436 #if defined(TRACE)
437 char *tracefile = "trace.din"; /* default filename for trace log */
438 FILE *tracefh = NULL;
439 #endif /* TRACE */
440
441 #if defined(PROFILE)
442 unsigned profile_frequency = 256;
443 unsigned profile_nsamples = (128 << 10);
444 unsigned short *profile_hist = NULL;
445 ut_reg profile_minpc;
446 ut_reg profile_maxpc;
447 int profile_shift = 0; /* address shift amount */
448 #endif /* PROFILE */
449
450 /*---------------------------------------------------------------------------*/
451 /*-- GDB simulator interface ------------------------------------------------*/
452 /*---------------------------------------------------------------------------*/
453
454 static void dotrace PARAMS((FILE *tracefh,int type,unsigned int address,int width,char *comment,...));
455 extern void sim_error PARAMS((char *fmt,...));
456 static void ColdReset PARAMS((void));
457 static int AddressTranslation PARAMS((uword64 vAddr,int IorD,int LorS,uword64 *pAddr,int *CCA,int host,int raw));
458 static void StoreMemory PARAMS((int CCA,int AccessLength,uword64 MemElem,uword64 pAddr,uword64 vAddr,int raw));
459 static uword64 LoadMemory PARAMS((int CCA,int AccessLength,uword64 pAddr,uword64 vAddr,int IorD,int raw));
460 static void SignalException PARAMS((int exception,...));
461 static void simulate PARAMS((void));
462 static long getnum(char *value);
463 extern void sim_size(unsigned int newsize);
464 extern void sim_set_profile(int frequency);
465 static unsigned int power2(unsigned int value);
466
467 void
468 sim_open (args)
469 char *args;
470 {
471 if (callback == NULL) {
472 fprintf(stderr,"SIM Error: sim_open() called without callbacks attached\n");
473 return;
474 }
475
476 /* The following ensures that the standard file handles for stdin,
477 stdout and stderr are initialised: */
478 callback->init(callback);
479
480 state = 0;
481 CHECKSIM();
482 if (state & simEXCEPTION) {
483 fprintf(stderr,"This simulator is not suitable for this host configuration\n");
484 exit(1);
485 }
486
487 {
488 int data = 0x12;
489 if (*((char *)&data) != 0x12)
490 state |= simHOSTBE; /* big-endian host */
491 }
492
493 #if defined(HASFPU)
494 /* Check that the host FPU conforms to IEEE 754-1985 for the SINGLE
495 and DOUBLE binary formats. This is a bit nasty, requiring that we
496 trust the explicit manifests held in the source: */
497 {
498 unsigned int s[2];
499 s[state & simHOSTBE ? 0 : 1] = 0x40805A5A;
500 s[state & simHOSTBE ? 1 : 0] = 0x00000000;
501
502 /* TODO: We need to cope with the simulated target and the host
503 not having the same endianness. This will require the high and
504 low words of a (double) to be swapped when converting between
505 the host and the simulated target. */
506
507 if (((float)4.01102924346923828125 != *(float *)(s + ((state & simHOSTBE) ? 0 : 1))) || ((double)523.2939453125 != *(double *)s)) {
508 fprintf(stderr,"The host executing the simulator does not seem to have IEEE 754-1985 std FP\n");
509 fprintf(stderr,"*(float *)s = %.20f (4.01102924346923828125)\n",*(float *)s);
510 fprintf(stderr,"*(double *)s = %.20f (523.2939453125)\n",*(double *)s);
511 exit(1);
512 }
513 }
514 #endif /* HASFPU */
515
516 /* This is NASTY, in that we are assuming the size of specific
517 registers: */
518 {
519 int rn;
520 for (rn = 0; (rn < (LAST_EMBED_REGNUM + 1)); rn++) {
521 if (rn < 32)
522 register_widths[rn] = GPRLEN;
523 else if ((rn >= FGRIDX) && (rn < (FGRIDX + 32)))
524 register_widths[rn] = GPRLEN;
525 else if ((rn >= 33) && (rn <= 37))
526 register_widths[rn] = GPRLEN;
527 else if ((rn == SRIDX) || (rn == FCR0IDX) || (rn == FCR31IDX) || ((rn >= 72) && (rn <= 89)))
528 register_widths[rn] = 32;
529 else
530 register_widths[rn] = 0;
531 }
532 }
533
534 /* It would be good if we could select particular named MIPS
535 architecture simulators. However, having a pre-built, fixed
536 engine would mean including multiple engines. If the simulator is
537 changed to a run-time conditional version, then the ability to
538 select a particular architecture would be straightforward. */
539 if (args != NULL) {
540 int c;
541 char *cline;
542 char **argv;
543 int argc;
544 static struct option cmdline[] = {
545 {"help", 0,0,'h'},
546 {"name", 1,0,'n'},
547 {"profile", 0,0,'p'},
548 {"size", 1,0,'s'},
549 {"trace", 0,0,'t'},
550 {"tracefile",1,0,'z'},
551 {"frequency",1,0,'y'},
552 {"samples", 1,0,'x'},
553 {0, 0,0,0}
554 };
555
556 /* Unfortunately, getopt_long() is designed to be used with
557 vectors, where the first option is normally program name (and
558 ignored). We cheat by creating a dummy first argument, so that
559 we can use the standard argument processing. */
560 #define DUMMYARG "simulator "
561 cline = (char *)malloc(strlen(args) + strlen(DUMMYARG) + 1);
562 if (cline == NULL) {
563 fprintf(stderr,"Failed to allocate memory for command line buffer\n");
564 exit(1);
565 }
566 sprintf(cline,"%s%s",DUMMYARG,args);
567 argv = buildargv(cline);
568 for (argc = 0; argv[argc]; argc++);
569
570 /* Unfortunately, getopt_long() assumes that it is ignoring the
571 first argument (normally the program name). This means it
572 ignores the first option on our "args" line. */
573 optind = 0; /* Force reset of argument processing */
574 while (1) {
575 int option_index = 0;
576
577 c = getopt_long(argc,argv,"hn:s:tp",cmdline,&option_index);
578 if (c == -1)
579 break;
580
581 switch (c) {
582 case 'h':
583 callback->printf_filtered(callback,"Usage:\n\t\
584 target sim [-h] [--name=<model>] [--size=<amount>]");
585 #if defined(TRACE)
586 callback->printf_filtered(callback," [-t [--tracefile=<name>]]");
587 #endif /* TRACE */
588 #if defined(PROFILE)
589 callback->printf_filtered(callback," [-p [--frequency=<count>] [--samples=<count>]]");
590 #endif /* PROFILE */
591 callback->printf_filtered(callback,"\n");
592 break;
593
594 case 'n':
595 callback->printf_filtered(callback,"Explicit model selection not yet available (Ignoring \"%s\")\n",optarg);
596 break;
597
598 case 's':
599 membank_size = (unsigned)getnum(optarg);
600 break;
601
602 case 't':
603 #if defined(TRACE)
604 /* Eventually the simTRACE flag could be treated as a toggle, to
605 allow external control of the program points being traced
606 (i.e. only from main onwards, excluding the run-time setup,
607 etc.). */
608 state |= simTRACE;
609 #else /* !TRACE */
610 fprintf(stderr,"\
611 Simulator constructed without tracing support (for performance).\n\
612 Re-compile simulator with \"-DTRACE\" to enable this option.\n");
613 #endif /* !TRACE */
614 break;
615
616 case 'z':
617 #if defined(TRACE)
618 if (optarg != NULL) {
619 char *tmp;
620 tmp = (char *)malloc(strlen(optarg) + 1);
621 if (tmp == NULL)
622 callback->printf_filtered(callback,"Failed to allocate buffer for tracefile name \"%s\"\n",optarg);
623 else {
624 strcpy(tmp,optarg);
625 tracefile = tmp;
626 callback->printf_filtered(callback,"Placing trace information into file \"%s\"\n",tracefile);
627 }
628 }
629 #endif /* TRACE */
630 break;
631
632 case 'p':
633 #if defined(PROFILE)
634 state |= simPROFILE;
635 #else /* !PROFILE */
636 fprintf(stderr,"\
637 Simulator constructed without profiling support (for performance).\n\
638 Re-compile simulator with \"-DPROFILE\" to enable this option.\n");
639 #endif /* !PROFILE */
640 break;
641
642 case 'x':
643 #if defined(PROFILE)
644 profile_nsamples = (unsigned)getnum(optarg);
645 #endif /* PROFILE */
646 break;
647
648 case 'y':
649 #if defined(PROFILE)
650 sim_set_profile((int)getnum(optarg));
651 #endif /* PROFILE */
652 break;
653
654 default:
655 callback->printf_filtered(callback,"Warning: Simulator getopt returned unrecognised code 0x%08X\n",c);
656 case '?':
657 break;
658 }
659 }
660
661 if (optind < argc) {
662 callback->printf_filtered(callback,"Warning: Ignoring spurious non-option arguments ");
663 while (optind < argc)
664 callback->printf_filtered(callback,"\"%s\" ",argv[optind++]);
665 callback->printf_filtered(callback,"\n");
666 }
667
668 freeargv(argv);
669 }
670
671 /* If the host has "mmap" available we could use it to provide a
672 very large virtual address space for the simulator, since memory
673 would only be allocated within the "mmap" space as it is
674 accessed. This can also be linked to the architecture specific
675 support, required to simulate the MMU. */
676 sim_size(membank_size);
677 /* NOTE: The above will also have enabled any profiling state */
678
679 ColdReset();
680 /* If we were providing a more complete I/O, co-processor or memory
681 simulation, we should perform any "device" initialisation at this
682 point. This can include pre-loading memory areas with particular
683 patterns (e.g. simulating ROM monitors). */
684
685 /* We can start writing to the memory, now that the processor has
686 been reset: */
687 monitor = (unsigned char *)calloc(1,monitor_size);
688 if (!monitor) {
689 fprintf(stderr,"Not enough VM for monitor simulation (%d bytes)\n",monitor_size);
690 } else {
691 int loop;
692 /* Entry into the IDT monitor is via fixed address vectors, and
693 not using machine instructions. To avoid clashing with use of
694 the MIPS TRAP system, we place our own (simulator specific)
695 "undefined" instructions into the relevant vector slots. */
696 for (loop = 0; (loop < monitor_size); loop += 4) {
697 uword64 vaddr = (monitor_base + loop);
698 uword64 paddr;
699 int cca;
700 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW))
701 StoreMemory(cca,AccessLength_WORD,(RSVD_INSTRUCTION | ((loop >> 2) & RSVD_INSTRUCTION_AMASK)),paddr,vaddr,isRAW);
702 }
703 /* The PMON monitor uses the same address space, but rather than
704 branching into it the address of a routine is loaded. We can
705 cheat for the moment, and direct the PMON routine to IDT style
706 instructions within the monitor space. This relies on the IDT
707 monitor not using the locations from 0xBFC00500 onwards as its
708 entry points.*/
709 for (loop = 0; (loop < 24); loop++)
710 {
711 uword64 vaddr = (monitor_base + 0x500 + (loop * 4));
712 uword64 paddr;
713 int cca;
714 unsigned int value = ((0x500 - 8) / 8); /* default UNDEFINED reason code */
715 switch (loop)
716 {
717 case 0: /* read */
718 value = 7;
719 break;
720
721 case 1: /* write */
722 value = 8;
723 break;
724
725 case 2: /* open */
726 value = 6;
727 break;
728
729 case 3: /* close */
730 value = 10;
731 break;
732
733 case 5: /* printf */
734 value = ((0x500 - 16) / 8); /* not an IDT reason code */
735 break;
736
737 case 8: /* cliexit */
738 value = 17;
739 break;
740 }
741 value = (monitor_base + (value * 8));
742 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW))
743 StoreMemory(cca,AccessLength_WORD,value,paddr,vaddr,isRAW);
744 else
745 callback->printf_filtered(callback,"Failed to write to monitor space 0x%08X%08X\n",WORD64HI(vaddr),WORD64LO(vaddr));
746 }
747 }
748
749 #if defined(TRACE)
750 if (state & simTRACE) {
751 tracefh = fopen(tracefile,"wb+");
752 if (tracefh == NULL) {
753 callback->printf_filtered(callback,"Failed to create file \"%s\", writing trace information to stderr.\n",tracefile);
754 tracefh = stderr;
755 }
756 }
757 #endif /* TRACE */
758
759 return;
760 }
761
762 /* For the profile writing, we write the data in the host
763 endianness. This unfortunately means we are assuming that the
764 profile file we create is processed on the same host executing the
765 simulator. The gmon.out file format should either have an explicit
766 endianness, or a method of encoding the endianness in the file
767 header. */
768 static int
769 writeout32(fh,val)
770 FILE *fh;
771 unsigned int val;
772 {
773 char buff[4];
774 int res = 1;
775
776 if (state & simHOSTBE) {
777 buff[3] = ((val >> 0) & 0xFF);
778 buff[2] = ((val >> 8) & 0xFF);
779 buff[1] = ((val >> 16) & 0xFF);
780 buff[0] = ((val >> 24) & 0xFF);
781 } else {
782 buff[0] = ((val >> 0) & 0xFF);
783 buff[1] = ((val >> 8) & 0xFF);
784 buff[2] = ((val >> 16) & 0xFF);
785 buff[3] = ((val >> 24) & 0xFF);
786 }
787 if (fwrite(buff,4,1,fh) != 1) {
788 callback->printf_filtered(callback,"Failed to write 4bytes to the profile file\n");
789 res = 0;
790 }
791 return(res);
792 }
793
794 static int
795 writeout16(fh,val)
796 FILE *fh;
797 unsigned short val;
798 {
799 char buff[2];
800 int res = 1;
801 if (state & simHOSTBE) {
802 buff[1] = ((val >> 0) & 0xFF);
803 buff[0] = ((val >> 8) & 0xFF);
804 } else {
805 buff[0] = ((val >> 0) & 0xFF);
806 buff[1] = ((val >> 8) & 0xFF);
807 }
808 if (fwrite(buff,2,1,fh) != 1) {
809 callback->printf_filtered(callback,"Failed to write 2bytes to the profile file\n");
810 res = 0;
811 }
812 return(res);
813 }
814
815 void
816 sim_close (quitting)
817 int quitting;
818 {
819 #ifdef DEBUG
820 printf("DBG: sim_close: entered (quitting = %d)\n",quitting);
821 #endif
822
823 /* Cannot assume sim_kill() has been called */
824 /* "quitting" is non-zero if we cannot hang on errors */
825
826 /* Ensure that any resources allocated through the callback
827 mechanism are released: */
828 callback->shutdown(callback);
829
830 #if defined(PROFILE)
831 if ((state & simPROFILE) && (profile_hist != NULL)) {
832 unsigned short *p = profile_hist;
833 FILE *pf = fopen("gmon.out","wb");
834 int loop;
835
836 if (pf == NULL)
837 callback->printf_filtered(callback,"Failed to open \"gmon.out\" profile file\n");
838 else {
839 int ok;
840 #ifdef DEBUG
841 printf("DBG: minpc = 0x%08X\n",(unsigned int)profile_minpc);
842 printf("DBG: maxpc = 0x%08X\n",(unsigned int)profile_maxpc);
843 #endif /* DEBUG */
844 ok = writeout32(pf,(unsigned int)profile_minpc);
845 if (ok)
846 ok = writeout32(pf,(unsigned int)profile_maxpc);
847 if (ok)
848 ok = writeout32(pf,(profile_nsamples * 2) + 12); /* size of sample buffer (+ header) */
849 #ifdef DEBUG
850 printf("DBG: nsamples = %d (size = 0x%08X)\n",profile_nsamples,((profile_nsamples * 2) + 12));
851 #endif /* DEBUG */
852 for (loop = 0; (ok && (loop < profile_nsamples)); loop++) {
853 ok = writeout16(pf,profile_hist[loop]);
854 if (!ok)
855 break;
856 }
857
858 fclose(pf);
859 }
860
861 free(profile_hist);
862 profile_hist = NULL;
863 state &= ~simPROFILE;
864 }
865 #endif /* PROFILE */
866
867 #if defined(TRACE)
868 if (tracefh != stderr)
869 fclose(tracefh);
870 state &= ~simTRACE;
871 #endif /* TRACE */
872
873 if (membank)
874 free(membank); /* cfree not available on all hosts */
875 membank = NULL;
876
877 return;
878 }
879
880 void
881 sim_resume (step,signal)
882 int step, signal;
883 {
884 #ifdef DEBUG
885 printf("DBG: sim_resume entered: step = %d, signal = %d (membank = 0x%08X)\n",step,signal,membank);
886 #endif /* DEBUG */
887
888 if (step)
889 state |= simSTEP; /* execute only a single instruction */
890 else
891 state &= ~(simSTOP | simSTEP); /* execute until event */
892
893 state |= (simHALTEX | simHALTIN); /* treat interrupt event as exception */
894
895 /* Start executing instructions from the current state (set
896 explicitly by register updates, or by sim_create_inferior): */
897
898 simulate();
899 return;
900 }
901
902 int
903 sim_write (addr,buffer,size)
904 SIM_ADDR addr;
905 unsigned char *buffer;
906 int size;
907 {
908 int index = size;
909 uword64 vaddr = (uword64)addr;
910
911 /* Return the number of bytes written, or zero if error. */
912 #ifdef DEBUG
913 callback->printf_filtered(callback,"sim_write(0x%08X%08X,buffer,%d);\n",WORD64HI(addr),WORD64LO(addr),size);
914 #endif
915
916 /* We provide raw read and write routines, since we do not want to
917 count the GDB memory accesses in our statistics gathering. */
918
919 /* There is a lot of code duplication in the individual blocks
920 below, but the variables are declared locally to a block to give
921 the optimiser the best chance of improving the code. We have to
922 perform slow byte reads from the host memory, to ensure that we
923 get the data into the correct endianness for the (simulated)
924 target memory world. */
925
926 /* Mask count to get odd byte, odd halfword, and odd word out of the
927 way. We can then perform doubleword transfers to and from the
928 simulator memory for optimum performance. */
929 if (index && (index & 1)) {
930 uword64 paddr;
931 int cca;
932 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW)) {
933 uword64 value = ((uword64)(*buffer++));
934 StoreMemory(cca,AccessLength_BYTE,value,paddr,vaddr,isRAW);
935 }
936 vaddr++;
937 index &= ~1; /* logical operations usually quicker than arithmetic on RISC systems */
938 }
939 if (index && (index & 2)) {
940 uword64 paddr;
941 int cca;
942 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW)) {
943 uword64 value;
944 /* We need to perform the following magic to ensure that that
945 bytes are written into same byte positions in the target memory
946 world, regardless of the endianness of the host. */
947 if (BigEndianMem) {
948 value = ((uword64)(*buffer++) << 8);
949 value |= ((uword64)(*buffer++) << 0);
950 } else {
951 value = ((uword64)(*buffer++) << 0);
952 value |= ((uword64)(*buffer++) << 8);
953 }
954 StoreMemory(cca,AccessLength_HALFWORD,value,paddr,vaddr,isRAW);
955 }
956 vaddr += 2;
957 index &= ~2;
958 }
959 if (index && (index & 4)) {
960 uword64 paddr;
961 int cca;
962 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW)) {
963 uword64 value;
964 if (BigEndianMem) {
965 value = ((uword64)(*buffer++) << 24);
966 value |= ((uword64)(*buffer++) << 16);
967 value |= ((uword64)(*buffer++) << 8);
968 value |= ((uword64)(*buffer++) << 0);
969 } else {
970 value = ((uword64)(*buffer++) << 0);
971 value |= ((uword64)(*buffer++) << 8);
972 value |= ((uword64)(*buffer++) << 16);
973 value |= ((uword64)(*buffer++) << 24);
974 }
975 StoreMemory(cca,AccessLength_WORD,value,paddr,vaddr,isRAW);
976 }
977 vaddr += 4;
978 index &= ~4;
979 }
980 for (;index; index -= 8) {
981 uword64 paddr;
982 int cca;
983 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isRAW)) {
984 uword64 value;
985 if (BigEndianMem) {
986 value = ((uword64)(*buffer++) << 56);
987 value |= ((uword64)(*buffer++) << 48);
988 value |= ((uword64)(*buffer++) << 40);
989 value |= ((uword64)(*buffer++) << 32);
990 value |= ((uword64)(*buffer++) << 24);
991 value |= ((uword64)(*buffer++) << 16);
992 value |= ((uword64)(*buffer++) << 8);
993 value |= ((uword64)(*buffer++) << 0);
994 } else {
995 value = ((uword64)(*buffer++) << 0);
996 value |= ((uword64)(*buffer++) << 8);
997 value |= ((uword64)(*buffer++) << 16);
998 value |= ((uword64)(*buffer++) << 24);
999 value |= ((uword64)(*buffer++) << 32);
1000 value |= ((uword64)(*buffer++) << 40);
1001 value |= ((uword64)(*buffer++) << 48);
1002 value |= ((uword64)(*buffer++) << 56);
1003 }
1004 StoreMemory(cca,AccessLength_DOUBLEWORD,value,paddr,vaddr,isRAW);
1005 }
1006 vaddr += 8;
1007 }
1008
1009 return(size);
1010 }
1011
1012 int
1013 sim_read (addr,buffer,size)
1014 SIM_ADDR addr;
1015 unsigned char *buffer;
1016 int size;
1017 {
1018 int index;
1019
1020 /* Return the number of bytes read, or zero if error. */
1021 #ifdef DEBUG
1022 callback->printf_filtered(callback,"sim_read(0x%08X%08X,buffer,%d);\n",WORD64HI(addr),WORD64LO(addr),size);
1023 #endif /* DEBUG */
1024
1025 /* TODO: Perform same optimisation as the sim_write() code
1026 above. NOTE: This will require a bit more work since we will need
1027 to ensure that the source physical address is doubleword aligned
1028 before, and then deal with trailing bytes. */
1029 for (index = 0; (index < size); index++) {
1030 uword64 vaddr,paddr,value;
1031 int cca;
1032 vaddr = (uword64)addr + index;
1033 if (AddressTranslation(vaddr,isDATA,isLOAD,&paddr,&cca,isTARGET,isRAW)) {
1034 value = LoadMemory(cca,AccessLength_BYTE,paddr,vaddr,isDATA,isRAW);
1035 buffer[index] = (unsigned char)(value&0xFF);
1036 } else
1037 break;
1038 }
1039
1040 return(index);
1041 }
1042
1043 void
1044 sim_store_register (rn,memory)
1045 int rn;
1046 unsigned char *memory;
1047 {
1048 #ifdef DEBUG
1049 callback->printf_filtered(callback,"sim_store_register(%d,*memory=0x%08X%08X);\n",rn,*((unsigned int *)memory),*((unsigned int *)(memory + 4)));
1050 #endif /* DEBUG */
1051
1052 /* Unfortunately this suffers from the same problem as the register
1053 numbering one. We need to know what the width of each logical
1054 register number is for the architecture being simulated. */
1055 if (register_widths[rn] == 0)
1056 callback->printf_filtered(callback,"Warning: Invalid register width for %d (register store ignored)\n",rn);
1057 else {
1058 if (register_widths[rn] == 32)
1059 registers[rn] = *((unsigned int *)memory);
1060 else
1061 registers[rn] = *((uword64 *)memory);
1062 }
1063
1064 return;
1065 }
1066
1067 void
1068 sim_fetch_register (rn,memory)
1069 int rn;
1070 unsigned char *memory;
1071 {
1072 #ifdef DEBUG
1073 callback->printf_filtered(callback,"sim_fetch_register(%d=0x%08X%08X,mem) : place simulator registers into memory\n",rn,WORD64HI(registers[rn]),WORD64LO(registers[rn]));
1074 #endif /* DEBUG */
1075
1076 if (register_widths[rn] == 0)
1077 callback->printf_filtered(callback,"Warning: Invalid register width for %d (register fetch ignored)\n",rn);
1078 else {
1079 if (register_widths[rn] == 32)
1080 *((unsigned int *)memory) = (registers[rn] & 0xFFFFFFFF);
1081 else /* 64bit register */
1082 *((uword64 *)memory) = registers[rn];
1083 }
1084 return;
1085 }
1086
1087 void
1088 sim_stop_reason (reason,sigrc)
1089 enum sim_stop *reason;
1090 int *sigrc;
1091 {
1092 /* We can have "*reason = {sim_exited, sim_stopped, sim_signalled}", so
1093 sim_exited *sigrc = argument to exit()
1094 sim_stopped *sigrc = exception number
1095 sim_signalled *sigrc = signal number
1096 */
1097 if (state & simEXCEPTION) {
1098 /* If "sim_signalled" is used, GDB expects normal SIGNAL numbers,
1099 and not the MIPS specific exception codes. */
1100 #if 1
1101 /* For some reason, sending GDB a sim_signalled reason cause it to
1102 terminate out. */
1103 *reason = sim_stopped;
1104 #else
1105 *reason = sim_signalled;
1106 #endif
1107 switch ((CAUSE >> 2) & 0x1F) {
1108 case Interrupt:
1109 *sigrc = SIGINT; /* wrong type of interrupt, but it will do for the moment */
1110 break;
1111
1112 case TLBModification:
1113 case TLBLoad:
1114 case TLBStore:
1115 case AddressLoad:
1116 case AddressStore:
1117 case InstructionFetch:
1118 case DataReference:
1119 *sigrc = SIGBUS;
1120 break;
1121
1122 case ReservedInstruction:
1123 case CoProcessorUnusable:
1124 *sigrc = SIGILL;
1125 break;
1126
1127 case IntegerOverflow:
1128 case FPE:
1129 *sigrc = SIGFPE;
1130 break;
1131
1132 case Trap:
1133 case Watch:
1134 case SystemCall:
1135 case BreakPoint:
1136 *sigrc = SIGTRAP;
1137 break;
1138
1139 default : /* Unknown internal exception */
1140 *sigrc = SIGQUIT;
1141 break;
1142 }
1143 } else if (state & simEXIT) {
1144 printf("DBG: simEXIT (%d)\n",rcexit);
1145 *reason = sim_exited;
1146 *sigrc = rcexit;
1147 } else { /* assume single-stepping */
1148 *reason = sim_stopped;
1149 *sigrc = SIGTRAP;
1150 }
1151 state &= ~(simEXCEPTION | simEXIT);
1152 return;
1153 }
1154
1155 void
1156 sim_info (verbose)
1157 int verbose;
1158 {
1159 /* Accessed from the GDB "info files" command: */
1160
1161 callback->printf_filtered(callback,"MIPS %d-bit simulator\n",(PROCESSOR_64BIT ? 64 : 32));
1162
1163 callback->printf_filtered(callback,"%s endian memory model\n",(BigEndianMem ? "Big" : "Little"));
1164
1165 callback->printf_filtered(callback,"0x%08X bytes of memory at 0x%08X%08X\n",(unsigned int)membank_size,WORD64HI(membank_base),WORD64LO(membank_base));
1166
1167 #if !defined(FASTSIM)
1168 if (instruction_fetch_overflow != 0)
1169 callback->printf_filtered(callback,"Instruction fetches = 0x%08X%08X\n",instruction_fetch_overflow,instruction_fetches);
1170 else
1171 callback->printf_filtered(callback,"Instruction fetches = %d\n",instruction_fetches);
1172 callback->printf_filtered(callback,"Pipeline ticks = %d\n",pipeline_ticks);
1173 /* It would be a useful feature, if when performing multi-cycle
1174 simulations (rather than single-stepping) we keep the start and
1175 end times of the execution, so that we can give a performance
1176 figure for the simulator. */
1177 #endif /* !FASTSIM */
1178
1179 /* print information pertaining to MIPS ISA and architecture being simulated */
1180 /* things that may be interesting */
1181 /* instructions executed - if available */
1182 /* cycles executed - if available */
1183 /* pipeline stalls - if available */
1184 /* virtual time taken */
1185 /* profiling size */
1186 /* profiling frequency */
1187 /* profile minpc */
1188 /* profile maxpc */
1189
1190 return;
1191 }
1192
1193 int
1194 sim_load (prog,from_tty)
1195 char *prog;
1196 int from_tty;
1197 {
1198 /* Return non-zero if the caller should handle the load. Zero if
1199 we have loaded the image. */
1200 return(-1);
1201 }
1202
1203 void
1204 sim_create_inferior (start_address,argv,env)
1205 SIM_ADDR start_address;
1206 char **argv;
1207 char **env;
1208 {
1209 #ifdef DEBUG
1210 printf("DBG: sim_create_inferior entered: start_address = 0x%08X\n",start_address);
1211 #endif /* DEBUG */
1212
1213 /* Prepare to execute the program to be simulated */
1214 /* argv and env are NULL terminated lists of pointers */
1215
1216 #if 1
1217 PC = (uword64)start_address;
1218 #else
1219 /* TODO: Sort this properly. SIM_ADDR may already be a 64bit value: */
1220 PC = SIGNEXTEND(start_address,32);
1221 #endif
1222 /* NOTE: GDB normally sets the PC explicitly. However, this call is
1223 used by other clients of the simulator. */
1224
1225 if (argv || env) {
1226 callback->printf_filtered(callback,"sim_create_inferior() : passed arguments ignored\n");
1227 #if 1 /* def DEBUG */
1228 {
1229 char **cptr;
1230 for (cptr = argv; (cptr && *cptr); cptr++)
1231 printf("DBG: arg \"%s\"\n",*cptr);
1232 }
1233 #endif /* DEBUG */
1234 /* We should really place the argv slot values into the argument
1235 registers, and onto the stack as required. However, this
1236 assumes that we have a stack defined, which is not necessarily
1237 true at the moment. */
1238 }
1239
1240 return;
1241 }
1242
1243 void
1244 sim_kill ()
1245 {
1246 #if 1
1247 /* This routine should be for terminating any existing simulation
1248 thread. Since we are single-threaded only at the moment, this is
1249 not an issue. It should *NOT* be used to terminate the
1250 simulator. */
1251 #else /* do *NOT* call sim_close */
1252 sim_close(1); /* Do not hang on errors */
1253 /* This would also be the point where any memory mapped areas used
1254 by the simulator should be released. */
1255 #endif
1256 return;
1257 }
1258
1259 int
1260 sim_get_quit_code ()
1261 {
1262 /* The standard MIPS PCS (Procedure Calling Standard) uses V0(r2) as
1263 the function return value. However, it may be more correct for
1264 this to return the argument to the exit() function (if
1265 called). */
1266 return(V0);
1267 }
1268
1269 void
1270 sim_set_callbacks (p)
1271 host_callback *p;
1272 {
1273 callback = p;
1274 return;
1275 }
1276
1277 typedef enum {e_terminate,e_help,e_setmemsize,e_reset} e_cmds;
1278
1279 static struct t_sim_command {
1280 e_cmds id;
1281 const char *name;
1282 const char *help;
1283 } sim_commands[] = {
1284 {e_help, "help", ": Show MIPS simulator private commands"},
1285 {e_setmemsize,"set-memory-size","<n> : Specify amount of memory simulated"},
1286 {e_reset, "reset-system", ": Reset the simulated processor"},
1287 {e_terminate, NULL}
1288 };
1289
1290 void
1291 sim_do_command (cmd)
1292 char *cmd;
1293 {
1294 struct t_sim_command *cptr;
1295
1296 if (callback == NULL) {
1297 fprintf(stderr,"Simulator not enabled: \"target sim\" should be used to activate\n");
1298 return;
1299 }
1300
1301 if (!(cmd && *cmd != '\0'))
1302 cmd = "help";
1303
1304 /* NOTE: Accessed from the GDB "sim" commmand: */
1305 for (cptr = sim_commands; cptr && cptr->name; cptr++)
1306 if (strncmp(cmd,cptr->name,strlen(cptr->name)) == 0) {
1307 cmd += strlen(cptr->name);
1308 switch (cptr->id) {
1309 case e_help: /* no arguments */
1310 { /* no arguments */
1311 struct t_sim_command *lptr;
1312 callback->printf_filtered(callback,"List of MIPS simulator commands:\n");
1313 for (lptr = sim_commands; lptr->name; lptr++)
1314 callback->printf_filtered(callback,"%s %s\n",lptr->name,lptr->help);
1315 }
1316 break;
1317
1318 case e_setmemsize: /* memory size argument */
1319 {
1320 unsigned int newsize = (unsigned int)getnum(cmd);
1321 sim_size(newsize);
1322 }
1323 break;
1324
1325 case e_reset: /* no arguments */
1326 ColdReset();
1327 /* NOTE: See the comments in sim_open() relating to device
1328 initialisation. */
1329 break;
1330
1331 default:
1332 callback->printf_filtered(callback,"FATAL: Matched \"%s\", but failed to match command id %d.\n",cmd,cptr->id);
1333 break;
1334 }
1335 break;
1336 }
1337
1338 if (!(cptr->name))
1339 callback->printf_filtered(callback,"Error: \"%s\" is not a valid MIPS simulator command.\n",cmd);
1340
1341 return;
1342 }
1343
1344 /*---------------------------------------------------------------------------*/
1345 /* NOTE: The following routines do not seem to be used by GDB at the
1346 moment. However, they may be useful to the standalone simulator
1347 world. */
1348
1349
1350 /* The profiling format is described in the "gmon_out.h" header file */
1351 void
1352 sim_set_profile (n)
1353 int n;
1354 {
1355 #if defined(PROFILE)
1356 profile_frequency = n;
1357 state |= simPROFILE;
1358 #endif /* PROFILE */
1359 return;
1360 }
1361
1362 void
1363 sim_set_profile_size (n)
1364 int n;
1365 {
1366 #if defined(PROFILE)
1367 if (state & simPROFILE) {
1368 int bsize;
1369
1370 /* Since we KNOW that the memory banks are a power-of-2 in size: */
1371 profile_nsamples = power2(n);
1372 profile_minpc = membank_base;
1373 profile_maxpc = (membank_base + membank_size);
1374
1375 /* Just in-case we are sampling every address: NOTE: The shift
1376 right of 2 is because we only have word-aligned PC addresses. */
1377 if (profile_nsamples > (membank_size >> 2))
1378 profile_nsamples = (membank_size >> 2);
1379
1380 /* Since we are dealing with power-of-2 values: */
1381 profile_shift = (((membank_size >> 2) / profile_nsamples) - 1);
1382
1383 bsize = (profile_nsamples * sizeof(unsigned short));
1384 if (profile_hist == NULL)
1385 profile_hist = (unsigned short *)calloc(64,(bsize / 64));
1386 else
1387 profile_hist = (unsigned short *)realloc(profile_hist,bsize);
1388 if (profile_hist == NULL) {
1389 callback->printf_filtered(callback,"Failed to allocate VM for profiling buffer (0x%08X bytes)\n",bsize);
1390 state &= ~simPROFILE;
1391 }
1392 }
1393 #endif /* PROFILE */
1394
1395 return;
1396 }
1397
1398 void
1399 sim_size(newsize)
1400 unsigned int newsize;
1401 {
1402 char *new;
1403 /* Used by "run", and internally, to set the simulated memory size */
1404 newsize = power2(newsize);
1405 if (membank == NULL)
1406 new = (char *)calloc(64,(membank_size / 64));
1407 else
1408 new = (char *)realloc(membank,newsize);
1409 if (new == NULL) {
1410 if (membank == NULL)
1411 callback->printf_filtered(callback,"Not enough VM for simulation memory of 0x%08X bytes\n",membank_size);
1412 else
1413 callback->printf_filtered(callback,"Failed to resize memory (still 0x%08X bytes)\n",membank_size);
1414 } else {
1415 membank_size = (unsigned)newsize;
1416 membank = new;
1417 callback->printf_filtered(callback,"Memory size now 0x%08X bytes\n",membank_size);
1418 #if defined(PROFILE)
1419 /* Ensure that we sample across the new memory range */
1420 sim_set_profile_size(profile_nsamples);
1421 #endif /* PROFILE */
1422 }
1423
1424 return;
1425 }
1426
1427 int
1428 sim_trace()
1429 {
1430 /* This routine is called by the "run" program, when detailed
1431 execution information is required. Rather than executing a single
1432 instruction, and looping around externally... we just start
1433 simulating, returning TRUE when the simulator stops (for whatever
1434 reason). */
1435
1436 #if defined(TRACE)
1437 /* Ensure tracing is enabled, if available */
1438 if (tracefh != NULL)
1439 state |= simTRACE;
1440 #endif /* TRACE */
1441
1442 state &= ~(simSTOP | simSTEP); /* execute until event */
1443 state |= (simHALTEX | simHALTIN); /* treat interrupt event as exception */
1444 /* Start executing instructions from the current state (set
1445 explicitly by register updates, or by sim_create_inferior): */
1446 simulate();
1447
1448 return(1);
1449 }
1450
1451 /*---------------------------------------------------------------------------*/
1452 /*-- Private simulator support interface ------------------------------------*/
1453 /*---------------------------------------------------------------------------*/
1454
1455 /* Simple monitor interface (currently setup for the IDT and PMON monitors) */
1456 static void
1457 sim_monitor(reason)
1458 unsigned int reason;
1459 {
1460 /* The IDT monitor actually allows two instructions per vector
1461 slot. However, the simulator currently causes a trap on each
1462 individual instruction. We cheat, and lose the bottom bit. */
1463 reason >>= 1;
1464
1465 /* The following callback functions are available, however the
1466 monitor we are simulating does not make use of them: get_errno,
1467 isatty, lseek, rename, system, time and unlink */
1468 switch (reason) {
1469 case 6: /* int open(char *path,int flags) */
1470 {
1471 const char *ptr;
1472 uword64 paddr;
1473 int cca;
1474 if (AddressTranslation(A0,isDATA,isLOAD,&paddr,&cca,isHOST,isREAL))
1475 V0 = callback->open(callback,(char *)((int)paddr),(int)A1);
1476 else
1477 callback->printf_filtered(callback,"WARNING: Attempt to pass pointer that does not reference simulated memory\n");
1478 }
1479 break;
1480
1481 case 7: /* int read(int file,char *ptr,int len) */
1482 {
1483 const char *ptr;
1484 uword64 paddr;
1485 int cca;
1486 if (AddressTranslation(A1,isDATA,isLOAD,&paddr,&cca,isHOST,isREAL))
1487 V0 = callback->read(callback,(int)A0,(char *)((int)paddr),(int)A2);
1488 else
1489 callback->printf_filtered(callback,"WARNING: Attempt to pass pointer that does not reference simulated memory\n");
1490 }
1491 break;
1492
1493 case 8: /* int write(int file,char *ptr,int len) */
1494 {
1495 const char *ptr;
1496 uword64 paddr;
1497 int cca;
1498 if (AddressTranslation(A1,isDATA,isLOAD,&paddr,&cca,isHOST,isREAL))
1499 V0 = callback->write(callback,(int)A0,(const char *)((int)paddr),(int)A2);
1500 else
1501 callback->printf_filtered(callback,"WARNING: Attempt to pass pointer that does not reference simulated memory\n");
1502 }
1503 break;
1504
1505 case 10: /* int close(int file) */
1506 V0 = callback->close(callback,(int)A0);
1507 break;
1508
1509 case 11: /* char inbyte(void) */
1510 {
1511 char tmp;
1512 if (callback->read_stdin(callback,&tmp,sizeof(char)) != sizeof(char)) {
1513 callback->printf_filtered(callback,"WARNING: Invalid return from character read\n");
1514 V0 = -1;
1515 }
1516 else
1517 V0 = tmp;
1518 }
1519 break;
1520
1521 case 12: /* void outbyte(char chr) : write a byte to "stdout" */
1522 {
1523 char tmp = (char)(A0 & 0xFF);
1524 callback->write_stdout(callback,&tmp,sizeof(char));
1525 }
1526 break;
1527
1528 case 17: /* void _exit() */
1529 callback->printf_filtered(callback,"sim_monitor(17): _exit(int reason) to be coded\n");
1530 state |= (simSTOP | simEXIT); /* stop executing code */
1531 rcexit = (unsigned int)(A0 & 0xFFFFFFFF);
1532 break;
1533
1534 case 55: /* void get_mem_info(unsigned int *ptr) */
1535 /* in: A0 = pointer to three word memory location */
1536 /* out: [A0 + 0] = size */
1537 /* [A0 + 4] = instruction cache size */
1538 /* [A0 + 8] = data cache size */
1539 {
1540 uword64 vaddr = A0;
1541 uword64 paddr, value;
1542 int cca;
1543 int failed = 0;
1544
1545 /* NOTE: We use RAW memory writes here, but since we are not
1546 gathering statistics for the monitor calls we are simulating,
1547 it is not an issue. */
1548
1549 /* Memory size */
1550 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isREAL)) {
1551 value = (uword64)membank_size;
1552 StoreMemory(cca,AccessLength_WORD,value,paddr,vaddr,isRAW);
1553 /* We re-do the address translations, in-case the block
1554 overlaps a memory boundary: */
1555 value = 0;
1556 vaddr += (AccessLength_WORD + 1);
1557 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isREAL)) {
1558 StoreMemory(cca,AccessLength_WORD,value,paddr,vaddr,isRAW);
1559 vaddr += (AccessLength_WORD + 1);
1560 if (AddressTranslation(vaddr,isDATA,isSTORE,&paddr,&cca,isTARGET,isREAL))
1561 StoreMemory(cca,AccessLength_WORD,value,paddr,vaddr,isRAW);
1562 else
1563 failed = -1;
1564 } else
1565 failed = -1;
1566 } else
1567 failed = -1;
1568
1569 if (failed)
1570 callback->printf_filtered(callback,"WARNING: Invalid pointer passed into monitor call\n");
1571 }
1572 break;
1573
1574 case 158 : /* PMON printf */
1575 /* in: A0 = pointer to format string */
1576 /* A1 = optional argument 1 */
1577 /* A2 = optional argument 2 */
1578 /* A3 = optional argument 3 */
1579 /* out: void */
1580 {
1581 uword64 paddr;
1582 int cca;
1583 if (AddressTranslation(A0,isDATA,isLOAD,&paddr,&cca,isHOST,isREAL))
1584 callback->printf_filtered(callback,(char *)((int)paddr),(int)A1,(int)A2,(int)A2);
1585 else
1586 callback->printf_filtered(callback,"WARNING: Attempt to pass pointer that does not reference simulated memory\n");
1587 }
1588 break;
1589
1590 default:
1591 callback->printf_filtered(callback,"TODO: sim_monitor(%d) : PC = 0x%08X%08X\n",reason,WORD64HI(IPC),WORD64LO(IPC));
1592 callback->printf_filtered(callback,"(Arguments : A0 = 0x%08X%08X : A1 = 0x%08X%08X : A2 = 0x%08X%08X : A3 = 0x%08X%08X)\n",WORD64HI(A0),WORD64LO(A0),WORD64HI(A1),WORD64LO(A1),WORD64HI(A2),WORD64LO(A2),WORD64HI(A3),WORD64LO(A3));
1593 break;
1594 }
1595 return;
1596 }
1597
1598 void
1599 sim_error(fmt)
1600 char *fmt;
1601 {
1602 va_list ap;
1603 va_start(ap,fmt);
1604 callback->printf_filtered(callback,"SIM Error: ");
1605 callback->printf_filtered(callback,fmt,ap);
1606 va_end(ap);
1607 SignalException(SimulatorFault,"");
1608 return;
1609 }
1610
1611 static unsigned int
1612 power2(value)
1613 unsigned int value;
1614 {
1615 int loop,tmp;
1616
1617 /* Round *UP* to the nearest power-of-2 if not already one */
1618 if (value != (value & ~(value - 1))) {
1619 for (tmp = value, loop = 0; (tmp != 0); loop++)
1620 tmp >>= 1;
1621 value = (1 << loop);
1622 }
1623
1624 return(value);
1625 }
1626
1627 static long
1628 getnum(value)
1629 char *value;
1630 {
1631 long num;
1632 char *end;
1633
1634 num = strtol(value,&end,10);
1635 if (end == value)
1636 callback->printf_filtered(callback,"Warning: Invalid number \"%s\" ignored, using zero\n",value);
1637 else {
1638 if (*end && ((tolower(*end) == 'k') || (tolower(*end) == 'm'))) {
1639 if (tolower(*end) == 'k')
1640 num *= (1 << 10);
1641 else
1642 num *= (1 << 20);
1643 end++;
1644 }
1645 if (*end)
1646 callback->printf_filtered(callback,"Warning: Spurious characters \"%s\" at end of number ignored\n",end);
1647 }
1648
1649 return(num);
1650 }
1651
1652 /*-- trace support ----------------------------------------------------------*/
1653
1654 /* The TRACE support is provided (if required) in the memory accessing
1655 routines. Since we are also providing the architecture specific
1656 features, the architecture simulation code can also deal with
1657 notifying the TRACE world of cache flushes, etc. Similarly we do
1658 not need to provide profiling support in the simulator engine,
1659 since we can sample in the instruction fetch control loop. By
1660 defining the TRACE manifest, we add tracing as a run-time
1661 option. */
1662
1663 #if defined(TRACE)
1664 /* Tracing by default produces "din" format (as required by
1665 dineroIII). Each line of such a trace file *MUST* have a din label
1666 and address field. The rest of the line is ignored, so comments can
1667 be included if desired. The first field is the label which must be
1668 one of the following values:
1669
1670 0 read data
1671 1 write data
1672 2 instruction fetch
1673 3 escape record (treated as unknown access type)
1674 4 escape record (causes cache flush)
1675
1676 The address field is a 32bit (lower-case) hexadecimal address
1677 value. The address should *NOT* be preceded by "0x".
1678
1679 The size of the memory transfer is not important when dealing with
1680 cache lines (as long as no more than a cache line can be
1681 transferred in a single operation :-), however more information
1682 could be given following the dineroIII requirement to allow more
1683 complete memory and cache simulators to provide better
1684 results. i.e. the University of Pisa has a cache simulator that can
1685 also take bus size and speed as (variable) inputs to calculate
1686 complete system performance (a much more useful ability when trying
1687 to construct an end product, rather than a processor). They
1688 currently have an ARM version of their tool called ChARM. */
1689
1690 static
1691 void dotrace(tracefh,type,address,width,comment)
1692 FILE *tracefh;
1693 int type;
1694 unsigned int address;
1695 int width;
1696 char *comment;
1697 {
1698 if (state & simTRACE) {
1699 va_list ap;
1700 fprintf(tracefh,"%d %08x ; width %d ; ",type,address,width);
1701 va_start(ap,comment);
1702 fprintf(tracefh,comment,ap);
1703 va_end(ap);
1704 fprintf(tracefh,"\n");
1705 }
1706 /* NOTE: Since the "din" format will only accept 32bit addresses, and
1707 we may be generating 64bit ones, we should put the hi-32bits of the
1708 address into the comment field. */
1709
1710 /* TODO: Provide a buffer for the trace lines. We can then avoid
1711 performing writes until the buffer is filled, or the file is
1712 being closed. */
1713
1714 /* NOTE: We could consider adding a comment field to the "din" file
1715 produced using type 3 markers (unknown access). This would then
1716 allow information about the program that the "din" is for, and
1717 the MIPs world that was being simulated, to be placed into the
1718 trace file. */
1719
1720 return;
1721 }
1722 #endif /* TRACE */
1723
1724 /*---------------------------------------------------------------------------*/
1725 /*-- simulator engine -------------------------------------------------------*/
1726 /*---------------------------------------------------------------------------*/
1727
1728 static void
1729 ColdReset()
1730 {
1731 /* RESET: Fixed PC address: */
1732 PC = (((uword64)0xFFFFFFFF<<32) | 0xBFC00000);
1733 /* The reset vector address is in the unmapped, uncached memory space. */
1734
1735 SR &= ~(status_SR | status_TS | status_RP);
1736 SR |= (status_ERL | status_BEV);
1737 /* VR4300 starts in Big-Endian mode */
1738 CONFIG &= ~(config_EP_mask << config_EP_shift);
1739 CONFIG |= ((config_EP_D << config_EP_shift) | config_BE);
1740 /* TODO: The VR4300 CONFIG register is not modelled fully at the moment */
1741
1742 #if defined(HASFPU) && (GPRLEN == (64))
1743 /* Cheat and allow access to the complete register set immediately: */
1744 SR |= status_FR; /* 64bit registers */
1745 #endif /* HASFPU and 64bit FP registers */
1746
1747 /* Ensure that any instructions with pending register updates are
1748 cleared: */
1749 {
1750 int loop;
1751 for (loop = 0; (loop < PSLOTS); loop++)
1752 pending_slot_reg[loop] = (LAST_EMBED_REGNUM + 1);
1753 pending_in = pending_out = pending_total = 0;
1754 }
1755
1756 #if defined(HASFPU)
1757 /* Initialise the FPU registers to the unknown state */
1758 {
1759 int rn;
1760 for (rn = 0; (rn < 32); rn++)
1761 fpr_state[rn] = fmt_uninterpreted;
1762 }
1763 #endif /* HASFPU */
1764
1765 return;
1766 }
1767
1768 /* Description from page A-22 of the "MIPS IV Instruction Set" manual (revision 3.1) */
1769 /* Translate a virtual address to a physical address and cache
1770 coherence algorithm describing the mechanism used to resolve the
1771 memory reference. Given the virtual address vAddr, and whether the
1772 reference is to Instructions ot Data (IorD), find the corresponding
1773 physical address (pAddr) and the cache coherence algorithm (CCA)
1774 used to resolve the reference. If the virtual address is in one of
1775 the unmapped address spaces the physical address and the CCA are
1776 determined directly by the virtual address. If the virtual address
1777 is in one of the mapped address spaces then the TLB is used to
1778 determine the physical address and access type; if the required
1779 translation is not present in the TLB or the desired access is not
1780 permitted the function fails and an exception is taken.
1781
1782 NOTE: This function is extended to return an exception state. This,
1783 along with the exception generation is used to notify whether a
1784 valid address translation occured */
1785
1786 static int
1787 AddressTranslation(vAddr,IorD,LorS,pAddr,CCA,host,raw)
1788 uword64 vAddr;
1789 int IorD;
1790 int LorS;
1791 uword64 *pAddr;
1792 int *CCA;
1793 int host;
1794 int raw;
1795 {
1796 int res = -1; /* TRUE : Assume good return */
1797
1798 #ifdef DEBUG
1799 callback->printf_filtered(callback,"AddressTranslation(0x%08X%08X,%s,%s,...);\n",WORD64HI(vAddr),WORD64LO(vAddr),(IorD ? "isDATA" : "isINSTRUCTION"),(LorS ? "iSTORE" : "isLOAD"));
1800 #endif
1801
1802 /* Check that the address is valid for this memory model */
1803
1804 /* For a simple (flat) memory model, we simply pass virtual
1805 addressess through (mostly) unchanged. */
1806 vAddr &= 0xFFFFFFFF;
1807
1808 /* Treat the kernel memory spaces identically for the moment: */
1809 if ((membank_base == K1BASE) && (vAddr >= K0BASE) && (vAddr < (K0BASE + K0SIZE)))
1810 vAddr += (K1BASE - K0BASE);
1811
1812 /* Also assume that the K1BASE memory wraps. This is required to
1813 allow the PMON run-time __sizemem() routine to function (without
1814 having to provide exception simulation). NOTE: A kludge to work
1815 around the fact that the monitor memory is currently held in the
1816 K1BASE space. */
1817 if (((vAddr < monitor_base) || (vAddr >= (monitor_base + monitor_size))) && (vAddr >= K1BASE && vAddr < (K1BASE + K1SIZE)))
1818 vAddr = (K1BASE | (vAddr & (membank_size - 1)));
1819
1820 *pAddr = vAddr; /* default for isTARGET */
1821 *CCA = Uncached; /* not used for isHOST */
1822
1823 /* NOTE: This is a duplicate of the code that appears in the
1824 LoadMemory and StoreMemory functions. They should be merged into
1825 a single function (that can be in-lined if required). */
1826 if ((vAddr >= membank_base) && (vAddr < (membank_base + membank_size))) {
1827 if (host)
1828 *pAddr = (int)&membank[((unsigned int)(vAddr - membank_base) & (membank_size - 1))];
1829 } else if ((vAddr >= monitor_base) && (vAddr < (monitor_base + monitor_size))) {
1830 if (host)
1831 *pAddr = (int)&monitor[((unsigned int)(vAddr - monitor_base) & (monitor_size - 1))];
1832 } else {
1833 #if 1 /* def DEBUG */
1834 callback->printf_filtered(callback,"Failed: AddressTranslation(0x%08X%08X,%s,%s,...) IPC = 0x%08X%08X\n",WORD64HI(vAddr),WORD64LO(vAddr),(IorD ? "isDATA" : "isINSTRUCTION"),(LorS ? "isSTORE" : "isLOAD"),WORD64HI(IPC),WORD64LO(IPC));
1835 #endif /* DEBUG */
1836 res = 0; /* AddressTranslation has failed */
1837 *pAddr = -1;
1838 if (!raw) /* only generate exceptions on real memory transfers */
1839 SignalException((LorS == isSTORE) ? AddressStore : AddressLoad);
1840 else
1841 callback->printf_filtered(callback,"AddressTranslation for %s %s from 0x%08X%08X failed\n",(IorD ? "data" : "instruction"),(LorS ? "store" : "load"),WORD64HI(vAddr),WORD64LO(vAddr));
1842 }
1843
1844 return(res);
1845 }
1846
1847 /* Description from page A-23 of the "MIPS IV Instruction Set" manual (revision 3.1) */
1848 /* Prefetch data from memory. Prefetch is an advisory instruction for
1849 which an implementation specific action is taken. The action taken
1850 may increase performance, but must not change the meaning of the
1851 program, or alter architecturally-visible state. */
1852 static void
1853 Prefetch(CCA,pAddr,vAddr,DATA,hint)
1854 int CCA;
1855 uword64 pAddr;
1856 uword64 vAddr;
1857 int DATA;
1858 int hint;
1859 {
1860 #ifdef DEBUG
1861 callback->printf_filtered(callback,"Prefetch(%d,0x%08X%08X,0x%08X%08X,%d,%d);\n",CCA,WORD64HI(pAddr),WORD64LO(pAddr),WORD64HI(vAddr),WORD64LO(vAddr),DATA,hint);
1862 #endif /* DEBUG */
1863
1864 /* For our simple memory model we do nothing */
1865 return;
1866 }
1867
1868 /* Description from page A-22 of the "MIPS IV Instruction Set" manual (revision 3.1) */
1869 /* Load a value from memory. Use the cache and main memory as
1870 specified in the Cache Coherence Algorithm (CCA) and the sort of
1871 access (IorD) to find the contents of AccessLength memory bytes
1872 starting at physical location pAddr. The data is returned in the
1873 fixed width naturally-aligned memory element (MemElem). The
1874 low-order two (or three) bits of the address and the AccessLength
1875 indicate which of the bytes within MemElem needs to be given to the
1876 processor. If the memory access type of the reference is uncached
1877 then only the referenced bytes are read from memory and valid
1878 within the memory element. If the access type is cached, and the
1879 data is not present in cache, an implementation specific size and
1880 alignment block of memory is read and loaded into the cache to
1881 satisfy a load reference. At a minimum, the block is the entire
1882 memory element. */
1883 static uword64
1884 LoadMemory(CCA,AccessLength,pAddr,vAddr,IorD,raw)
1885 int CCA;
1886 int AccessLength;
1887 uword64 pAddr;
1888 uword64 vAddr;
1889 int IorD;
1890 int raw;
1891 {
1892 uword64 value;
1893
1894 #ifdef DEBUG
1895 if (membank == NULL)
1896 callback->printf_filtered(callback,"DBG: LoadMemory(%d,%d,0x%08X%08X,0x%08X%08X,%s,%s)\n",CCA,AccessLength,WORD64HI(pAddr),WORD64LO(pAddr),WORD64HI(vAddr),WORD64LO(vAddr),(IorD ? "isDATA" : "isINSTRUCTION"),(raw ? "isRAW" : "isREAL"));
1897 #endif /* DEBUG */
1898
1899 #if defined(WARN_MEM)
1900 if (CCA != uncached)
1901 callback->printf_filtered(callback,"SIM Warning: LoadMemory CCA (%d) is not uncached (currently all accesses treated as cached)\n",CCA);
1902
1903 if (((pAddr & LOADDRMASK) + AccessLength) > LOADDRMASK) {
1904 /* In reality this should be a Bus Error */
1905 sim_error("AccessLength of %d would extend over 64bit aligned boundary for physical address 0x%08X%08X\n",AccessLength,WORD64HI(pAddr),WORD64LO(pAddr));
1906 }
1907 #endif /* WARN_MEM */
1908
1909 /* Decide which physical memory locations are being dealt with. At
1910 this point we should be able to split the pAddr bits into the
1911 relevant address map being simulated. If the "raw" variable is
1912 set, the memory read being performed should *NOT* update any I/O
1913 state or affect the CPU state. This also includes avoiding
1914 affecting statistics gathering. */
1915
1916 /* If instruction fetch then we need to check that the two lo-order
1917 bits are zero, otherwise raise a InstructionFetch exception: */
1918 if ((IorD == isINSTRUCTION) && ((pAddr & 0x3) != 0))
1919 SignalException(InstructionFetch);
1920 else {
1921 unsigned int index;
1922 unsigned char *mem = NULL;
1923
1924 #if defined(TRACE)
1925 if (!raw)
1926 dotrace(tracefh,((IorD == isDATA) ? 0 : 2),(unsigned int)(pAddr&0xFFFFFFFF),(AccessLength + 1),"load%s",((IorD == isDATA) ? "" : " instruction"));
1927 #endif /* TRACE */
1928
1929 /* NOTE: Quicker methods of decoding the address space can be used
1930 when a real memory map is being simulated (i.e. using hi-order
1931 address bits to select device). */
1932 if ((pAddr >= membank_base) && (pAddr < (membank_base + membank_size))) {
1933 index = ((unsigned int)(pAddr - membank_base) & (membank_size - 1));
1934 mem = membank;
1935 } else if ((pAddr >= monitor_base) && (pAddr < (monitor_base + monitor_size))) {
1936 index = ((unsigned int)(pAddr - monitor_base) & (monitor_size - 1));
1937 mem = monitor;
1938 }
1939 if (mem == NULL)
1940 sim_error("Simulator memory not found for physical address 0x%08X%08X\n",WORD64HI(pAddr),WORD64LO(pAddr));
1941 else {
1942 /* If we obtained the endianness of the host, and it is the same
1943 as the target memory system we can optimise the memory
1944 accesses. However, without that information we must perform
1945 slow transfer, and hope that the compiler optimisation will
1946 merge successive loads. */
1947 value = 0; /* no data loaded yet */
1948
1949 /* In reality we should always be loading a doubleword value (or
1950 word value in 32bit memory worlds). The external code then
1951 extracts the required bytes. However, to keep performance
1952 high we only load the required bytes into the relevant
1953 slots. */
1954 if (BigEndianMem)
1955 switch (AccessLength) { /* big-endian memory */
1956 case AccessLength_DOUBLEWORD :
1957 value |= ((uword64)mem[index++] << 56);
1958 case AccessLength_SEPTIBYTE :
1959 value |= ((uword64)mem[index++] << 48);
1960 case AccessLength_SEXTIBYTE :
1961 value |= ((uword64)mem[index++] << 40);
1962 case AccessLength_QUINTIBYTE :
1963 value |= ((uword64)mem[index++] << 32);
1964 case AccessLength_WORD :
1965 value |= ((unsigned int)mem[index++] << 24);
1966 case AccessLength_TRIPLEBYTE :
1967 value |= ((unsigned int)mem[index++] << 16);
1968 case AccessLength_HALFWORD :
1969 value |= ((unsigned int)mem[index++] << 8);
1970 case AccessLength_BYTE :
1971 value |= mem[index];
1972 break;
1973 }
1974 else {
1975 index += (AccessLength + 1);
1976 switch (AccessLength) { /* little-endian memory */
1977 case AccessLength_DOUBLEWORD :
1978 value |= ((uword64)mem[--index] << 56);
1979 case AccessLength_SEPTIBYTE :
1980 value |= ((uword64)mem[--index] << 48);
1981 case AccessLength_SEXTIBYTE :
1982 value |= ((uword64)mem[--index] << 40);
1983 case AccessLength_QUINTIBYTE :
1984 value |= ((uword64)mem[--index] << 32);
1985 case AccessLength_WORD :
1986 value |= ((uword64)mem[--index] << 24);
1987 case AccessLength_TRIPLEBYTE :
1988 value |= ((uword64)mem[--index] << 16);
1989 case AccessLength_HALFWORD :
1990 value |= ((uword64)mem[--index] << 8);
1991 case AccessLength_BYTE :
1992 value |= ((uword64)mem[--index] << 0);
1993 break;
1994 }
1995 }
1996
1997 #ifdef DEBUG
1998 printf("DBG: LoadMemory() : (offset %d) : value = 0x%08X%08X\n",(int)(pAddr & LOADDRMASK),WORD64HI(value),WORD64LO(value));
1999 #endif /* DEBUG */
2000
2001 /* TODO: We could try and avoid the shifts when dealing with raw
2002 memory accesses. This would mean updating the LoadMemory and
2003 StoreMemory routines to avoid shifting the data before
2004 returning or using it. */
2005 if (!raw) { /* do nothing for raw accessess */
2006 if (BigEndianMem)
2007 value <<= (((7 - (pAddr & LOADDRMASK)) - AccessLength) * 8);
2008 else /* little-endian only needs to be shifted up to the correct byte offset */
2009 value <<= ((pAddr & LOADDRMASK) * 8);
2010 }
2011
2012 #ifdef DEBUG
2013 printf("DBG: LoadMemory() : shifted value = 0x%08X%08X\n",WORD64HI(value),WORD64LO(value));
2014 #endif /* DEBUG */
2015 }
2016 }
2017
2018 return(value);
2019 }
2020
2021 /* Description from page A-23 of the "MIPS IV Instruction Set" manual (revision 3.1) */
2022 /* Store a value to memory. The specified data is stored into the
2023 physical location pAddr using the memory hierarchy (data caches and
2024 main memory) as specified by the Cache Coherence Algorithm
2025 (CCA). The MemElem contains the data for an aligned, fixed-width
2026 memory element (word for 32-bit processors, doubleword for 64-bit
2027 processors), though only the bytes that will actually be stored to
2028 memory need to be valid. The low-order two (or three) bits of pAddr
2029 and the AccessLength field indicates which of the bytes within the
2030 MemElem data should actually be stored; only these bytes in memory
2031 will be changed. */
2032 static void
2033 StoreMemory(CCA,AccessLength,MemElem,pAddr,vAddr,raw)
2034 int CCA;
2035 int AccessLength;
2036 uword64 MemElem;
2037 uword64 pAddr;
2038 uword64 vAddr;
2039 int raw;
2040 {
2041 #ifdef DEBUG
2042 callback->printf_filtered(callback,"DBG: StoreMemory(%d,%d,0x%08X%08X,0x%08X%08X,0x%08X%08X,%s)\n",CCA,AccessLength,WORD64HI(MemElem),WORD64LO(MemElem),WORD64HI(pAddr),WORD64LO(pAddr),WORD64HI(vAddr),WORD64LO(vAddr),(raw ? "isRAW" : "isREAL"));
2043 #endif /* DEBUG */
2044
2045 #if defined(WARN_MEM)
2046 if (CCA != uncached)
2047 callback->printf_filtered(callback,"SIM Warning: StoreMemory CCA (%d) is not uncached (currently all accesses treated as cached)\n",CCA);
2048
2049 if (((pAddr & LOADDRMASK) + AccessLength) > LOADDRMASK)
2050 sim_error("AccessLength of %d would extend over 64bit aligned boundary for physical address 0x%08X%08X\n",AccessLength,WORD64HI(pAddr),WORD64LO(pAddr));
2051 #endif /* WARN_MEM */
2052
2053 #if defined(TRACE)
2054 if (!raw)
2055 dotrace(tracefh,1,(unsigned int)(pAddr&0xFFFFFFFF),(AccessLength + 1),"store");
2056 #endif /* TRACE */
2057
2058 /* See the comments in the LoadMemory routine about optimising
2059 memory accesses. Also if we wanted to make the simulator smaller,
2060 we could merge a lot of this code with the LoadMemory
2061 routine. However, this would slow the simulator down with
2062 run-time conditionals. */
2063 {
2064 unsigned int index;
2065 unsigned char *mem = NULL;
2066
2067 if ((pAddr >= membank_base) && (pAddr < (membank_base + membank_size))) {
2068 index = ((unsigned int)(pAddr - membank_base) & (membank_size - 1));
2069 mem = membank;
2070 } else if ((pAddr >= monitor_base) && (pAddr < (monitor_base + monitor_size))) {
2071 index = ((unsigned int)(pAddr - monitor_base) & (monitor_size - 1));
2072 mem = monitor;
2073 }
2074
2075 if (mem == NULL)
2076 sim_error("Simulator memory not found for physical address 0x%08X%08X\n",WORD64HI(pAddr),WORD64LO(pAddr));
2077 else {
2078 int shift = 0;
2079
2080 #ifdef DEBUG
2081 printf("DBG: StoreMemory: offset = %d MemElem = 0x%08X%08X\n",(unsigned int)(pAddr & LOADDRMASK),WORD64HI(MemElem),WORD64LO(MemElem));
2082 #endif /* DEBUG */
2083
2084 if (BigEndianMem) {
2085 if (raw)
2086 shift = ((7 - AccessLength) * 8);
2087 else /* real memory access */
2088 shift = ((pAddr & LOADDRMASK) * 8);
2089 MemElem <<= shift;
2090 } else {
2091 /* no need to shift raw little-endian data */
2092 if (!raw)
2093 MemElem >>= ((pAddr & LOADDRMASK) * 8);
2094 }
2095
2096 #ifdef DEBUG
2097 printf("DBG: StoreMemory: shift = %d MemElem = 0x%08X%08X\n",shift,WORD64HI(MemElem),WORD64LO(MemElem));
2098 #endif /* DEBUG */
2099
2100 if (BigEndianMem) {
2101 switch (AccessLength) { /* big-endian memory */
2102 case AccessLength_DOUBLEWORD :
2103 mem[index++] = (unsigned char)(MemElem >> 56);
2104 MemElem <<= 8;
2105 case AccessLength_SEPTIBYTE :
2106 mem[index++] = (unsigned char)(MemElem >> 56);
2107 MemElem <<= 8;
2108 case AccessLength_SEXTIBYTE :
2109 mem[index++] = (unsigned char)(MemElem >> 56);
2110 MemElem <<= 8;
2111 case AccessLength_QUINTIBYTE :
2112 mem[index++] = (unsigned char)(MemElem >> 56);
2113 MemElem <<= 8;
2114 case AccessLength_WORD :
2115 mem[index++] = (unsigned char)(MemElem >> 56);
2116 MemElem <<= 8;
2117 case AccessLength_TRIPLEBYTE :
2118 mem[index++] = (unsigned char)(MemElem >> 56);
2119 MemElem <<= 8;
2120 case AccessLength_HALFWORD :
2121 mem[index++] = (unsigned char)(MemElem >> 56);
2122 MemElem <<= 8;
2123 case AccessLength_BYTE :
2124 mem[index++] = (unsigned char)(MemElem >> 56);
2125 break;
2126 }
2127 } else {
2128 index += (AccessLength + 1);
2129 switch (AccessLength) { /* little-endian memory */
2130 case AccessLength_DOUBLEWORD :
2131 mem[--index] = (unsigned char)(MemElem >> 56);
2132 case AccessLength_SEPTIBYTE :
2133 mem[--index] = (unsigned char)(MemElem >> 48);
2134 case AccessLength_SEXTIBYTE :
2135 mem[--index] = (unsigned char)(MemElem >> 40);
2136 case AccessLength_QUINTIBYTE :
2137 mem[--index] = (unsigned char)(MemElem >> 32);
2138 case AccessLength_WORD :
2139 mem[--index] = (unsigned char)(MemElem >> 24);
2140 case AccessLength_TRIPLEBYTE :
2141 mem[--index] = (unsigned char)(MemElem >> 16);
2142 case AccessLength_HALFWORD :
2143 mem[--index] = (unsigned char)(MemElem >> 8);
2144 case AccessLength_BYTE :
2145 mem[--index] = (unsigned char)(MemElem >> 0);
2146 break;
2147 }
2148 }
2149 }
2150 }
2151
2152 return;
2153 }
2154
2155 /* Description from page A-26 of the "MIPS IV Instruction Set" manual (revision 3.1) */
2156 /* Order loads and stores to synchronise shared memory. Perform the
2157 action necessary to make the effects of groups of synchronizable
2158 loads and stores indicated by stype occur in the same order for all
2159 processors. */
2160 static void
2161 SyncOperation(stype)
2162 int stype;
2163 {
2164 #ifdef DEBUG
2165 callback->printf_filtered(callback,"SyncOperation(%d) : TODO\n",stype);
2166 #endif /* DEBUG */
2167 return;
2168 }
2169
2170 /* Description from page A-26 of the "MIPS IV Instruction Set" manual (revision 3.1) */
2171 /* Signal an exception condition. This will result in an exception
2172 that aborts the instruction. The instruction operation pseudocode
2173 will never see a return from this function call. */
2174 static void
2175 SignalException(exception)
2176 int exception;
2177 {
2178 /* Ensure that any active atomic read/modify/write operation will fail: */
2179 LLBIT = 0;
2180
2181 switch (exception) {
2182 /* TODO: For testing purposes I have been ignoring TRAPs. In
2183 reality we should either simulate them, or allow the user to
2184 ignore them at run-time. */
2185 case Trap :
2186 callback->printf_filtered(callback,"Ignoring instruction TRAP (PC 0x%08X%08X)\n",WORD64HI(IPC),WORD64LO(IPC));
2187 break;
2188
2189 case ReservedInstruction :
2190 {
2191 va_list ap;
2192 unsigned int instruction;
2193 va_start(ap,exception);
2194 instruction = va_arg(ap,unsigned int);
2195 va_end(ap);
2196 /* Provide simple monitor support using ReservedInstruction
2197 exceptions. The following code simulates the fixed vector
2198 entry points into the IDT monitor by causing a simulator
2199 trap, performing the monitor operation, and returning to
2200 the address held in the $ra register (standard PCS return
2201 address). This means we only need to pre-load the vector
2202 space with suitable instruction values. For systems were
2203 actual trap instructions are used, we would not need to
2204 perform this magic. */
2205 if ((instruction & ~RSVD_INSTRUCTION_AMASK) == RSVD_INSTRUCTION) {
2206 sim_monitor(instruction & RSVD_INSTRUCTION_AMASK);
2207 PC = RA; /* simulate the return from the vector entry */
2208 /* NOTE: This assumes that a branch-and-link style
2209 instruction was used to enter the vector (which is the
2210 case with the current IDT monitor). */
2211 break; /* out of the switch statement */
2212 } /* else fall through to normal exception processing */
2213 callback->printf_filtered(callback,"DBG: ReservedInstruction 0x%08X at IPC = 0x%08X%08X\n",instruction,WORD64HI(IPC),WORD64LO(IPC));
2214 }
2215
2216 default:
2217 #if 1 /* def DEBUG */
2218 callback->printf_filtered(callback,"DBG: SignalException(%d) IPC = 0x%08X%08X\n",exception,WORD64HI(IPC),WORD64LO(IPC));
2219 #endif /* DEBUG */
2220 /* Store exception code into current exception id variable (used
2221 by exit code): */
2222
2223 /* TODO: If not simulating exceptions then stop the simulator
2224 execution. At the moment we always stop the simulation. */
2225 state |= (simSTOP | simEXCEPTION);
2226 CAUSE = (exception << 2);
2227 if (state & simDELAYSLOT) {
2228 CAUSE |= cause_BD;
2229 EPC = (IPC - 4); /* reference the branch instruction */
2230 } else
2231 EPC = IPC;
2232 /* The following is so that the simulator will continue from the
2233 exception address on breakpoint operations. */
2234 PC = EPC;
2235 break;
2236
2237 case SimulatorFault:
2238 {
2239 va_list ap;
2240 char *msg;
2241 va_start(ap,exception);
2242 msg = va_arg(ap,char *);
2243 fprintf(stderr,"FATAL: Simulator error \"%s\"\n",msg);
2244 va_end(ap);
2245 }
2246 exit(1);
2247 }
2248
2249 return;
2250 }
2251
2252 #if defined(WARN_RESULT)
2253 /* Description from page A-26 of the "MIPS IV Instruction Set" manual (revision 3.1) */
2254 /* This function indicates that the result of the operation is
2255 undefined. However, this should not affect the instruction
2256 stream. All that is meant to happen is that the destination
2257 register is set to an undefined result. To keep the simulator
2258 simple, we just don't bother updating the destination register, so
2259 the overall result will be undefined. If desired we can stop the
2260 simulator by raising a pseudo-exception. */
2261 static void
2262 UndefinedResult()
2263 {
2264 callback->printf_filtered(callback,"UndefinedResult: IPC = 0x%08X%08X\n",WORD64HI(IPC),WORD64LO(IPC));
2265 #if 0 /* Disabled for the moment, since it actually happens a lot at the moment. */
2266 state |= simSTOP;
2267 #endif
2268 return;
2269 }
2270 #endif /* WARN_RESULT */
2271
2272 static void
2273 CacheOp(op,pAddr,vAddr,instruction)
2274 int op;
2275 uword64 pAddr;
2276 uword64 vAddr;
2277 unsigned int instruction;
2278 {
2279 static int icache_warning = 0;
2280 static int dcache_warning = 0;
2281
2282 /* If CP0 is not useable (User or Supervisor mode) and the CP0
2283 enable bit in the Status Register is clear - a coprocessor
2284 unusable exception is taken. */
2285 #if 0
2286 callback->printf_filtered(callback,"TODO: Cache availability checking (PC = 0x%08X%08X)\n",WORD64HI(IPC),WORD64LO(IPC));
2287 #endif
2288
2289 switch (op & 0x3) {
2290 case 0: /* instruction cache */
2291 switch (op >> 2) {
2292 case 0: /* Index Invalidate */
2293 case 1: /* Index Load Tag */
2294 case 2: /* Index Store Tag */
2295 case 4: /* Hit Invalidate */
2296 case 5: /* Fill */
2297 case 6: /* Hit Writeback */
2298 if (!icache_warning)
2299 {
2300 callback->printf_filtered(callback,"SIM Warning: Instruction CACHE operation %d to be coded\n",(op >> 2));
2301 icache_warning = 1;
2302 }
2303 break;
2304
2305 default:
2306 SignalException(ReservedInstruction,instruction);
2307 break;
2308 }
2309 break;
2310
2311 case 1: /* data cache */
2312 switch (op >> 2) {
2313 case 0: /* Index Writeback Invalidate */
2314 case 1: /* Index Load Tag */
2315 case 2: /* Index Store Tag */
2316 case 3: /* Create Dirty */
2317 case 4: /* Hit Invalidate */
2318 case 5: /* Hit Writeback Invalidate */
2319 case 6: /* Hit Writeback */
2320 if (!dcache_warning)
2321 {
2322 callback->printf_filtered(callback,"SIM Warning: Data CACHE operation %d to be coded\n",(op >> 2));
2323 dcache_warning = 1;
2324 }
2325 break;
2326
2327 default:
2328 SignalException(ReservedInstruction,instruction);
2329 break;
2330 }
2331 break;
2332
2333 default: /* unrecognised cache ID */
2334 SignalException(ReservedInstruction,instruction);
2335 break;
2336 }
2337
2338 return;
2339 }
2340
2341 /*-- FPU support routines ---------------------------------------------------*/
2342
2343 #if defined(HASFPU) /* Only needed when building FPU aware simulators */
2344
2345 #if 1
2346 #define SizeFGR() (GPRLEN)
2347 #else
2348 /* They depend on the CPU being simulated */
2349 #define SizeFGR() ((PROCESSOR_64BIT && ((SR & status_FR) == 1)) ? 64 : 32)
2350 #endif
2351
2352 /* Numbers are held in normalized form. The SINGLE and DOUBLE binary
2353 formats conform to ANSI/IEEE Std 754-1985. */
2354 /* SINGLE precision floating:
2355 * seeeeeeeefffffffffffffffffffffff
2356 * s = 1bit = sign
2357 * e = 8bits = exponent
2358 * f = 23bits = fraction
2359 */
2360 /* SINGLE precision fixed:
2361 * siiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
2362 * s = 1bit = sign
2363 * i = 31bits = integer
2364 */
2365 /* DOUBLE precision floating:
2366 * seeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffff
2367 * s = 1bit = sign
2368 * e = 11bits = exponent
2369 * f = 52bits = fraction
2370 */
2371 /* DOUBLE precision fixed:
2372 * siiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
2373 * s = 1bit = sign
2374 * i = 63bits = integer
2375 */
2376
2377 /* Extract sign-bit: */
2378 #define FP_S_s(v) (((v) & ((unsigned)1 << 31)) ? 1 : 0)
2379 #define FP_D_s(v) (((v) & ((uword64)1 << 63)) ? 1 : 0)
2380 /* Extract biased exponent: */
2381 #define FP_S_be(v) (((v) >> 23) & 0xFF)
2382 #define FP_D_be(v) (((v) >> 52) & 0x7FF)
2383 /* Extract unbiased Exponent: */
2384 #define FP_S_e(v) (FP_S_be(v) - 0x7F)
2385 #define FP_D_e(v) (FP_D_be(v) - 0x3FF)
2386 /* Extract complete fraction field: */
2387 #define FP_S_f(v) ((v) & ~((unsigned)0x1FF << 23))
2388 #define FP_D_f(v) ((v) & ~((uword64)0xFFF << 52))
2389 /* Extract numbered fraction bit: */
2390 #define FP_S_fb(b,v) (((v) & (1 << (23 - (b)))) ? 1 : 0)
2391 #define FP_D_fb(b,v) (((v) & (1 << (52 - (b)))) ? 1 : 0)
2392
2393 /* Explicit QNaN values used when value required: */
2394 #define FPQNaN_SINGLE (0x7FBFFFFF)
2395 #define FPQNaN_WORD (0x7FFFFFFF)
2396 #define FPQNaN_DOUBLE (((uword64)0x7FF7FFFF << 32) | 0xFFFFFFFF)
2397 #define FPQNaN_LONG (((uword64)0x7FFFFFFF << 32) | 0xFFFFFFFF)
2398
2399 /* Explicit Infinity values used when required: */
2400 #define FPINF_SINGLE (0x7F800000)
2401 #define FPINF_DOUBLE (((uword64)0x7FF00000 << 32) | 0x00000000)
2402
2403 #if 1 /* def DEBUG */
2404 #define RMMODE(v) (((v) == FP_RM_NEAREST) ? "Round" : (((v) == FP_RM_TOZERO) ? "Trunc" : (((v) == FP_RM_TOPINF) ? "Ceil" : "Floor")))
2405 #define DOFMT(v) (((v) == fmt_single) ? "single" : (((v) == fmt_double) ? "double" : (((v) == fmt_word) ? "word" : (((v) == fmt_long) ? "long" : (((v) == fmt_unknown) ? "<unknown>" : (((v) == fmt_uninterpreted) ? "<uninterpreted>" : "<format error>"))))))
2406 #endif /* DEBUG */
2407
2408 static uword64
2409 ValueFPR(fpr,fmt)
2410 int fpr;
2411 FP_formats fmt;
2412 {
2413 uword64 value;
2414 int err = 0;
2415
2416 /* Treat unused register values, as fixed-point 64bit values: */
2417 if ((fmt == fmt_uninterpreted) || (fmt == fmt_unknown))
2418 #if 1
2419 /* If request to read data as "uninterpreted", then use the current
2420 encoding: */
2421 fmt = fpr_state[fpr];
2422 #else
2423 fmt = fmt_long;
2424 #endif
2425
2426 /* For values not yet accessed, set to the desired format: */
2427 if (fpr_state[fpr] == fmt_uninterpreted) {
2428 fpr_state[fpr] = fmt;
2429 #ifdef DEBUG
2430 printf("DBG: Register %d was fmt_uninterpreted. Now %s\n",fpr,DOFMT(fmt));
2431 #endif /* DEBUG */
2432 }
2433 if (fmt != fpr_state[fpr]) {
2434 callback->printf_filtered(callback,"Warning: FPR %d (format %s) being accessed with format %s - setting to unknown (PC = 0x%08X%08X)\n",fpr,DOFMT(fpr_state[fpr]),DOFMT(fmt),WORD64HI(IPC),WORD64LO(IPC));
2435 fpr_state[fpr] = fmt_unknown;
2436 }
2437
2438 if (fpr_state[fpr] == fmt_unknown) {
2439 /* Set QNaN value: */
2440 switch (fmt) {
2441 case fmt_single:
2442 value = FPQNaN_SINGLE;
2443 break;
2444
2445 case fmt_double:
2446 value = FPQNaN_DOUBLE;
2447 break;
2448
2449 case fmt_word:
2450 value = FPQNaN_WORD;
2451 break;
2452
2453 case fmt_long:
2454 value = FPQNaN_LONG;
2455 break;
2456
2457 default:
2458 err = -1;
2459 break;
2460 }
2461 } else if (SizeFGR() == 64) {
2462 switch (fmt) {
2463 case fmt_single:
2464 case fmt_word:
2465 value = (FGR[fpr] & 0xFFFFFFFF);
2466 break;
2467
2468 case fmt_uninterpreted:
2469 case fmt_double:
2470 case fmt_long:
2471 value = FGR[fpr];
2472 break;
2473
2474 default :
2475 err = -1;
2476 break;
2477 }
2478 } else if ((fpr & 1) == 0) { /* even registers only */
2479 switch (fmt) {
2480 case fmt_single:
2481 case fmt_word:
2482 value = (FGR[fpr] & 0xFFFFFFFF);
2483 break;
2484
2485 case fmt_uninterpreted:
2486 case fmt_double:
2487 case fmt_long:
2488 value = ((FGR[fpr+1] << 32) | (FGR[fpr] & 0xFFFFFFFF));
2489 break;
2490
2491 default :
2492 err = -1;
2493 break;
2494 }
2495 }
2496
2497 if (err)
2498 SignalException(SimulatorFault,"Unrecognised FP format in ValueFPR()");
2499
2500 #ifdef DEBUG
2501 printf("DBG: ValueFPR: fpr = %d, fmt = %s, value = 0x%08X%08X : PC = 0x%08X%08X : SizeFGR() = %d\n",fpr,DOFMT(fmt),WORD64HI(value),WORD64LO(value),WORD64HI(IPC),WORD64LO(IPC),SizeFGR());
2502 #endif /* DEBUG */
2503
2504 return(value);
2505 }
2506
2507 static void
2508 StoreFPR(fpr,fmt,value)
2509 int fpr;
2510 FP_formats fmt;
2511 uword64 value;
2512 {
2513 int err = 0;
2514
2515 #ifdef DEBUG
2516 printf("DBG: StoreFPR: fpr = %d, fmt = %s, value = 0x%08X%08X : PC = 0x%08X%08X : SizeFGR() = %d\n",fpr,DOFMT(fmt),WORD64HI(value),WORD64LO(value),WORD64HI(IPC),WORD64LO(IPC),SizeFGR());
2517 #endif /* DEBUG */
2518
2519 if (SizeFGR() == 64) {
2520 switch (fmt) {
2521 case fmt_single :
2522 case fmt_word :
2523 FGR[fpr] = (((uword64)0xDEADC0DE << 32) | (value & 0xFFFFFFFF));
2524 fpr_state[fpr] = fmt;
2525 break;
2526
2527 case fmt_uninterpreted:
2528 case fmt_double :
2529 case fmt_long :
2530 FGR[fpr] = value;
2531 fpr_state[fpr] = fmt;
2532 break;
2533
2534 default :
2535 fpr_state[fpr] = fmt_unknown;
2536 err = -1;
2537 break;
2538 }
2539 } else if ((fpr & 1) == 0) { /* even register number only */
2540 switch (fmt) {
2541 case fmt_single :
2542 case fmt_word :
2543 FGR[fpr+1] = 0xDEADC0DE;
2544 FGR[fpr] = (value & 0xFFFFFFFF);
2545 fpr_state[fpr + 1] = fmt;
2546 fpr_state[fpr] = fmt;
2547 break;
2548
2549 case fmt_uninterpreted:
2550 case fmt_double :
2551 case fmt_long :
2552 FGR[fpr+1] = (value >> 32);
2553 FGR[fpr] = (value & 0xFFFFFFFF);
2554 fpr_state[fpr + 1] = fmt;
2555 fpr_state[fpr] = fmt;
2556 break;
2557
2558 default :
2559 fpr_state[fpr] = fmt_unknown;
2560 err = -1;
2561 break;
2562 }
2563 }
2564 #if defined(WARN_RESULT)
2565 else
2566 UndefinedResult();
2567 #endif /* WARN_RESULT */
2568
2569 if (err)
2570 SignalException(SimulatorFault,"Unrecognised FP format in StoreFPR()");
2571
2572 #ifdef DEBUG
2573 printf("DBG: StoreFPR: fpr[%d] = 0x%08X%08X (format %s)\n",fpr,WORD64HI(FGR[fpr]),WORD64LO(FGR[fpr]),DOFMT(fmt));
2574 #endif /* DEBUG */
2575
2576 return;
2577 }
2578
2579 static int
2580 NaN(op,fmt)
2581 uword64 op;
2582 FP_formats fmt;
2583 {
2584 int boolean = 0;
2585
2586 /* Check if (((E - bias) == (E_max + 1)) && (fraction != 0)). We
2587 know that the exponent field is biased... we we cheat and avoid
2588 removing the bias value. */
2589 switch (fmt) {
2590 case fmt_single:
2591 boolean = ((FP_S_be(op) == 0xFF) && (FP_S_f(op) != 0));
2592 /* We could use "FP_S_fb(1,op)" to ascertain whether we are
2593 dealing with a SNaN or QNaN */
2594 break;
2595 case fmt_double:
2596 boolean = ((FP_D_be(op) == 0x7FF) && (FP_D_f(op) != 0));
2597 /* We could use "FP_S_fb(1,op)" to ascertain whether we are
2598 dealing with a SNaN or QNaN */
2599 break;
2600 case fmt_word:
2601 boolean = (op == FPQNaN_WORD);
2602 break;
2603 case fmt_long:
2604 boolean = (op == FPQNaN_LONG);
2605 break;
2606 }
2607
2608 #ifdef DEBUG
2609 printf("DBG: NaN: returning %d for 0x%08X%08X (format = %s)\n",boolean,WORD64HI(op),WORD64LO(op),DOFMT(fmt));
2610 #endif /* DEBUG */
2611
2612 return(boolean);
2613 }
2614
2615 static int
2616 Infinity(op,fmt)
2617 uword64 op;
2618 FP_formats fmt;
2619 {
2620 int boolean = 0;
2621
2622 #ifdef DEBUG
2623 printf("DBG: Infinity: format %s 0x%08X%08X (PC = 0x%08X%08X)\n",DOFMT(fmt),WORD64HI(op),WORD64LO(op),WORD64HI(IPC),WORD64LO(IPC));
2624 #endif /* DEBUG */
2625
2626 /* Check if (((E - bias) == (E_max + 1)) && (fraction == 0)). We
2627 know that the exponent field is biased... we we cheat and avoid
2628 removing the bias value. */
2629 switch (fmt) {
2630 case fmt_single:
2631 boolean = ((FP_S_be(op) == 0xFF) && (FP_S_f(op) == 0));
2632 break;
2633 case fmt_double:
2634 boolean = ((FP_D_be(op) == 0x7FF) && (FP_D_f(op) == 0));
2635 break;
2636 default:
2637 printf("DBG: TODO: unrecognised format (%s) for Infinity check\n",DOFMT(fmt));
2638 break;
2639 }
2640
2641 #ifdef DEBUG
2642 printf("DBG: Infinity: returning %d for 0x%08X%08X (format = %s)\n",boolean,WORD64HI(op),WORD64LO(op),DOFMT(fmt));
2643 #endif /* DEBUG */
2644
2645 return(boolean);
2646 }
2647
2648 static int
2649 Less(op1,op2,fmt)
2650 uword64 op1;
2651 uword64 op2;
2652 FP_formats fmt;
2653 {
2654 int boolean = 0;
2655
2656 /* Argument checking already performed by the FPCOMPARE code */
2657
2658 #ifdef DEBUG
2659 printf("DBG: Less: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2660 #endif /* DEBUG */
2661
2662 /* The format type should already have been checked: */
2663 switch (fmt) {
2664 case fmt_single:
2665 {
2666 unsigned int wop1 = (unsigned int)op1;
2667 unsigned int wop2 = (unsigned int)op2;
2668 boolean = (*(float *)&wop1 < *(float *)&wop2);
2669 }
2670 break;
2671 case fmt_double:
2672 boolean = (*(double *)&op1 < *(double *)&op2);
2673 break;
2674 }
2675
2676 #ifdef DEBUG
2677 printf("DBG: Less: returning %d (format = %s)\n",boolean,DOFMT(fmt));
2678 #endif /* DEBUG */
2679
2680 return(boolean);
2681 }
2682
2683 static int
2684 Equal(op1,op2,fmt)
2685 uword64 op1;
2686 uword64 op2;
2687 FP_formats fmt;
2688 {
2689 int boolean = 0;
2690
2691 /* Argument checking already performed by the FPCOMPARE code */
2692
2693 #ifdef DEBUG
2694 printf("DBG: Equal: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2695 #endif /* DEBUG */
2696
2697 /* The format type should already have been checked: */
2698 switch (fmt) {
2699 case fmt_single:
2700 boolean = ((op1 & 0xFFFFFFFF) == (op2 & 0xFFFFFFFF));
2701 break;
2702 case fmt_double:
2703 boolean = (op1 == op2);
2704 break;
2705 }
2706
2707 #ifdef DEBUG
2708 printf("DBG: Equal: returning %d (format = %s)\n",boolean,DOFMT(fmt));
2709 #endif /* DEBUG */
2710
2711 return(boolean);
2712 }
2713
2714 static uword64
2715 AbsoluteValue(op,fmt)
2716 uword64 op;
2717 FP_formats fmt;
2718 {
2719 uword64 result;
2720
2721 #ifdef DEBUG
2722 printf("DBG: AbsoluteValue: %s: op = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op),WORD64LO(op));
2723 #endif /* DEBUG */
2724
2725 /* The format type should already have been checked: */
2726 switch (fmt) {
2727 case fmt_single:
2728 {
2729 unsigned int wop = (unsigned int)op;
2730 float tmp = ((float)fabs((double)*(float *)&wop));
2731 result = (uword64)*(unsigned int *)&tmp;
2732 }
2733 break;
2734 case fmt_double:
2735 {
2736 double tmp = (fabs(*(double *)&op));
2737 result = *(uword64 *)&tmp;
2738 }
2739 }
2740
2741 return(result);
2742 }
2743
2744 static uword64
2745 Negate(op,fmt)
2746 uword64 op;
2747 FP_formats fmt;
2748 {
2749 uword64 result;
2750
2751 #ifdef DEBUG
2752 printf("DBG: Negate: %s: op = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op),WORD64LO(op));
2753 #endif /* DEBUG */
2754
2755 /* The format type should already have been checked: */
2756 switch (fmt) {
2757 case fmt_single:
2758 {
2759 unsigned int wop = (unsigned int)op;
2760 float tmp = ((float)0.0 - *(float *)&wop);
2761 result = (uword64)*(unsigned int *)&tmp;
2762 }
2763 break;
2764 case fmt_double:
2765 {
2766 double tmp = ((double)0.0 - *(double *)&op);
2767 result = *(uword64 *)&tmp;
2768 }
2769 break;
2770 }
2771
2772 return(result);
2773 }
2774
2775 static uword64
2776 Add(op1,op2,fmt)
2777 uword64 op1;
2778 uword64 op2;
2779 FP_formats fmt;
2780 {
2781 uword64 result;
2782
2783 #ifdef DEBUG
2784 printf("DBG: Add: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2785 #endif /* DEBUG */
2786
2787 /* The registers must specify FPRs valid for operands of type
2788 "fmt". If they are not valid, the result is undefined. */
2789
2790 /* The format type should already have been checked: */
2791 switch (fmt) {
2792 case fmt_single:
2793 {
2794 unsigned int wop1 = (unsigned int)op1;
2795 unsigned int wop2 = (unsigned int)op2;
2796 float tmp = (*(float *)&wop1 + *(float *)&wop2);
2797 result = (uword64)*(unsigned int *)&tmp;
2798 }
2799 break;
2800 case fmt_double:
2801 {
2802 double tmp = (*(double *)&op1 + *(double *)&op2);
2803 result = *(uword64 *)&tmp;
2804 }
2805 break;
2806 }
2807
2808 #ifdef DEBUG
2809 printf("DBG: Add: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
2810 #endif /* DEBUG */
2811
2812 return(result);
2813 }
2814
2815 static uword64
2816 Sub(op1,op2,fmt)
2817 uword64 op1;
2818 uword64 op2;
2819 FP_formats fmt;
2820 {
2821 uword64 result;
2822
2823 #ifdef DEBUG
2824 printf("DBG: Sub: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2825 #endif /* DEBUG */
2826
2827 /* The registers must specify FPRs valid for operands of type
2828 "fmt". If they are not valid, the result is undefined. */
2829
2830 /* The format type should already have been checked: */
2831 switch (fmt) {
2832 case fmt_single:
2833 {
2834 unsigned int wop1 = (unsigned int)op1;
2835 unsigned int wop2 = (unsigned int)op2;
2836 float tmp = (*(float *)&wop1 - *(float *)&wop2);
2837 result = (uword64)*(unsigned int *)&tmp;
2838 }
2839 break;
2840 case fmt_double:
2841 {
2842 double tmp = (*(double *)&op1 - *(double *)&op2);
2843 result = *(uword64 *)&tmp;
2844 }
2845 break;
2846 }
2847
2848 #ifdef DEBUG
2849 printf("DBG: Sub: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
2850 #endif /* DEBUG */
2851
2852 return(result);
2853 }
2854
2855 static uword64
2856 Multiply(op1,op2,fmt)
2857 uword64 op1;
2858 uword64 op2;
2859 FP_formats fmt;
2860 {
2861 uword64 result;
2862
2863 #ifdef DEBUG
2864 printf("DBG: Multiply: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2865 #endif /* DEBUG */
2866
2867 /* The registers must specify FPRs valid for operands of type
2868 "fmt". If they are not valid, the result is undefined. */
2869
2870 /* The format type should already have been checked: */
2871 switch (fmt) {
2872 case fmt_single:
2873 {
2874 unsigned int wop1 = (unsigned int)op1;
2875 unsigned int wop2 = (unsigned int)op2;
2876 float tmp = (*(float *)&wop1 * *(float *)&wop2);
2877 result = (uword64)*(unsigned int *)&tmp;
2878 }
2879 break;
2880 case fmt_double:
2881 {
2882 double tmp = (*(double *)&op1 * *(double *)&op2);
2883 result = *(uword64 *)&tmp;
2884 }
2885 break;
2886 }
2887
2888 #ifdef DEBUG
2889 printf("DBG: Multiply: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
2890 #endif /* DEBUG */
2891
2892 return(result);
2893 }
2894
2895 static uword64
2896 Divide(op1,op2,fmt)
2897 uword64 op1;
2898 uword64 op2;
2899 FP_formats fmt;
2900 {
2901 uword64 result;
2902
2903 #ifdef DEBUG
2904 printf("DBG: Divide: %s: op1 = 0x%08X%08X : op2 = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op1),WORD64LO(op1),WORD64HI(op2),WORD64LO(op2));
2905 #endif /* DEBUG */
2906
2907 /* The registers must specify FPRs valid for operands of type
2908 "fmt". If they are not valid, the result is undefined. */
2909
2910 /* The format type should already have been checked: */
2911 switch (fmt) {
2912 case fmt_single:
2913 {
2914 unsigned int wop1 = (unsigned int)op1;
2915 unsigned int wop2 = (unsigned int)op2;
2916 float tmp = (*(float *)&wop1 / *(float *)&wop2);
2917 result = (uword64)*(unsigned int *)&tmp;
2918 }
2919 break;
2920 case fmt_double:
2921 {
2922 double tmp = (*(double *)&op1 / *(double *)&op2);
2923 result = *(uword64 *)&tmp;
2924 }
2925 break;
2926 }
2927
2928 #ifdef DEBUG
2929 printf("DBG: Divide: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
2930 #endif /* DEBUG */
2931
2932 return(result);
2933 }
2934
2935 static uword64
2936 Recip(op,fmt)
2937 uword64 op;
2938 FP_formats fmt;
2939 {
2940 uword64 result;
2941
2942 #ifdef DEBUG
2943 printf("DBG: Recip: %s: op = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op),WORD64LO(op));
2944 #endif /* DEBUG */
2945
2946 /* The registers must specify FPRs valid for operands of type
2947 "fmt". If they are not valid, the result is undefined. */
2948
2949 /* The format type should already have been checked: */
2950 switch (fmt) {
2951 case fmt_single:
2952 {
2953 unsigned int wop = (unsigned int)op;
2954 float tmp = ((float)1.0 / *(float *)&wop);
2955 result = (uword64)*(unsigned int *)&tmp;
2956 }
2957 break;
2958 case fmt_double:
2959 {
2960 double tmp = ((double)1.0 / *(double *)&op);
2961 result = *(uword64 *)&tmp;
2962 }
2963 break;
2964 }
2965
2966 #ifdef DEBUG
2967 printf("DBG: Recip: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
2968 #endif /* DEBUG */
2969
2970 return(result);
2971 }
2972
2973 static uword64
2974 SquareRoot(op,fmt)
2975 uword64 op;
2976 FP_formats fmt;
2977 {
2978 uword64 result;
2979
2980 #ifdef DEBUG
2981 printf("DBG: SquareRoot: %s: op = 0x%08X%08X\n",DOFMT(fmt),WORD64HI(op),WORD64LO(op));
2982 #endif /* DEBUG */
2983
2984 /* The registers must specify FPRs valid for operands of type
2985 "fmt". If they are not valid, the result is undefined. */
2986
2987 /* The format type should already have been checked: */
2988 switch (fmt) {
2989 case fmt_single:
2990 {
2991 unsigned int wop = (unsigned int)op;
2992 float tmp = ((float)sqrt((double)*(float *)&wop));
2993 result = (uword64)*(unsigned int *)&tmp;
2994 }
2995 break;
2996 case fmt_double:
2997 {
2998 double tmp = (sqrt(*(double *)&op));
2999 result = *(uword64 *)&tmp;
3000 }
3001 break;
3002 }
3003
3004 #ifdef DEBUG
3005 printf("DBG: SquareRoot: returning 0x%08X%08X (format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(fmt));
3006 #endif /* DEBUG */
3007
3008 return(result);
3009 }
3010
3011 static uword64
3012 Convert(rm,op,from,to)
3013 int rm;
3014 uword64 op;
3015 FP_formats from;
3016 FP_formats to;
3017 {
3018 uword64 result;
3019
3020 #ifdef DEBUG
3021 printf("DBG: Convert: mode %s : op 0x%08X%08X : from %s : to %s : (PC = 0x%08X%08X)\n",RMMODE(rm),WORD64HI(op),WORD64LO(op),DOFMT(from),DOFMT(to),WORD64HI(IPC),WORD64LO(IPC));
3022 #endif /* DEBUG */
3023
3024 /* The value "op" is converted to the destination format, rounding
3025 using mode "rm". When the destination is a fixed-point format,
3026 then a source value of Infinity, NaN or one which would round to
3027 an integer outside the fixed point range then an IEEE Invalid
3028 Operation condition is raised. */
3029 switch (to) {
3030 case fmt_single:
3031 {
3032 float tmp;
3033 switch (from) {
3034 case fmt_double:
3035 tmp = (float)(*(double *)&op);
3036 break;
3037
3038 case fmt_word:
3039 tmp = (float)((int)(op & 0xFFFFFFFF));
3040 break;
3041
3042 case fmt_long:
3043 tmp = (float)((int)op);
3044 break;
3045 }
3046
3047 switch (rm) {
3048 case FP_RM_NEAREST:
3049 /* Round result to nearest representable value. When two
3050 representable values are equally near, round to the value
3051 that has a least significant bit of zero (i.e. is even). */
3052 #if defined(sun)
3053 tmp = (float)anint((double)tmp);
3054 #else
3055 /* TODO: Provide round-to-nearest */
3056 #endif
3057 break;
3058
3059 case FP_RM_TOZERO:
3060 /* Round result to the value closest to, and not greater in
3061 magnitude than, the result. */
3062 #if defined(sun)
3063 tmp = (float)aint((double)tmp);
3064 #else
3065 /* TODO: Provide round-to-zero */
3066 #endif
3067 break;
3068
3069 case FP_RM_TOPINF:
3070 /* Round result to the value closest to, and not less than,
3071 the result. */
3072 tmp = (float)ceil((double)tmp);
3073 break;
3074
3075 case FP_RM_TOMINF:
3076 /* Round result to the value closest to, and not greater than,
3077 the result. */
3078 tmp = (float)floor((double)tmp);
3079 break;
3080 }
3081 result = (uword64)*(unsigned int *)&tmp;
3082 }
3083 break;
3084
3085 case fmt_double:
3086 {
3087 double tmp;
3088
3089 switch (from) {
3090 case fmt_single:
3091 {
3092 unsigned int wop = (unsigned int)op;
3093 tmp = (double)(*(float *)&wop);
3094 }
3095 break;
3096
3097 case fmt_word:
3098 tmp = (double)((word64)SIGNEXTEND((op & 0xFFFFFFFF),32));
3099 break;
3100
3101 case fmt_long:
3102 tmp = (double)((word64)op);
3103 break;
3104 }
3105
3106 switch (rm) {
3107 case FP_RM_NEAREST:
3108 #if defined(sun)
3109 tmp = anint(*(double *)&tmp);
3110 #else
3111 /* TODO: Provide round-to-nearest */
3112 #endif
3113 break;
3114
3115 case FP_RM_TOZERO:
3116 #if defined(sun)
3117 tmp = aint(*(double *)&tmp);
3118 #else
3119 /* TODO: Provide round-to-zero */
3120 #endif
3121 break;
3122
3123 case FP_RM_TOPINF:
3124 tmp = ceil(*(double *)&tmp);
3125 break;
3126
3127 case FP_RM_TOMINF:
3128 tmp = floor(*(double *)&tmp);
3129 break;
3130 }
3131 result = *(uword64 *)&tmp;
3132 }
3133 break;
3134
3135 case fmt_word:
3136 case fmt_long:
3137 if (Infinity(op,from) || NaN(op,from) || (1 == 0/*TODO: check range */)) {
3138 printf("DBG: TODO: update FCSR\n");
3139 SignalException(FPE);
3140 } else {
3141 if (to == fmt_word) {
3142 unsigned int tmp;
3143 switch (from) {
3144 case fmt_single:
3145 {
3146 unsigned int wop = (unsigned int)op;
3147 tmp = (unsigned int)*((float *)&wop);
3148 }
3149 break;
3150 case fmt_double:
3151 tmp = (unsigned int)*((double *)&op);
3152 #ifdef DEBUG
3153 printf("DBG: from double %.30f (0x%08X%08X) to word: 0x%08X\n",*((double *)&op),WORD64HI(op),WORD64LO(op),tmp);
3154 #endif /* DEBUG */
3155 break;
3156 }
3157 result = (uword64)tmp;
3158 } else { /* fmt_long */
3159 switch (from) {
3160 case fmt_single:
3161 {
3162 unsigned int wop = (unsigned int)op;
3163 result = (uword64)*((float *)&wop);
3164 }
3165 break;
3166 case fmt_double:
3167 result = (uword64)*((double *)&op);
3168 break;
3169 }
3170 }
3171 }
3172 break;
3173 }
3174
3175 #ifdef DEBUG
3176 printf("DBG: Convert: returning 0x%08X%08X (to format = %s)\n",WORD64HI(result),WORD64LO(result),DOFMT(to));
3177 #endif /* DEBUG */
3178
3179 return(result);
3180 }
3181 #endif /* HASFPU */
3182
3183 /*-- co-processor support routines ------------------------------------------*/
3184
3185 static int
3186 CoProcPresent(coproc_number)
3187 unsigned int coproc_number;
3188 {
3189 /* Return TRUE if simulator provides a model for the given co-processor number */
3190 return(0);
3191 }
3192
3193 static void
3194 COP_LW(coproc_num,coproc_reg,memword)
3195 int coproc_num, coproc_reg;
3196 unsigned int memword;
3197 {
3198 switch (coproc_num) {
3199 #if defined(HASFPU)
3200 case 1:
3201 #ifdef DEBUG
3202 printf("DBG: COP_LW: memword = 0x%08X (uword64)memword = 0x%08X%08X\n",memword,WORD64HI(memword),WORD64LO(memword));
3203 #endif
3204 StoreFPR(coproc_reg,fmt_uninterpreted,(uword64)memword);
3205 break;
3206 #endif /* HASFPU */
3207
3208 default:
3209 callback->printf_filtered(callback,"COP_LW(%d,%d,0x%08X) at IPC = 0x%08X%08X : TODO (architecture specific)\n",coproc_num,coproc_reg,memword,WORD64HI(IPC),WORD64LO(IPC));
3210 break;
3211 }
3212
3213 return;
3214 }
3215
3216 static void
3217 COP_LD(coproc_num,coproc_reg,memword)
3218 int coproc_num, coproc_reg;
3219 uword64 memword;
3220 {
3221 switch (coproc_num) {
3222 #if defined(HASFPU)
3223 case 1:
3224 StoreFPR(coproc_reg,fmt_uninterpreted,memword);
3225 break;
3226 #endif /* HASFPU */
3227
3228 default:
3229 callback->printf_filtered(callback,"COP_LD(%d,%d,0x%08X%08X) at IPC = 0x%08X%08X : TODO (architecture specific)\n",coproc_num,coproc_reg,WORD64HI(memword),WORD64LO(memword),WORD64HI(IPC),WORD64LO(IPC));
3230 break;
3231 }
3232
3233 return;
3234 }
3235
3236 static unsigned int
3237 COP_SW(coproc_num,coproc_reg)
3238 int coproc_num, coproc_reg;
3239 {
3240 unsigned int value = 0;
3241 switch (coproc_num) {
3242 #if defined(HASFPU)
3243 case 1:
3244 #if 1
3245 value = (unsigned int)ValueFPR(coproc_reg,fmt_uninterpreted);
3246 #else
3247 #if 1
3248 value = (unsigned int)ValueFPR(coproc_reg,fpr_state[coproc_reg]);
3249 #else
3250 #ifdef DEBUG
3251 printf("DBG: COP_SW: reg in format %s (will be accessing as single)\n",DOFMT(fpr_state[coproc_reg]));
3252 #endif /* DEBUG */
3253 value = (unsigned int)ValueFPR(coproc_reg,fmt_single);
3254 #endif
3255 #endif
3256 break;
3257 #endif /* HASFPU */
3258
3259 default:
3260 callback->printf_filtered(callback,"COP_SW(%d,%d) at IPC = 0x%08X%08X : TODO (architecture specific)\n",coproc_num,coproc_reg,WORD64HI(IPC),WORD64LO(IPC));
3261 break;
3262 }
3263
3264 return(value);
3265 }
3266
3267 static uword64
3268 COP_SD(coproc_num,coproc_reg)
3269 int coproc_num, coproc_reg;
3270 {
3271 uword64 value = 0;
3272 switch (coproc_num) {
3273 #if defined(HASFPU)
3274 case 1:
3275 #if 1
3276 value = ValueFPR(coproc_reg,fmt_uninterpreted);
3277 #else
3278 #if 1
3279 value = ValueFPR(coproc_reg,fpr_state[coproc_reg]);
3280 #else
3281 #ifdef DEBUG
3282 printf("DBG: COP_SD: reg in format %s (will be accessing as double)\n",DOFMT(fpr_state[coproc_reg]));
3283 #endif /* DEBUG */
3284 value = ValueFPR(coproc_reg,fmt_double);
3285 #endif
3286 #endif
3287 break;
3288 #endif /* HASFPU */
3289
3290 default:
3291 callback->printf_filtered(callback,"COP_SD(%d,%d) at IPC = 0x%08X%08X : TODO (architecture specific)\n",coproc_num,coproc_reg,WORD64HI(IPC),WORD64LO(IPC));
3292 break;
3293 }
3294
3295 return(value);
3296 }
3297
3298 static void
3299 decode_coproc(instruction)
3300 unsigned int instruction;
3301 {
3302 int coprocnum = ((instruction >> 26) & 3);
3303
3304 switch (coprocnum) {
3305 case 0: /* standard CPU control and cache registers */
3306 {
3307 /* NOTEs:
3308 Standard CP0 registers
3309 0 = Index R4000 VR4100 VR4300
3310 1 = Random R4000 VR4100 VR4300
3311 2 = EntryLo0 R4000 VR4100 VR4300
3312 3 = EntryLo1 R4000 VR4100 VR4300
3313 4 = Context R4000 VR4100 VR4300
3314 5 = PageMask R4000 VR4100 VR4300
3315 6 = Wired R4000 VR4100 VR4300
3316 8 = BadVAddr R4000 VR4100 VR4300
3317 9 = Count R4000 VR4100 VR4300
3318 10 = EntryHi R4000 VR4100 VR4300
3319 11 = Compare R4000 VR4100 VR4300
3320 12 = SR R4000 VR4100 VR4300
3321 13 = Cause R4000 VR4100 VR4300
3322 14 = EPC R4000 VR4100 VR4300
3323 15 = PRId R4000 VR4100 VR4300
3324 16 = Config R4000 VR4100 VR4300
3325 17 = LLAddr R4000 VR4100 VR4300
3326 18 = WatchLo R4000 VR4100 VR4300
3327 19 = WatchHi R4000 VR4100 VR4300
3328 20 = XContext R4000 VR4100 VR4300
3329 26 = PErr or ECC R4000 VR4100 VR4300
3330 27 = CacheErr R4000 VR4100
3331 28 = TagLo R4000 VR4100 VR4300
3332 29 = TagHi R4000 VR4100 VR4300
3333 30 = ErrorEPC R4000 VR4100 VR4300
3334 */
3335 int code = ((instruction >> 21) & 0x1F);
3336 /* R4000 Users Manual (second edition) lists the following CP0
3337 instructions:
3338 DMFC0 Doubleword Move From CP0 (VR4100 = 01000000001tttttddddd00000000000)
3339 DMTC0 Doubleword Move To CP0 (VR4100 = 01000000101tttttddddd00000000000)
3340 MFC0 word Move From CP0 (VR4100 = 01000000000tttttddddd00000000000)
3341 MTC0 word Move To CP0 (VR4100 = 01000000100tttttddddd00000000000)
3342 TLBR Read Indexed TLB Entry (VR4100 = 01000010000000000000000000000001)
3343 TLBWI Write Indexed TLB Entry (VR4100 = 01000010000000000000000000000010)
3344 TLBWR Write Random TLB Entry (VR4100 = 01000010000000000000000000000110)
3345 TLBP Probe TLB for Matching Entry (VR4100 = 01000010000000000000000000001000)
3346 CACHE Cache operation (VR4100 = 101111bbbbbpppppiiiiiiiiiiiiiiii)
3347 ERET Exception return (VR4100 = 01000010000000000000000000011000)
3348 */
3349 if (((code == 0x00) || (code == 0x04)) && ((instruction & 0x7FF) == 0)) {
3350 int rt = ((instruction >> 16) & 0x1F);
3351 int rd = ((instruction >> 11) & 0x1F);
3352 if (code == 0x00) { /* MF : move from */
3353 callback->printf_filtered(callback,"Warning: MFC0 %d,%d not handled yet (architecture specific)\n",rt,rd);
3354 GPR[rt] = 0xDEADC0DE; /* CPR[0,rd] */
3355 } else { /* MT : move to */
3356 /* CPR[0,rd] = GPR[rt]; */
3357 callback->printf_filtered(callback,"Warning: MTC0 %d,%d not handled yet (architecture specific)\n",rt,rd);
3358 }
3359 } else
3360 callback->printf_filtered(callback,"Warning: Unrecognised COP0 instruction 0x%08X at IPC = 0x%08X%08X : No handler present\n",instruction,WORD64HI(IPC),WORD64LO(IPC));
3361 /* TODO: When executing an ERET or RFE instruction we should
3362 clear LLBIT, to ensure that any out-standing atomic
3363 read/modify/write sequence fails. */
3364 }
3365 break;
3366
3367 case 2: /* undefined co-processor */
3368 callback->printf_filtered(callback,"Warning: COP2 instruction 0x%08X at IPC = 0x%08X%08X : No handler present\n",instruction,WORD64HI(IPC),WORD64LO(IPC));
3369 break;
3370
3371 case 1: /* should not occur (FPU co-processor) */
3372 case 3: /* should not occur (FPU co-processor) */
3373 SignalException(ReservedInstruction,instruction);
3374 break;
3375 }
3376
3377 return;
3378 }
3379
3380 /*-- instruction simulation -------------------------------------------------*/
3381
3382 static void
3383 simulate ()
3384 {
3385 unsigned int pipeline_count = 1;
3386
3387 #ifdef DEBUG
3388 if (membank == NULL) {
3389 printf("DBG: simulate() entered with no memory\n");
3390 exit(1);
3391 }
3392 #endif /* DEBUG */
3393
3394 #if 0 /* Disabled to check that everything works OK */
3395 /* The VR4300 seems to sign-extend the PC on its first
3396 access. However, this may just be because it is currently
3397 configured in 32bit mode. However... */
3398 PC = SIGNEXTEND(PC,32);
3399 #endif
3400
3401 /* main controlling loop */
3402 do {
3403 /* Fetch the next instruction from the simulator memory: */
3404 uword64 vaddr = (uword64)PC;
3405 uword64 paddr;
3406 int cca;
3407 unsigned int instruction;
3408 int dsstate = (state & simDELAYSLOT);
3409
3410 #ifdef DEBUG
3411 {
3412 printf("DBG: state = 0x%08X :",state);
3413 if (state & simSTOP) printf(" simSTOP");
3414 if (state & simSTEP) printf(" simSTEP");
3415 if (state & simHALTEX) printf(" simHALTEX");
3416 if (state & simHALTIN) printf(" simHALTIN");
3417 if (state & simBE) printf(" simBE");
3418 }
3419 #endif /* DEBUG */
3420
3421 #ifdef DEBUG
3422 if (dsstate)
3423 callback->printf_filtered(callback,"DBG: DSPC = 0x%08X%08X\n",WORD64HI(DSPC),WORD64LO(DSPC));
3424 #endif /* DEBUG */
3425
3426 if (AddressTranslation(PC,isINSTRUCTION,isLOAD,&paddr,&cca,isTARGET,isREAL)) { /* Copy the action of the LW instruction */
3427 unsigned int reverse = (ReverseEndian ? 1 : 0);
3428 unsigned int bigend = (BigEndianCPU ? 1 : 0);
3429 uword64 value;
3430 unsigned int byte;
3431 paddr = ((paddr & ~0x7) | ((paddr & 0x7) ^ (reverse << 2)));
3432 value = LoadMemory(cca,AccessLength_WORD,paddr,vaddr,isINSTRUCTION,isREAL);
3433 byte = ((vaddr & 0x7) ^ (bigend << 2));
3434 instruction = ((value >> (8 * byte)) & 0xFFFFFFFF);
3435 } else {
3436 fprintf(stderr,"Cannot translate address for PC = 0x%08X%08X failed\n",WORD64HI(PC),WORD64LO(PC));
3437 exit(1);
3438 }
3439
3440 #ifdef DEBUG
3441 callback->printf_filtered(callback,"DBG: fetched 0x%08X from PC = 0x%08X%08X\n",instruction,WORD64HI(PC),WORD64LO(PC));
3442 #endif /* DEBUG */
3443
3444 /*DBG*/ if (instruction == 0x46200005) /* ABS.D */
3445 /*DBG*/ callback->printf_filtered(callback,"DBG: ABS.D (0x%08X) instruction\n",instruction);
3446
3447 #if !defined(FASTSIM) || defined(PROFILE)
3448 instruction_fetches++;
3449 /* Since we increment above, the value should only ever be zero if
3450 we have just overflowed: */
3451 if (instruction_fetches == 0)
3452 instruction_fetch_overflow++;
3453 #if defined(PROFILE)
3454 if ((state & simPROFILE) && ((instruction_fetches % profile_frequency) == 0) && profile_hist) {
3455 int n = ((unsigned int)(PC - profile_minpc) >> (profile_shift + 2));
3456 if (n < profile_nsamples) {
3457 /* NOTE: The counts for the profiling bins are only 16bits wide */
3458 if (profile_hist[n] != USHRT_MAX)
3459 (profile_hist[n])++;
3460 }
3461 }
3462 #endif /* PROFILE */
3463 #endif /* !FASTSIM && PROFILE */
3464
3465 IPC = PC; /* copy PC for this instruction */
3466 /* This is required by exception processing, to ensure that we can
3467 cope with exceptions in the delay slots of branches that may
3468 already have changed the PC. */
3469 PC += 4; /* increment ready for the next fetch */
3470 /* NOTE: If we perform a delay slot change to the PC, this
3471 increment is not requuired. However, it would make the
3472 simulator more complicated to try and avoid this small hit. */
3473
3474 /* Currently this code provides a simple model. For more
3475 complicated models we could perform exception status checks at
3476 this point, and set the simSTOP state as required. This could
3477 also include processing any hardware interrupts raised by any
3478 I/O model attached to the simulator context.
3479
3480 Support for "asynchronous" I/O events within the simulated world
3481 could be providing by managing a counter, and calling a I/O
3482 specific handler when a particular threshold is reached. On most
3483 architectures a decrement and check for zero operation is
3484 usually quicker than an increment and compare. However, the
3485 process of managing a known value decrement to zero, is higher
3486 than the cost of using an explicit value UINT_MAX into the
3487 future. Which system is used will depend on how complicated the
3488 I/O model is, and how much it is likely to affect the simulator
3489 bandwidth.
3490
3491 If events need to be scheduled further in the future than
3492 UINT_MAX event ticks, then the I/O model should just provide its
3493 own counter, triggered from the event system. */
3494
3495 /* MIPS pipeline ticks. To allow for future support where the
3496 pipeline hit of individual instructions is known, this control
3497 loop manages a "pipeline_count" variable. It is initialised to
3498 1 (one), and will only be changed by the simulator engine when
3499 executing an instruction. If the engine does not have access to
3500 pipeline cycle count information then all instructions will be
3501 treated as using a single cycle. NOTE: A standard system is not
3502 provided by the default simulator because different MIPS
3503 architectures have different cycle counts for the same
3504 instructions. */
3505
3506 #if defined(HASFPU)
3507 /* Set previous flag, depending on current: */
3508 if (state & simPCOC0)
3509 state |= simPCOC1;
3510 else
3511 state &= ~simPCOC1;
3512 /* and update the current value: */
3513 if (GETFCC(0))
3514 state |= simPCOC0;
3515 else
3516 state &= ~simPCOC0;
3517 #endif /* HASFPU */
3518
3519 /* NOTE: For multi-context simulation environments the "instruction"
3520 variable should be local to this routine. */
3521
3522 /* Shorthand accesses for engine. Note: If we wanted to use global
3523 variables (and a single-threaded simulator engine), then we can
3524 create the actual variables with these names. */
3525
3526 if (!(state & simSKIPNEXT)) {
3527 /* Include the simulator engine */
3528 #include "engine.c"
3529 #if ((GPRLEN == 64) && !defined(PROCESSOR_64BIT)) || ((GPRLEN == 32) && defined(PROCESSOR_64BIT))
3530 #error "Mismatch between run-time simulator code and simulation engine"
3531 #endif
3532
3533 #if defined(WARN_LOHI)
3534 /* Decrement the HI/LO validity ticks */
3535 if (HIACCESS > 0)
3536 HIACCESS--;
3537 if (LOACCESS > 0)
3538 LOACCESS--;
3539 #endif /* WARN_LOHI */
3540
3541 #if defined(WARN_ZERO)
3542 /* For certain MIPS architectures, GPR[0] is hardwired to zero. We
3543 should check for it being changed. It is better doing it here,
3544 than within the simulator, since it will help keep the simulator
3545 small. */
3546 if (ZERO != 0) {
3547 callback->printf_filtered(callback,"SIM Warning: The ZERO register has been updated with 0x%08X%08X (PC = 0x%08X%08X)\nSIM Warning: Resetting back to zero\n",WORD64HI(ZERO),WORD64LO(ZERO),WORD64HI(IPC),WORD64LO(IPC));
3548 ZERO = 0; /* reset back to zero before next instruction */
3549 }
3550 #endif /* WARN_ZERO */
3551 } else /* simSKIPNEXT check */
3552 state &= ~simSKIPNEXT;
3553
3554 /* If the delay slot was active before the instruction is
3555 executed, then update the PC to its new value: */
3556 if (dsstate) {
3557 #ifdef DEBUG
3558 printf("DBG: dsstate set before instruction execution - updating PC to 0x%08X%08X\n",WORD64HI(DSPC),WORD64LO(DSPC));
3559 #endif /* DEBUG */
3560 PC = DSPC;
3561 state &= ~simDELAYSLOT;
3562 }
3563
3564 if (MIPSISA < 4) { /* The following is only required on pre MIPS IV processors: */
3565 /* Deal with pending register updates: */
3566 #ifdef DEBUG
3567 printf("DBG: EMPTY BEFORE pending_in = %d, pending_out = %d, pending_total = %d\n",pending_in,pending_out,pending_total);
3568 #endif /* DEBUG */
3569 if (pending_out != pending_in) {
3570 int loop;
3571 int index = pending_out;
3572 int total = pending_total;
3573 if (pending_total == 0) {
3574 fprintf(stderr,"FATAL: Mis-match on pending update pointers\n");
3575 exit(1);
3576 }
3577 for (loop = 0; (loop < total); loop++) {
3578 #ifdef DEBUG
3579 printf("DBG: BEFORE index = %d, loop = %d\n",index,loop);
3580 #endif /* DEBUG */
3581 if (pending_slot_reg[index] != (LAST_EMBED_REGNUM + 1)) {
3582 #ifdef DEBUG
3583 printf("pending_slot_count[%d] = %d\n",index,pending_slot_count[index]);
3584 #endif /* DEBUG */
3585 if (--(pending_slot_count[index]) == 0) {
3586 #ifdef DEBUG
3587 printf("pending_slot_reg[%d] = %d\n",index,pending_slot_reg[index]);
3588 printf("pending_slot_value[%d] = 0x%08X%08X\n",index,WORD64HI(pending_slot_value[index]),WORD64LO(pending_slot_value[index]));
3589 #endif /* DEBUG */
3590 if (pending_slot_reg[index] == COCIDX) {
3591 SETFCC(0,((FCR31 & (1 << 23)) ? 1 : 0));
3592 } else {
3593 registers[pending_slot_reg[index]] = pending_slot_value[index];
3594 #if defined(HASFPU)
3595 /* The only time we have PENDING updates to FPU
3596 registers, is when performing binary transfers. This
3597 means we should update the register type field. */
3598 if ((pending_slot_reg[index] >= FGRIDX) && (pending_slot_reg[index] < (FGRIDX + 32)))
3599 fpr_state[pending_slot_reg[index]] = fmt_uninterpreted;
3600 #endif /* HASFPU */
3601 }
3602 #ifdef DEBUG
3603 printf("registers[%d] = 0x%08X%08X\n",pending_slot_reg[index],WORD64HI(registers[pending_slot_reg[index]]),WORD64LO(registers[pending_slot_reg[index]]));
3604 #endif /* DEBUG */
3605 pending_slot_reg[index] = (LAST_EMBED_REGNUM + 1);
3606 pending_out++;
3607 if (pending_out == PSLOTS)
3608 pending_out = 0;
3609 pending_total--;
3610 }
3611 }
3612 #ifdef DEBUG
3613 printf("DBG: AFTER index = %d, loop = %d\n",index,loop);
3614 #endif /* DEBUG */
3615 index++;
3616 if (index == PSLOTS)
3617 index = 0;
3618 }
3619 }
3620 #ifdef DEBUG
3621 printf("DBG: EMPTY AFTER pending_in = %d, pending_out = %d, pending_total = %d\n",pending_in,pending_out,pending_total);
3622 #endif /* DEBUG */
3623 }
3624
3625 #if !defined(FASTSIM)
3626 pipeline_ticks += pipeline_count;
3627 #endif /* FASTSIM */
3628
3629 if (state & simSTEP)
3630 state |= simSTOP;
3631 } while (!(state & simSTOP));
3632
3633 #ifdef DEBUG
3634 if (membank == NULL) {
3635 printf("DBG: simulate() LEAVING with no memory\n");
3636 exit(1);
3637 }
3638 #endif /* DEBUG */
3639
3640 return;
3641 }
3642
3643 /*---------------------------------------------------------------------------*/
3644 /*> EOF interp.c <*/
This page took 0.137167 seconds and 4 git commands to generate.