static_inst.hh revision 716
1/*
2 * Copyright (c) 2003 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#ifndef __STATIC_INST_HH__
30#define __STATIC_INST_HH__
31
32#include <bitset>
33#include <string>
34
35#include "sim/host.hh"
36#include "base/hashmap.hh"
37#include "base/refcnt.hh"
38
39#include "cpu/full_cpu/op_class.hh"
40#include "targetarch/isa_traits.hh"
41
42// forward declarations
43class ExecContext;
44class DynInst;
45typedef DynInst FullCPUExecContext;
46class FastCPU;
47typedef FastCPU FastCPUExecContext;
48class SimpleCPU;
49typedef SimpleCPU SimpleCPUExecContext;
50class SymbolTable;
51
52namespace Trace {
53    class InstRecord;
54}
55
56/**
57 * Base, ISA-independent static instruction class.
58 *
59 * The main component of this class is the vector of flags and the
60 * associated methods for reading them.  Any object that can rely
61 * solely on these flags can process instructions without being
62 * recompiled for multiple ISAs.
63 */
64class StaticInstBase : public RefCounted
65{
66  protected:
67
68    /// Set of boolean static instruction properties.
69    ///
70    /// Notes:
71    /// - The IsInteger and IsFloating flags are based on the class of
72    /// registers accessed by the instruction.  Although most
73    /// instructions will have exactly one of these two flags set, it
74    /// is possible for an instruction to have neither (e.g., direct
75    /// unconditional branches, memory barriers) or both (e.g., an
76    /// FP/int conversion).
77    /// - If IsMemRef is set, then exactly one of IsLoad or IsStore
78    /// will be set.  Prefetches are marked as IsLoad, even if they
79    /// prefetch exclusive copies.
80    /// - If IsControl is set, then exactly one of IsDirectControl or
81    /// IsIndirect Control will be set, and exactly one of
82    /// IsCondControl or IsUncondControl will be set.
83    /// - IsSerializing, IsMemBarrier, and IsWriteBarrier are
84    /// implemented as flags since in the current model there's no
85    /// other way for instructions to inject behavior into the
86    /// pipeline outside of fetch.  Once we go to an exec-in-exec CPU
87    /// model we should be able to get rid of these flags and
88    /// implement this behavior via the execute() methods.
89    ///
90    enum Flags {
91        IsNop,		///< Is a no-op (no effect at all).
92
93        IsInteger,	///< References integer regs.
94        IsFloating,	///< References FP regs.
95
96        IsMemRef,	///< References memory (load, store, or prefetch).
97        IsLoad,		///< Reads from memory (load or prefetch).
98        IsStore,	///< Writes to memory.
99        IsInstPrefetch,	///< Instruction-cache prefetch.
100        IsDataPrefetch,	///< Data-cache prefetch.
101        IsCopy,         ///< Fast Cache block copy
102
103        IsControl,		///< Control transfer instruction.
104        IsDirectControl,	///< PC relative control transfer.
105        IsIndirectControl,	///< Register indirect control transfer.
106        IsCondControl,		///< Conditional control transfer.
107        IsUncondControl,	///< Unconditional control transfer.
108        IsCall,			///< Subroutine call.
109        IsReturn,		///< Subroutine return.
110
111        IsThreadSync,	///< Thread synchronization operation.
112
113        IsSerializing,	///< Serializes pipeline: won't until all
114                        /// older instructions have committed.
115        IsMemBarrier,	///< Is a memory barrier
116        IsWriteBarrier,	///< Is a write barrier
117
118        NumFlags
119    };
120
121    /// Flag values for this instruction.
122    std::bitset<NumFlags> flags;
123
124    /// See opClass().
125    OpClass _opClass;
126
127    /// See numSrcRegs().
128    int8_t _numSrcRegs;
129
130    /// See numDestRegs().
131    int8_t _numDestRegs;
132
133    /// The following are used to track physical register usage
134    /// for machines with separate int & FP reg files.
135    //@{
136    int8_t _numFPDestRegs;
137    int8_t _numIntDestRegs;
138    //@}
139
140    /// Constructor.
141    /// It's important to initialize everything here to a sane
142    /// default, since the decoder generally only overrides
143    /// the fields that are meaningful for the particular
144    /// instruction.
145    StaticInstBase(OpClass __opClass)
146        : _opClass(__opClass), _numSrcRegs(0), _numDestRegs(0),
147          _numFPDestRegs(0), _numIntDestRegs(0)
148    {
149    }
150
151  public:
152
153    /// @name Register information.
154    /// The sum of numFPDestRegs() and numIntDestRegs() equals
155    /// numDestRegs().  The former two functions are used to track
156    /// physical register usage for machines with separate int & FP
157    /// reg files.
158    //@{
159    /// Number of source registers.
160    int8_t numSrcRegs()  const { return _numSrcRegs; }
161    /// Number of destination registers.
162    int8_t numDestRegs() const { return _numDestRegs; }
163    /// Number of floating-point destination regs.
164    int8_t numFPDestRegs()  const { return _numFPDestRegs; }
165    /// Number of integer destination regs.
166    int8_t numIntDestRegs() const { return _numIntDestRegs; }
167    //@}
168
169    /// @name Flag accessors.
170    /// These functions are used to access the values of the various
171    /// instruction property flags.  See StaticInstBase::Flags for descriptions
172    /// of the individual flags.
173    //@{
174
175    bool isNop() 	  const { return flags[IsNop]; }
176
177    bool isMemRef()    	  const { return flags[IsMemRef]; }
178    bool isLoad()	  const { return flags[IsLoad]; }
179    bool isStore()	  const { return flags[IsStore]; }
180    bool isInstPrefetch() const { return flags[IsInstPrefetch]; }
181    bool isDataPrefetch() const { return flags[IsDataPrefetch]; }
182    bool isCopy()         const { return flags[IsCopy];}
183
184    bool isInteger()	  const { return flags[IsInteger]; }
185    bool isFloating()	  const { return flags[IsFloating]; }
186
187    bool isControl()	  const { return flags[IsControl]; }
188    bool isCall()	  const { return flags[IsCall]; }
189    bool isReturn()	  const { return flags[IsReturn]; }
190    bool isDirectCtrl()	  const { return flags[IsDirectControl]; }
191    bool isIndirectCtrl() const { return flags[IsIndirectControl]; }
192    bool isCondCtrl()	  const { return flags[IsCondControl]; }
193    bool isUncondCtrl()	  const { return flags[IsUncondControl]; }
194
195    bool isThreadSync()   const { return flags[IsThreadSync]; }
196    bool isSerializing()  const { return flags[IsSerializing]; }
197    bool isMemBarrier()   const { return flags[IsMemBarrier]; }
198    bool isWriteBarrier() const { return flags[IsWriteBarrier]; }
199    //@}
200
201    /// Operation class.  Used to select appropriate function unit in issue.
202    OpClass opClass()     const { return _opClass; }
203};
204
205
206// forward declaration
207template <class ISA>
208class StaticInstPtr;
209
210/**
211 * Generic yet ISA-dependent static instruction class.
212 *
213 * This class builds on StaticInstBase, defining fields and interfaces
214 * that are generic across all ISAs but that differ in details
215 * according to the specific ISA being used.
216 */
217template <class ISA>
218class StaticInst : public StaticInstBase
219{
220  public:
221
222    /// Binary machine instruction type.
223    typedef typename ISA::MachInst MachInst;
224    /// Memory address type.
225    typedef typename ISA::Addr	   Addr;
226    /// Logical register index type.
227    typedef typename ISA::RegIndex RegIndex;
228
229    enum {
230        MaxInstSrcRegs = ISA::MaxInstSrcRegs,	//< Max source regs
231        MaxInstDestRegs = ISA::MaxInstDestRegs,	//< Max dest regs
232    };
233
234
235    /// Return logical index (architectural reg num) of i'th destination reg.
236    /// Only the entries from 0 through numDestRegs()-1 are valid.
237    RegIndex destRegIdx(int i) const { return _destRegIdx[i]; }
238
239    /// Return logical index (architectural reg num) of i'th source reg.
240    /// Only the entries from 0 through numSrcRegs()-1 are valid.
241    RegIndex srcRegIdx(int i)  const { return _srcRegIdx[i]; }
242
243    /// Pointer to a statically allocated "null" instruction object.
244    /// Used to give eaCompInst() and memAccInst() something to return
245    /// when called on non-memory instructions.
246    static StaticInstPtr<ISA> nullStaticInstPtr;
247
248    /**
249     * Memory references only: returns "fake" instruction representing
250     * the effective address part of the memory operation.  Used to
251     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
252     * just the EA computation.
253     */
254    virtual StaticInstPtr<ISA> eaCompInst() { return nullStaticInstPtr; }
255
256    /**
257     * Memory references only: returns "fake" instruction representing
258     * the memory access part of the memory operation.  Used to
259     * obtain the dependence info (numSrcRegs and srcRegIdx[]) for
260     * just the memory access (not the EA computation).
261     */
262    virtual StaticInstPtr<ISA> memAccInst() { return nullStaticInstPtr; }
263
264    /// The binary machine instruction.
265    const MachInst machInst;
266
267  protected:
268
269    /// See destRegIdx().
270    RegIndex _destRegIdx[MaxInstDestRegs];
271    /// See srcRegIdx().
272    RegIndex _srcRegIdx[MaxInstSrcRegs];
273
274    /**
275     * Base mnemonic (e.g., "add").  Used by generateDisassembly()
276     * methods.  Also useful to readily identify instructions from
277     * within the debugger when #cachedDisassembly has not been
278     * initialized.
279     */
280    const char *mnemonic;
281
282    /**
283     * String representation of disassembly (lazily evaluated via
284     * disassemble()).
285     */
286    std::string *cachedDisassembly;
287
288    /**
289     * Internal function to generate disassembly string.
290     */
291    virtual std::string generateDisassembly(Addr pc,
292                                            const SymbolTable *symtab) = 0;
293
294    /// Constructor.
295    StaticInst(const char *_mnemonic, MachInst _machInst, OpClass __opClass)
296        : StaticInstBase(__opClass),
297          machInst(_machInst), mnemonic(_mnemonic), cachedDisassembly(0)
298    {
299    }
300
301  public:
302
303    virtual ~StaticInst()
304    {
305        if (cachedDisassembly)
306            delete cachedDisassembly;
307    }
308
309    /**
310     * Execute this instruction under SimpleCPU model.
311     */
312    virtual Fault execute(SimpleCPUExecContext *xc,
313                          Trace::InstRecord *traceData) = 0;
314
315    /**
316     * Execute this instruction under FastCPU model.
317     */
318    virtual Fault execute(FastCPUExecContext *xc,
319                          Trace::InstRecord *traceData) = 0;
320
321    /**
322     * Execute this instruction under detailed FullCPU model.
323     */
324    virtual Fault execute(FullCPUExecContext *xc,
325                          Trace::InstRecord *traceData) = 0;
326
327    /**
328     * Return the target address for a PC-relative branch.
329     * Invalid if not a PC-relative branch (i.e. isDirectCtrl()
330     * should be true).
331     */
332    virtual Addr branchTarget(Addr branchPC) const
333    {
334        panic("StaticInst::branchTarget() called on instruction "
335              "that is not a PC-relative branch.");
336    }
337
338    /**
339     * Return the target address for an indirect branch (jump).  The
340     * register value is read from the supplied execution context, so
341     * the result is valid only if the execution context is about to
342     * execute the branch in question.  Invalid if not an indirect
343     * branch (i.e. isIndirectCtrl() should be true).
344     */
345    virtual Addr branchTarget(ExecContext *xc) const
346    {
347        panic("StaticInst::branchTarget() called on instruction "
348              "that is not an indirect branch.");
349    }
350
351    /**
352     * Return true if the instruction is a control transfer, and if so,
353     * return the target address as well.
354     */
355    bool hasBranchTarget(Addr pc, ExecContext *xc, Addr &tgt);
356
357    /**
358     * Return string representation of disassembled instruction.
359     * The default version of this function will call the internal
360     * virtual generateDisassembly() function to get the string,
361     * then cache it in #cachedDisassembly.  If the disassembly
362     * should not be cached, this function should be overridden directly.
363     */
364    virtual const std::string &disassemble(Addr pc,
365                                           const SymbolTable *symtab = 0)
366    {
367        if (!cachedDisassembly)
368            cachedDisassembly =
369                new std::string(generateDisassembly(pc, symtab));
370
371        return *cachedDisassembly;
372    }
373
374    /// Decoded instruction cache type.
375    /// For now we're using a generic hash_map; this seems to work
376    /// pretty well.
377    typedef m5::hash_map<MachInst, StaticInstPtr<ISA> > DecodeCache;
378
379    /// A cache of decoded instruction objects.
380    static DecodeCache decodeCache;
381
382    /**
383     * Dump some basic stats on the decode cache hash map.
384     * Only gets called if DECODE_CACHE_HASH_STATS is defined.
385     */
386    static void dumpDecodeCacheStats();
387
388    /// Decode a machine instruction.
389    /// @param mach_inst The binary instruction to decode.
390    /// @retval A pointer to the corresponding StaticInst object.
391    static
392    StaticInstPtr<ISA> decode(MachInst mach_inst)
393    {
394#ifdef DECODE_CACHE_HASH_STATS
395        // Simple stats on decode hash_map.  Turns out the default
396        // hash function is as good as anything I could come up with.
397        const int dump_every_n = 10000000;
398        static int decodes_til_dump = dump_every_n;
399
400        if (--decodes_til_dump == 0) {
401            dumpDecodeCacheStats();
402            decodes_til_dump = dump_every_n;
403        }
404#endif
405
406        typename DecodeCache::iterator iter = decodeCache.find(mach_inst);
407        if (iter != decodeCache.end()) {
408            return iter->second;
409        }
410
411        StaticInstPtr<ISA> si = ISA::decodeInst(mach_inst);
412        decodeCache[mach_inst] = si;
413        return si;
414    }
415};
416
417typedef RefCountingPtr<StaticInstBase> StaticInstBasePtr;
418
419/// Reference-counted pointer to a StaticInst object.
420/// This type should be used instead of "StaticInst<ISA> *" so that
421/// StaticInst objects can be properly reference-counted.
422template <class ISA>
423class StaticInstPtr : public RefCountingPtr<StaticInst<ISA> >
424{
425  public:
426    /// Constructor.
427    StaticInstPtr()
428        : RefCountingPtr<StaticInst<ISA> >()
429    {
430    }
431
432    /// Conversion from "StaticInst<ISA> *".
433    StaticInstPtr(StaticInst<ISA> *p)
434        : RefCountingPtr<StaticInst<ISA> >(p)
435    {
436    }
437
438    /// Copy constructor.
439    StaticInstPtr(const StaticInstPtr &r)
440        : RefCountingPtr<StaticInst<ISA> >(r)
441    {
442    }
443
444    /// Construct directly from machine instruction.
445    /// Calls StaticInst<ISA>::decode().
446    StaticInstPtr(typename ISA::MachInst mach_inst)
447        : RefCountingPtr<StaticInst<ISA> >(StaticInst<ISA>::decode(mach_inst))
448    {
449    }
450
451    /// Convert to pointer to StaticInstBase class.
452    operator const StaticInstBasePtr()
453    {
454        return get();
455    }
456};
457
458#endif // __STATIC_INST_HH__
459