static_inst.hh revision 8148:93982cb5044c
16242Sgblack@eecs.umich.edu/*
26242Sgblack@eecs.umich.edu * Copyright (c) 2003-2005 The Regents of The University of Michigan
36242Sgblack@eecs.umich.edu * All rights reserved.
46242Sgblack@eecs.umich.edu *
56242Sgblack@eecs.umich.edu * Redistribution and use in source and binary forms, with or without
66242Sgblack@eecs.umich.edu * modification, are permitted provided that the following conditions are
76242Sgblack@eecs.umich.edu * met: redistributions of source code must retain the above copyright
86242Sgblack@eecs.umich.edu * notice, this list of conditions and the following disclaimer;
96242Sgblack@eecs.umich.edu * redistributions in binary form must reproduce the above copyright
106242Sgblack@eecs.umich.edu * notice, this list of conditions and the following disclaimer in the
116242Sgblack@eecs.umich.edu * documentation and/or other materials provided with the distribution;
126242Sgblack@eecs.umich.edu * neither the name of the copyright holders nor the names of its
136242Sgblack@eecs.umich.edu * contributors may be used to endorse or promote products derived from
146242Sgblack@eecs.umich.edu * this software without specific prior written permission.
156242Sgblack@eecs.umich.edu *
166242Sgblack@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
176242Sgblack@eecs.umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
186242Sgblack@eecs.umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
196242Sgblack@eecs.umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
206242Sgblack@eecs.umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
216242Sgblack@eecs.umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
226242Sgblack@eecs.umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
236242Sgblack@eecs.umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
246242Sgblack@eecs.umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
256242Sgblack@eecs.umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
266242Sgblack@eecs.umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
276242Sgblack@eecs.umich.edu *
286242Sgblack@eecs.umich.edu * Authors: Steve Reinhardt
296242Sgblack@eecs.umich.edu */
306242Sgblack@eecs.umich.edu
316242Sgblack@eecs.umich.edu#ifndef __CPU_STATIC_INST_HH__
326242Sgblack@eecs.umich.edu#define __CPU_STATIC_INST_HH__
336242Sgblack@eecs.umich.edu
346242Sgblack@eecs.umich.edu#include <bitset>
356242Sgblack@eecs.umich.edu#include <string>
366242Sgblack@eecs.umich.edu
376242Sgblack@eecs.umich.edu#include "arch/isa_traits.hh"
386242Sgblack@eecs.umich.edu#include "arch/types.hh"
396242Sgblack@eecs.umich.edu#include "arch/registers.hh"
406242Sgblack@eecs.umich.edu#include "config/the_isa.hh"
416242Sgblack@eecs.umich.edu#include "base/hashmap.hh"
426242Sgblack@eecs.umich.edu#include "base/misc.hh"
436242Sgblack@eecs.umich.edu#include "base/refcnt.hh"
446242Sgblack@eecs.umich.edu#include "base/types.hh"
456242Sgblack@eecs.umich.edu#include "cpu/op_class.hh"
466242Sgblack@eecs.umich.edu#include "sim/fault_fwd.hh"
476242Sgblack@eecs.umich.edu
486242Sgblack@eecs.umich.edu// forward declarations
496242Sgblack@eecs.umich.edustruct AlphaSimpleImpl;
506242Sgblack@eecs.umich.edustruct OzoneImpl;
516242Sgblack@eecs.umich.edustruct SimpleImpl;
526242Sgblack@eecs.umich.educlass ThreadContext;
536242Sgblack@eecs.umich.educlass DynInst;
546242Sgblack@eecs.umich.educlass Packet;
556242Sgblack@eecs.umich.edu
566242Sgblack@eecs.umich.educlass O3CPUImpl;
576242Sgblack@eecs.umich.edutemplate <class Impl> class BaseO3DynInst;
586735Sgblack@eecs.umich.edutypedef BaseO3DynInst<O3CPUImpl> O3DynInst;
596242Sgblack@eecs.umich.edutemplate <class Impl> class OzoneDynInst;
606242Sgblack@eecs.umich.educlass InOrderDynInst;
616242Sgblack@eecs.umich.edu
626723Sgblack@eecs.umich.educlass CheckerCPU;
636242Sgblack@eecs.umich.educlass FastCPU;
646242Sgblack@eecs.umich.educlass AtomicSimpleCPU;
656261Sgblack@eecs.umich.educlass TimingSimpleCPU;
666403Sgblack@eecs.umich.educlass InorderCPU;
676403Sgblack@eecs.umich.educlass SymbolTable;
686403Sgblack@eecs.umich.educlass AddrDecodePage;
696735Sgblack@eecs.umich.edu
706735Sgblack@eecs.umich.edunamespace Trace {
716261Sgblack@eecs.umich.edu    class InstRecord;
726261Sgblack@eecs.umich.edu}
736261Sgblack@eecs.umich.edu
746735Sgblack@eecs.umich.edu/**
756735Sgblack@eecs.umich.edu * Base, ISA-independent static instruction class.
766242Sgblack@eecs.umich.edu *
776242Sgblack@eecs.umich.edu * The main component of this class is the vector of flags and the
786242Sgblack@eecs.umich.edu * associated methods for reading them.  Any object that can rely
796242Sgblack@eecs.umich.edu * solely on these flags can process instructions without being
806242Sgblack@eecs.umich.edu * recompiled for multiple ISAs.
816242Sgblack@eecs.umich.edu */
826242Sgblack@eecs.umich.educlass StaticInstBase : public RefCounted
836242Sgblack@eecs.umich.edu{
846735Sgblack@eecs.umich.edu  public:
856242Sgblack@eecs.umich.edu
866242Sgblack@eecs.umich.edu    /// Set of boolean static instruction properties.
876735Sgblack@eecs.umich.edu    ///
886242Sgblack@eecs.umich.edu    /// Notes:
896242Sgblack@eecs.umich.edu    /// - The IsInteger and IsFloating flags are based on the class of
906242Sgblack@eecs.umich.edu    /// registers accessed by the instruction.  Although most
916242Sgblack@eecs.umich.edu    /// instructions will have exactly one of these two flags set, it
926242Sgblack@eecs.umich.edu    /// is possible for an instruction to have neither (e.g., direct
936242Sgblack@eecs.umich.edu    /// unconditional branches, memory barriers) or both (e.g., an
946242Sgblack@eecs.umich.edu    /// FP/int conversion).
956735Sgblack@eecs.umich.edu    /// - If IsMemRef is set, then exactly one of IsLoad or IsStore
966735Sgblack@eecs.umich.edu    /// will be set.
976735Sgblack@eecs.umich.edu    /// - If IsControl is set, then exactly one of IsDirectControl or
986735Sgblack@eecs.umich.edu    /// IsIndirect Control will be set, and exactly one of
996735Sgblack@eecs.umich.edu    /// IsCondControl or IsUncondControl will be set.
1006735Sgblack@eecs.umich.edu    /// - IsSerializing, IsMemBarrier, and IsWriteBarrier are
1016735Sgblack@eecs.umich.edu    /// implemented as flags since in the current model there's no
1026735Sgblack@eecs.umich.edu    /// other way for instructions to inject behavior into the
1036735Sgblack@eecs.umich.edu    /// pipeline outside of fetch.  Once we go to an exec-in-exec CPU
1046735Sgblack@eecs.umich.edu    /// model we should be able to get rid of these flags and
1056735Sgblack@eecs.umich.edu    /// implement this behavior via the execute() methods.
1066735Sgblack@eecs.umich.edu    ///
1076735Sgblack@eecs.umich.edu    enum Flags {
1086735Sgblack@eecs.umich.edu        IsNop,          ///< Is a no-op (no effect at all).
1096735Sgblack@eecs.umich.edu
1106735Sgblack@eecs.umich.edu        IsInteger,      ///< References integer regs.
1116735Sgblack@eecs.umich.edu        IsFloating,     ///< References FP regs.
1126735Sgblack@eecs.umich.edu
1136735Sgblack@eecs.umich.edu        IsMemRef,       ///< References memory (load, store, or prefetch).
1146735Sgblack@eecs.umich.edu        IsLoad,         ///< Reads from memory (load or prefetch).
1156735Sgblack@eecs.umich.edu        IsStore,        ///< Writes to memory.
1166735Sgblack@eecs.umich.edu        IsStoreConditional,    ///< Store conditional instruction.
1176735Sgblack@eecs.umich.edu        IsIndexed,      ///< Accesses memory with an indexed address computation
1186735Sgblack@eecs.umich.edu        IsInstPrefetch, ///< Instruction-cache prefetch.
1196735Sgblack@eecs.umich.edu        IsDataPrefetch, ///< Data-cache prefetch.
1206242Sgblack@eecs.umich.edu        IsCopy,         ///< Fast Cache block copy
1216242Sgblack@eecs.umich.edu
1226242Sgblack@eecs.umich.edu        IsControl,              ///< Control transfer instruction.
123        IsDirectControl,        ///< PC relative control transfer.
124        IsIndirectControl,      ///< Register indirect control transfer.
125        IsCondControl,          ///< Conditional control transfer.
126        IsUncondControl,        ///< Unconditional control transfer.
127        IsCall,                 ///< Subroutine call.
128        IsReturn,               ///< Subroutine return.
129
130        IsCondDelaySlot,///< Conditional Delay-Slot Instruction
131
132        IsThreadSync,   ///< Thread synchronization operation.
133
134        IsSerializing,  ///< Serializes pipeline: won't execute until all
135                        /// older instructions have committed.
136        IsSerializeBefore,
137        IsSerializeAfter,
138        IsMemBarrier,   ///< Is a memory barrier
139        IsWriteBarrier, ///< Is a write barrier
140        IsReadBarrier,  ///< Is a read barrier
141        IsERET, /// <- Causes the IFU to stall (MIPS ISA)
142
143        IsNonSpeculative, ///< Should not be executed speculatively
144        IsQuiesce,      ///< Is a quiesce instruction
145
146        IsIprAccess,    ///< Accesses IPRs
147        IsUnverifiable, ///< Can't be verified by a checker
148
149        IsSyscall,      ///< Causes a system call to be emulated in syscall
150                        /// emulation mode.
151
152        //Flags for microcode
153        IsMacroop,      ///< Is a macroop containing microops
154        IsMicroop,      ///< Is a microop
155        IsDelayedCommit,        ///< This microop doesn't commit right away
156        IsLastMicroop,  ///< This microop ends a microop sequence
157        IsFirstMicroop, ///< This microop begins a microop sequence
158        //This flag doesn't do anything yet
159        IsMicroBranch,  ///< This microop branches within the microcode for a macroop
160        IsDspOp,
161        IsSquashAfter, ///< Squash all uncommitted state after executed
162        NumFlags
163    };
164
165  protected:
166
167    /// Flag values for this instruction.
168    std::bitset<NumFlags> flags;
169
170    /// See opClass().
171    OpClass _opClass;
172
173    /// See numSrcRegs().
174    int8_t _numSrcRegs;
175
176    /// See numDestRegs().
177    int8_t _numDestRegs;
178
179    /// The following are used to track physical register usage
180    /// for machines with separate int & FP reg files.
181    //@{
182    int8_t _numFPDestRegs;
183    int8_t _numIntDestRegs;
184    //@}
185
186    /// Constructor.
187    /// It's important to initialize everything here to a sane
188    /// default, since the decoder generally only overrides
189    /// the fields that are meaningful for the particular
190    /// instruction.
191    StaticInstBase(OpClass __opClass)
192        : _opClass(__opClass), _numSrcRegs(0), _numDestRegs(0),
193          _numFPDestRegs(0), _numIntDestRegs(0)
194    {
195    }
196
197  public:
198
199    /// @name Register information.
200    /// The sum of numFPDestRegs() and numIntDestRegs() equals
201    /// numDestRegs().  The former two functions are used to track
202    /// physical register usage for machines with separate int & FP
203    /// reg files.
204    //@{
205    /// Number of source registers.
206    int8_t numSrcRegs()  const { return _numSrcRegs; }
207    /// Number of destination registers.
208    int8_t numDestRegs() const { return _numDestRegs; }
209    /// Number of floating-point destination regs.
210    int8_t numFPDestRegs()  const { return _numFPDestRegs; }
211    /// Number of integer destination regs.
212    int8_t numIntDestRegs() const { return _numIntDestRegs; }
213    //@}
214
215    /// @name Flag accessors.
216    /// These functions are used to access the values of the various
217    /// instruction property flags.  See StaticInstBase::Flags for descriptions
218    /// of the individual flags.
219    //@{
220
221    bool isNop()          const { return flags[IsNop]; }
222
223    bool isMemRef()       const { return flags[IsMemRef]; }
224    bool isLoad()         const { return flags[IsLoad]; }
225    bool isStore()        const { return flags[IsStore]; }
226    bool isStoreConditional()     const { return flags[IsStoreConditional]; }
227    bool isInstPrefetch() const { return flags[IsInstPrefetch]; }
228    bool isDataPrefetch() const { return flags[IsDataPrefetch]; }
229    bool isPrefetch()     const { return isInstPrefetch() ||
230                                         isDataPrefetch(); }
231    bool isCopy()         const { return flags[IsCopy];}
232
233    bool isInteger()      const { return flags[IsInteger]; }
234    bool isFloating()     const { return flags[IsFloating]; }
235
236    bool isControl()      const { return flags[IsControl]; }
237    bool isCall()         const { return flags[IsCall]; }
238    bool isReturn()       const { return flags[IsReturn]; }
239    bool isDirectCtrl()   const { return flags[IsDirectControl]; }
240    bool isIndirectCtrl() const { return flags[IsIndirectControl]; }
241    bool isCondCtrl()     const { return flags[IsCondControl]; }
242    bool isUncondCtrl()   const { return flags[IsUncondControl]; }
243    bool isCondDelaySlot() const { return flags[IsCondDelaySlot]; }
244
245    bool isThreadSync()   const { return flags[IsThreadSync]; }
246    bool isSerializing()  const { return flags[IsSerializing] ||
247                                      flags[IsSerializeBefore] ||
248                                      flags[IsSerializeAfter]; }
249    bool isSerializeBefore() const { return flags[IsSerializeBefore]; }
250    bool isSerializeAfter() const { return flags[IsSerializeAfter]; }
251    bool isSquashAfter() const { return flags[IsSquashAfter]; }
252    bool isMemBarrier()   const { return flags[IsMemBarrier]; }
253    bool isWriteBarrier() const { return flags[IsWriteBarrier]; }
254    bool isNonSpeculative() const { return flags[IsNonSpeculative]; }
255    bool isQuiesce() const { return flags[IsQuiesce]; }
256    bool isIprAccess() const { return flags[IsIprAccess]; }
257    bool isUnverifiable() const { return flags[IsUnverifiable]; }
258    bool isSyscall() const { return flags[IsSyscall]; }
259    bool isMacroop() const { return flags[IsMacroop]; }
260    bool isMicroop() const { return flags[IsMicroop]; }
261    bool isDelayedCommit() const { return flags[IsDelayedCommit]; }
262    bool isLastMicroop() const { return flags[IsLastMicroop]; }
263    bool isFirstMicroop() const { return flags[IsFirstMicroop]; }
264    //This flag doesn't do anything yet
265    bool isMicroBranch() const { return flags[IsMicroBranch]; }
266    //@}
267
268    void setLastMicroop() { flags[IsLastMicroop] = true; }
269    void setDelayedCommit() { flags[IsDelayedCommit] = true; }
270    void setFlag(Flags f) { flags[f] = true; }
271
272    /// Operation class.  Used to select appropriate function unit in issue.
273    OpClass opClass()     const { return _opClass; }
274};
275
276
277// forward declaration
278class StaticInstPtr;
279
280/**
281 * Generic yet ISA-dependent static instruction class.
282 *
283 * This class builds on StaticInstBase, defining fields and interfaces
284 * that are generic across all ISAs but that differ in details
285 * according to the specific ISA being used.
286 */
287class StaticInst : public StaticInstBase
288{
289  public:
290
291    /// Binary machine instruction type.
292    typedef TheISA::MachInst MachInst;
293    /// Binary extended machine instruction type.
294    typedef TheISA::ExtMachInst ExtMachInst;
295    /// Logical register index type.
296    typedef TheISA::RegIndex RegIndex;
297
298    enum {
299        MaxInstSrcRegs = TheISA::MaxInstSrcRegs,        //< Max source regs
300        MaxInstDestRegs = TheISA::MaxInstDestRegs,      //< Max dest regs
301    };
302
303
304    /// Return logical index (architectural reg num) of i'th destination reg.
305    /// Only the entries from 0 through numDestRegs()-1 are valid.
306    RegIndex destRegIdx(int i) const { return _destRegIdx[i]; }
307
308    /// Return logical index (architectural reg num) of i'th source reg.
309    /// Only the entries from 0 through numSrcRegs()-1 are valid.
310    RegIndex srcRegIdx(int i)  const { return _srcRegIdx[i]; }
311
312    /// Pointer to a statically allocated "null" instruction object.
313    /// Used to give eaCompInst() and memAccInst() something to return
314    /// when called on non-memory instructions.
315    static StaticInstPtr nullStaticInstPtr;
316
317    /**
318     * Memory references only: returns "fake" instruction representing
319     * the effective address part of the memory operation.  Used to
320     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
321     * just the EA computation.
322     */
323    virtual const
324    StaticInstPtr &eaCompInst() const { return nullStaticInstPtr; }
325
326    /**
327     * Memory references only: returns "fake" instruction representing
328     * the memory access part of the memory operation.  Used to
329     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
330     * just the memory access (not the EA computation).
331     */
332    virtual const
333    StaticInstPtr &memAccInst() const { return nullStaticInstPtr; }
334
335    /// The binary machine instruction.
336    const ExtMachInst machInst;
337
338  protected:
339
340    /// See destRegIdx().
341    RegIndex _destRegIdx[MaxInstDestRegs];
342    /// See srcRegIdx().
343    RegIndex _srcRegIdx[MaxInstSrcRegs];
344
345    /**
346     * Base mnemonic (e.g., "add").  Used by generateDisassembly()
347     * methods.  Also useful to readily identify instructions from
348     * within the debugger when #cachedDisassembly has not been
349     * initialized.
350     */
351    const char *mnemonic;
352
353    /**
354     * String representation of disassembly (lazily evaluated via
355     * disassemble()).
356     */
357    mutable std::string *cachedDisassembly;
358
359    /**
360     * Internal function to generate disassembly string.
361     */
362    virtual std::string
363    generateDisassembly(Addr pc, const SymbolTable *symtab) const = 0;
364
365    /// Constructor.
366    StaticInst(const char *_mnemonic, ExtMachInst _machInst, OpClass __opClass)
367        : StaticInstBase(__opClass),
368          machInst(_machInst), mnemonic(_mnemonic), cachedDisassembly(0)
369    { }
370
371  public:
372    virtual ~StaticInst();
373
374/**
375 * The execute() signatures are auto-generated by scons based on the
376 * set of CPU models we are compiling in today.
377 */
378#include "cpu/static_inst_exec_sigs.hh"
379
380    virtual void advancePC(TheISA::PCState &pcState) const = 0;
381
382    /**
383     * Return the microop that goes with a particular micropc. This should
384     * only be defined/used in macroops which will contain microops
385     */
386    virtual StaticInstPtr fetchMicroop(MicroPC upc) const;
387
388    /**
389     * Return the target address for a PC-relative branch.
390     * Invalid if not a PC-relative branch (i.e. isDirectCtrl()
391     * should be true).
392     */
393    virtual TheISA::PCState branchTarget(const TheISA::PCState &pc) const;
394
395    /**
396     * Return the target address for an indirect branch (jump).  The
397     * register value is read from the supplied thread context, so
398     * the result is valid only if the thread context is about to
399     * execute the branch in question.  Invalid if not an indirect
400     * branch (i.e. isIndirectCtrl() should be true).
401     */
402    virtual TheISA::PCState branchTarget(ThreadContext *tc) const;
403
404    /**
405     * Return true if the instruction is a control transfer, and if so,
406     * return the target address as well.
407     */
408    bool hasBranchTarget(const TheISA::PCState &pc, ThreadContext *tc,
409                         TheISA::PCState &tgt) const;
410
411    /**
412     * Return string representation of disassembled instruction.
413     * The default version of this function will call the internal
414     * virtual generateDisassembly() function to get the string,
415     * then cache it in #cachedDisassembly.  If the disassembly
416     * should not be cached, this function should be overridden directly.
417     */
418    virtual const std::string &disassemble(Addr pc,
419        const SymbolTable *symtab = 0) const;
420
421    /// Decoded instruction cache type.
422    /// For now we're using a generic hash_map; this seems to work
423    /// pretty well.
424    typedef m5::hash_map<ExtMachInst, StaticInstPtr> DecodeCache;
425
426    /// A cache of decoded instruction objects.
427    static DecodeCache decodeCache;
428
429    /**
430     * Dump some basic stats on the decode cache hash map.
431     * Only gets called if DECODE_CACHE_HASH_STATS is defined.
432     */
433    static void dumpDecodeCacheStats();
434
435    /// Decode a machine instruction.
436    /// @param mach_inst The binary instruction to decode.
437    /// @retval A pointer to the corresponding StaticInst object.
438    //This is defined as inlined below.
439    static StaticInstPtr decode(ExtMachInst mach_inst, Addr addr);
440
441    /// Return name of machine instruction
442    std::string getName() { return mnemonic; }
443
444    /// Decoded instruction cache type, for address decoding.
445    /// A generic hash_map is used.
446    typedef m5::hash_map<Addr, AddrDecodePage *> AddrDecodeCache;
447
448    /// A cache of decoded instruction objects from addresses.
449    static AddrDecodeCache addrDecodeCache;
450
451    struct cacheElement
452    {
453        Addr page_addr;
454        AddrDecodePage *decodePage;
455
456        cacheElement() : decodePage(NULL) { }
457    };
458
459    /// An array of recently decoded instructions.
460    // might not use an array if there is only two elements
461    static struct cacheElement recentDecodes[2];
462
463    /// Updates the recently decoded instructions entries
464    /// @param page_addr The page address recently used.
465    /// @param decodePage Pointer to decoding page containing the decoded
466    ///                   instruction.
467    static inline void
468    updateCache(Addr page_addr, AddrDecodePage *decodePage)
469    {
470        recentDecodes[1].page_addr = recentDecodes[0].page_addr;
471        recentDecodes[1].decodePage = recentDecodes[0].decodePage;
472        recentDecodes[0].page_addr = page_addr;
473        recentDecodes[0].decodePage = decodePage;
474    }
475
476    /// Searches the decoded instruction cache for instruction decoding.
477    /// If it is not found, then we decode the instruction.
478    /// Otherwise, we get the instruction from the cache and move it into
479    /// the address-to-instruction decoding page.
480    /// @param mach_inst The binary instruction to decode.
481    /// @param addr The address that contained the binary instruction.
482    /// @param decodePage Pointer to decoding page containing the instruction.
483    /// @retval A pointer to the corresponding StaticInst object.
484    //This is defined as inlined below.
485    static StaticInstPtr searchCache(ExtMachInst mach_inst, Addr addr,
486                                     AddrDecodePage *decodePage);
487};
488
489typedef RefCountingPtr<StaticInstBase> StaticInstBasePtr;
490
491/// Reference-counted pointer to a StaticInst object.
492/// This type should be used instead of "StaticInst *" so that
493/// StaticInst objects can be properly reference-counted.
494class StaticInstPtr : public RefCountingPtr<StaticInst>
495{
496  public:
497    /// Constructor.
498    StaticInstPtr()
499        : RefCountingPtr<StaticInst>()
500    {
501    }
502
503    /// Conversion from "StaticInst *".
504    StaticInstPtr(StaticInst *p)
505        : RefCountingPtr<StaticInst>(p)
506    {
507    }
508
509    /// Copy constructor.
510    StaticInstPtr(const StaticInstPtr &r)
511        : RefCountingPtr<StaticInst>(r)
512    {
513    }
514
515    /// Construct directly from machine instruction.
516    /// Calls StaticInst::decode().
517    explicit StaticInstPtr(TheISA::ExtMachInst mach_inst, Addr addr)
518        : RefCountingPtr<StaticInst>(StaticInst::decode(mach_inst, addr))
519    {
520    }
521
522    /// Convert to pointer to StaticInstBase class.
523    operator const StaticInstBasePtr()
524    {
525        return this->get();
526    }
527};
528
529/// A page of a list of decoded instructions from an address.
530class AddrDecodePage
531{
532  typedef TheISA::ExtMachInst ExtMachInst;
533  protected:
534    StaticInstPtr instructions[TheISA::PageBytes];
535    bool valid[TheISA::PageBytes];
536    Addr lowerMask;
537
538  public:
539    /// Constructor
540    AddrDecodePage()
541    {
542        lowerMask = TheISA::PageBytes - 1;
543        memset(valid, 0, TheISA::PageBytes);
544    }
545
546    /// Checks if the instruction is already decoded and the machine
547    /// instruction in the cache matches the current machine instruction
548    /// related to the address
549    /// @param mach_inst The binary instruction to check
550    /// @param addr The address containing the instruction
551    bool
552    decoded(ExtMachInst mach_inst, Addr addr)
553    {
554        return (valid[addr & lowerMask] &&
555                (instructions[addr & lowerMask]->machInst == mach_inst));
556    }
557
558    /// Returns the instruction object. decoded should be called first
559    /// to check if the instruction is valid.
560    /// @param addr The address of the instruction.
561    /// @retval A pointer to the corresponding StaticInst object.
562    StaticInstPtr
563    getInst(Addr addr)
564    {
565        return instructions[addr & lowerMask];
566    }
567
568    /// Inserts a pointer to a StaticInst object into the list of decoded
569    /// instructions on the page.
570    /// @param addr The address of the instruction.
571    /// @param si A pointer to the corresponding StaticInst object.
572    void
573    insert(Addr addr, StaticInstPtr &si)
574    {
575        instructions[addr & lowerMask] = si;
576        valid[addr & lowerMask] = true;
577    }
578};
579
580
581inline StaticInstPtr
582StaticInst::decode(StaticInst::ExtMachInst mach_inst, Addr addr)
583{
584#ifdef DECODE_CACHE_HASH_STATS
585    // Simple stats on decode hash_map.  Turns out the default
586    // hash function is as good as anything I could come up with.
587    const int dump_every_n = 10000000;
588    static int decodes_til_dump = dump_every_n;
589
590    if (--decodes_til_dump == 0) {
591        dumpDecodeCacheStats();
592        decodes_til_dump = dump_every_n;
593    }
594#endif
595
596    Addr page_addr = addr & ~(TheISA::PageBytes - 1);
597
598    // checks recently decoded addresses
599    if (recentDecodes[0].decodePage &&
600        page_addr == recentDecodes[0].page_addr) {
601        if (recentDecodes[0].decodePage->decoded(mach_inst, addr))
602            return recentDecodes[0].decodePage->getInst(addr);
603
604        return searchCache(mach_inst, addr, recentDecodes[0].decodePage);
605    }
606
607    if (recentDecodes[1].decodePage &&
608        page_addr == recentDecodes[1].page_addr) {
609        if (recentDecodes[1].decodePage->decoded(mach_inst, addr))
610            return recentDecodes[1].decodePage->getInst(addr);
611
612        return searchCache(mach_inst, addr, recentDecodes[1].decodePage);
613    }
614
615    // searches the page containing the address to decode
616    AddrDecodeCache::iterator iter = addrDecodeCache.find(page_addr);
617    if (iter != addrDecodeCache.end()) {
618        updateCache(page_addr, iter->second);
619        if (iter->second->decoded(mach_inst, addr))
620            return iter->second->getInst(addr);
621
622        return searchCache(mach_inst, addr, iter->second);
623    }
624
625    // creates a new object for a page of decoded instructions
626    AddrDecodePage *decodePage = new AddrDecodePage;
627    addrDecodeCache[page_addr] = decodePage;
628    updateCache(page_addr, decodePage);
629    return searchCache(mach_inst, addr, decodePage);
630}
631
632inline StaticInstPtr
633StaticInst::searchCache(ExtMachInst mach_inst, Addr addr,
634                        AddrDecodePage *decodePage)
635{
636    DecodeCache::iterator iter = decodeCache.find(mach_inst);
637    if (iter != decodeCache.end()) {
638        decodePage->insert(addr, iter->second);
639        return iter->second;
640    }
641
642    StaticInstPtr si = TheISA::decodeInst(mach_inst);
643    decodePage->insert(addr, si);
644    decodeCache[mach_inst] = si;
645    return si;
646}
647
648#endif // __CPU_STATIC_INST_HH__
649