base_dyn_inst.hh revision 7944
1/*
2 * Copyright (c) 2011 ARM Limited
3 * All rights reserved.
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * Copyright (c) 2009 The University of Edinburgh
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 *          Timothy M. Jones
43 */
44
45#ifndef __CPU_BASE_DYN_INST_HH__
46#define __CPU_BASE_DYN_INST_HH__
47
48#include <bitset>
49#include <list>
50#include <string>
51
52#include "arch/faults.hh"
53#include "arch/utility.hh"
54#include "base/fast_alloc.hh"
55#include "base/trace.hh"
56#include "config/full_system.hh"
57#include "config/the_isa.hh"
58#include "cpu/o3/comm.hh"
59#include "cpu/exetrace.hh"
60#include "cpu/inst_seq.hh"
61#include "cpu/op_class.hh"
62#include "cpu/static_inst.hh"
63#include "cpu/translation.hh"
64#include "mem/packet.hh"
65#include "sim/byteswap.hh"
66#include "sim/system.hh"
67#include "sim/tlb.hh"
68
69/**
70 * @file
71 * Defines a dynamic instruction context.
72 */
73
74// Forward declaration.
75class StaticInstPtr;
76
77template <class Impl>
78class BaseDynInst : public FastAlloc, public RefCounted
79{
80  public:
81    // Typedef for the CPU.
82    typedef typename Impl::CPUType ImplCPU;
83    typedef typename ImplCPU::ImplState ImplState;
84
85    // Logical register index type.
86    typedef TheISA::RegIndex RegIndex;
87    // Integer register type.
88    typedef TheISA::IntReg IntReg;
89    // Floating point register type.
90    typedef TheISA::FloatReg FloatReg;
91
92    // The DynInstPtr type.
93    typedef typename Impl::DynInstPtr DynInstPtr;
94
95    // The list of instructions iterator type.
96    typedef typename std::list<DynInstPtr>::iterator ListIt;
97
98    enum {
99        MaxInstSrcRegs = TheISA::MaxInstSrcRegs,        /// Max source regs
100        MaxInstDestRegs = TheISA::MaxInstDestRegs,      /// Max dest regs
101    };
102
103    /** The StaticInst used by this BaseDynInst. */
104    StaticInstPtr staticInst;
105
106    ////////////////////////////////////////////
107    //
108    // INSTRUCTION EXECUTION
109    //
110    ////////////////////////////////////////////
111    /** InstRecord that tracks this instructions. */
112    Trace::InstRecord *traceData;
113
114    void demapPage(Addr vaddr, uint64_t asn)
115    {
116        cpu->demapPage(vaddr, asn);
117    }
118    void demapInstPage(Addr vaddr, uint64_t asn)
119    {
120        cpu->demapPage(vaddr, asn);
121    }
122    void demapDataPage(Addr vaddr, uint64_t asn)
123    {
124        cpu->demapPage(vaddr, asn);
125    }
126
127    /**
128     * Does a read to a given address.
129     * @param addr The address to read.
130     * @param data The read's data is written into this parameter.
131     * @param flags The request's flags.
132     * @return Returns any fault due to the read.
133     */
134    template <class T>
135    Fault read(Addr addr, T &data, unsigned flags);
136
137    Fault readBytes(Addr addr, uint8_t *data, unsigned size, unsigned flags);
138
139    /**
140     * Does a write to a given address.
141     * @param data The data to be written.
142     * @param addr The address to write to.
143     * @param flags The request's flags.
144     * @param res The result of the write (for load locked/store conditionals).
145     * @return Returns any fault due to the write.
146     */
147    template <class T>
148    Fault write(T data, Addr addr, unsigned flags, uint64_t *res);
149
150    Fault writeBytes(uint8_t *data, unsigned size,
151                     Addr addr, unsigned flags, uint64_t *res);
152
153    /** Splits a request in two if it crosses a dcache block. */
154    void splitRequest(RequestPtr req, RequestPtr &sreqLow,
155                      RequestPtr &sreqHigh);
156
157    /** Initiate a DTB address translation. */
158    void initiateTranslation(RequestPtr req, RequestPtr sreqLow,
159                             RequestPtr sreqHigh, uint64_t *res,
160                             BaseTLB::Mode mode);
161
162    /** Finish a DTB address translation. */
163    void finishTranslation(WholeTranslationState *state);
164
165    /** True if the DTB address translation has started. */
166    bool translationStarted;
167
168    /** True if the DTB address translation has completed. */
169    bool translationCompleted;
170
171    /**
172     * Returns true if the DTB address translation is being delayed due to a hw
173     * page table walk.
174     */
175    bool isTranslationDelayed() const
176    {
177        return (translationStarted && !translationCompleted);
178    }
179
180    /**
181     * Saved memory requests (needed when the DTB address translation is
182     * delayed due to a hw page table walk).
183     */
184    RequestPtr savedReq;
185    RequestPtr savedSreqLow;
186    RequestPtr savedSreqHigh;
187
188    /** @todo: Consider making this private. */
189  public:
190    /** The sequence number of the instruction. */
191    InstSeqNum seqNum;
192
193    enum Status {
194        IqEntry,                 /// Instruction is in the IQ
195        RobEntry,                /// Instruction is in the ROB
196        LsqEntry,                /// Instruction is in the LSQ
197        Completed,               /// Instruction has completed
198        ResultReady,             /// Instruction has its result
199        CanIssue,                /// Instruction can issue and execute
200        Issued,                  /// Instruction has issued
201        Executed,                /// Instruction has executed
202        CanCommit,               /// Instruction can commit
203        AtCommit,                /// Instruction has reached commit
204        Committed,               /// Instruction has committed
205        Squashed,                /// Instruction is squashed
206        SquashedInIQ,            /// Instruction is squashed in the IQ
207        SquashedInLSQ,           /// Instruction is squashed in the LSQ
208        SquashedInROB,           /// Instruction is squashed in the ROB
209        RecoverInst,             /// Is a recover instruction
210        BlockingInst,            /// Is a blocking instruction
211        ThreadsyncWait,          /// Is a thread synchronization instruction
212        SerializeBefore,         /// Needs to serialize on
213                                 /// instructions ahead of it
214        SerializeAfter,          /// Needs to serialize instructions behind it
215        SerializeHandled,        /// Serialization has been handled
216        NumStatus
217    };
218
219    /** The status of this BaseDynInst.  Several bits can be set. */
220    std::bitset<NumStatus> status;
221
222    /** The thread this instruction is from. */
223    ThreadID threadNumber;
224
225    /** data address space ID, for loads & stores. */
226    short asid;
227
228    /** How many source registers are ready. */
229    unsigned readyRegs;
230
231    /** Pointer to the Impl's CPU object. */
232    ImplCPU *cpu;
233
234    /** Pointer to the thread state. */
235    ImplState *thread;
236
237    /** The kind of fault this instruction has generated. */
238    Fault fault;
239
240    /** Pointer to the data for the memory access. */
241    uint8_t *memData;
242
243    /** The effective virtual address (lds & stores only). */
244    Addr effAddr;
245
246    /** Is the effective virtual address valid. */
247    bool effAddrValid;
248
249    /** The effective physical address. */
250    Addr physEffAddr;
251
252    /** Effective virtual address for a copy source. */
253    Addr copySrcEffAddr;
254
255    /** Effective physical address for a copy source. */
256    Addr copySrcPhysEffAddr;
257
258    /** The memory request flags (from translation). */
259    unsigned memReqFlags;
260
261    union Result {
262        uint64_t integer;
263//        float fp;
264        double dbl;
265    };
266
267    /** The result of the instruction; assumes for now that there's only one
268     *  destination register.
269     */
270    Result instResult;
271
272    /** Records changes to result? */
273    bool recordResult;
274
275    /** Did this instruction execute, or is it predicated false */
276    bool predicate;
277
278  protected:
279    /** PC state for this instruction. */
280    TheISA::PCState pc;
281
282    /** Predicted PC state after this instruction. */
283    TheISA::PCState predPC;
284
285    /** If this is a branch that was predicted taken */
286    bool predTaken;
287
288  public:
289
290#ifdef DEBUG
291    void dumpSNList();
292#endif
293
294    /** Whether or not the source register is ready.
295     *  @todo: Not sure this should be here vs the derived class.
296     */
297    bool _readySrcRegIdx[MaxInstSrcRegs];
298
299  protected:
300    /** Flattened register index of the destination registers of this
301     *  instruction.
302     */
303    TheISA::RegIndex _flatDestRegIdx[TheISA::MaxInstDestRegs];
304
305    /** Flattened register index of the source registers of this
306     *  instruction.
307     */
308    TheISA::RegIndex _flatSrcRegIdx[TheISA::MaxInstSrcRegs];
309
310    /** Physical register index of the destination registers of this
311     *  instruction.
312     */
313    PhysRegIndex _destRegIdx[TheISA::MaxInstDestRegs];
314
315    /** Physical register index of the source registers of this
316     *  instruction.
317     */
318    PhysRegIndex _srcRegIdx[TheISA::MaxInstSrcRegs];
319
320    /** Physical register index of the previous producers of the
321     *  architected destinations.
322     */
323    PhysRegIndex _prevDestRegIdx[TheISA::MaxInstDestRegs];
324
325  public:
326
327    /** Returns the physical register index of the i'th destination
328     *  register.
329     */
330    PhysRegIndex renamedDestRegIdx(int idx) const
331    {
332        return _destRegIdx[idx];
333    }
334
335    /** Returns the physical register index of the i'th source register. */
336    PhysRegIndex renamedSrcRegIdx(int idx) const
337    {
338        return _srcRegIdx[idx];
339    }
340
341    /** Returns the flattened register index of the i'th destination
342     *  register.
343     */
344    TheISA::RegIndex flattenedDestRegIdx(int idx) const
345    {
346        return _flatDestRegIdx[idx];
347    }
348
349    /** Returns the flattened register index of the i'th source register */
350    TheISA::RegIndex flattenedSrcRegIdx(int idx) const
351    {
352        return _flatSrcRegIdx[idx];
353    }
354
355    /** Returns the physical register index of the previous physical register
356     *  that remapped to the same logical register index.
357     */
358    PhysRegIndex prevDestRegIdx(int idx) const
359    {
360        return _prevDestRegIdx[idx];
361    }
362
363    /** Renames a destination register to a physical register.  Also records
364     *  the previous physical register that the logical register mapped to.
365     */
366    void renameDestReg(int idx,
367                       PhysRegIndex renamed_dest,
368                       PhysRegIndex previous_rename)
369    {
370        _destRegIdx[idx] = renamed_dest;
371        _prevDestRegIdx[idx] = previous_rename;
372    }
373
374    /** Renames a source logical register to the physical register which
375     *  has/will produce that logical register's result.
376     *  @todo: add in whether or not the source register is ready.
377     */
378    void renameSrcReg(int idx, PhysRegIndex renamed_src)
379    {
380        _srcRegIdx[idx] = renamed_src;
381    }
382
383    /** Flattens a source architectural register index into a logical index.
384     */
385    void flattenSrcReg(int idx, TheISA::RegIndex flattened_src)
386    {
387        _flatSrcRegIdx[idx] = flattened_src;
388    }
389
390    /** Flattens a destination architectural register index into a logical
391     * index.
392     */
393    void flattenDestReg(int idx, TheISA::RegIndex flattened_dest)
394    {
395        _flatDestRegIdx[idx] = flattened_dest;
396    }
397    /** BaseDynInst constructor given a binary instruction.
398     *  @param staticInst A StaticInstPtr to the underlying instruction.
399     *  @param pc The PC state for the instruction.
400     *  @param predPC The predicted next PC state for the instruction.
401     *  @param seq_num The sequence number of the instruction.
402     *  @param cpu Pointer to the instruction's CPU.
403     */
404    BaseDynInst(StaticInstPtr staticInst, TheISA::PCState pc,
405                TheISA::PCState predPC, InstSeqNum seq_num, ImplCPU *cpu);
406
407    /** BaseDynInst constructor given a binary instruction.
408     *  @param inst The binary instruction.
409     *  @param _pc The PC state for the instruction.
410     *  @param _predPC The predicted next PC state for the instruction.
411     *  @param seq_num The sequence number of the instruction.
412     *  @param cpu Pointer to the instruction's CPU.
413     */
414    BaseDynInst(TheISA::ExtMachInst inst, TheISA::PCState pc,
415                TheISA::PCState predPC, InstSeqNum seq_num, ImplCPU *cpu);
416
417    /** BaseDynInst constructor given a StaticInst pointer.
418     *  @param _staticInst The StaticInst for this BaseDynInst.
419     */
420    BaseDynInst(StaticInstPtr &_staticInst);
421
422    /** BaseDynInst destructor. */
423    ~BaseDynInst();
424
425  private:
426    /** Function to initialize variables in the constructors. */
427    void initVars();
428
429  public:
430    /** Dumps out contents of this BaseDynInst. */
431    void dump();
432
433    /** Dumps out contents of this BaseDynInst into given string. */
434    void dump(std::string &outstring);
435
436    /** Read this CPU's ID. */
437    int cpuId() { return cpu->cpuId(); }
438
439    /** Read this context's system-wide ID **/
440    int contextId() { return thread->contextId(); }
441
442    /** Returns the fault type. */
443    Fault getFault() { return fault; }
444
445    /** Checks whether or not this instruction has had its branch target
446     *  calculated yet.  For now it is not utilized and is hacked to be
447     *  always false.
448     *  @todo: Actually use this instruction.
449     */
450    bool doneTargCalc() { return false; }
451
452    /** Set the predicted target of this current instruction. */
453    void setPredTarg(const TheISA::PCState &_predPC)
454    {
455        predPC = _predPC;
456    }
457
458    const TheISA::PCState &readPredTarg() { return predPC; }
459
460    /** Returns the predicted PC immediately after the branch. */
461    Addr predInstAddr() { return predPC.instAddr(); }
462
463    /** Returns the predicted PC two instructions after the branch */
464    Addr predNextInstAddr() { return predPC.nextInstAddr(); }
465
466    /** Returns the predicted micro PC after the branch */
467    Addr predMicroPC() { return predPC.microPC(); }
468
469    /** Returns whether the instruction was predicted taken or not. */
470    bool readPredTaken()
471    {
472        return predTaken;
473    }
474
475    void setPredTaken(bool predicted_taken)
476    {
477        predTaken = predicted_taken;
478    }
479
480    /** Returns whether the instruction mispredicted. */
481    bool mispredicted()
482    {
483        TheISA::PCState tempPC = pc;
484        TheISA::advancePC(tempPC, staticInst);
485        return !(tempPC == predPC);
486    }
487
488    //
489    //  Instruction types.  Forward checks to StaticInst object.
490    //
491    bool isNop()          const { return staticInst->isNop(); }
492    bool isMemRef()       const { return staticInst->isMemRef(); }
493    bool isLoad()         const { return staticInst->isLoad(); }
494    bool isStore()        const { return staticInst->isStore(); }
495    bool isStoreConditional() const
496    { return staticInst->isStoreConditional(); }
497    bool isInstPrefetch() const { return staticInst->isInstPrefetch(); }
498    bool isDataPrefetch() const { return staticInst->isDataPrefetch(); }
499    bool isCopy()         const { return staticInst->isCopy(); }
500    bool isInteger()      const { return staticInst->isInteger(); }
501    bool isFloating()     const { return staticInst->isFloating(); }
502    bool isControl()      const { return staticInst->isControl(); }
503    bool isCall()         const { return staticInst->isCall(); }
504    bool isReturn()       const { return staticInst->isReturn(); }
505    bool isDirectCtrl()   const { return staticInst->isDirectCtrl(); }
506    bool isIndirectCtrl() const { return staticInst->isIndirectCtrl(); }
507    bool isCondCtrl()     const { return staticInst->isCondCtrl(); }
508    bool isUncondCtrl()   const { return staticInst->isUncondCtrl(); }
509    bool isCondDelaySlot() const { return staticInst->isCondDelaySlot(); }
510    bool isThreadSync()   const { return staticInst->isThreadSync(); }
511    bool isSerializing()  const { return staticInst->isSerializing(); }
512    bool isSerializeBefore() const
513    { return staticInst->isSerializeBefore() || status[SerializeBefore]; }
514    bool isSerializeAfter() const
515    { return staticInst->isSerializeAfter() || status[SerializeAfter]; }
516    bool isSquashAfter() const { return staticInst->isSquashAfter(); }
517    bool isMemBarrier()   const { return staticInst->isMemBarrier(); }
518    bool isWriteBarrier() const { return staticInst->isWriteBarrier(); }
519    bool isNonSpeculative() const { return staticInst->isNonSpeculative(); }
520    bool isQuiesce() const { return staticInst->isQuiesce(); }
521    bool isIprAccess() const { return staticInst->isIprAccess(); }
522    bool isUnverifiable() const { return staticInst->isUnverifiable(); }
523    bool isSyscall() const { return staticInst->isSyscall(); }
524    bool isMacroop() const { return staticInst->isMacroop(); }
525    bool isMicroop() const { return staticInst->isMicroop(); }
526    bool isDelayedCommit() const { return staticInst->isDelayedCommit(); }
527    bool isLastMicroop() const { return staticInst->isLastMicroop(); }
528    bool isFirstMicroop() const { return staticInst->isFirstMicroop(); }
529    bool isMicroBranch() const { return staticInst->isMicroBranch(); }
530
531    /** Temporarily sets this instruction as a serialize before instruction. */
532    void setSerializeBefore() { status.set(SerializeBefore); }
533
534    /** Clears the serializeBefore part of this instruction. */
535    void clearSerializeBefore() { status.reset(SerializeBefore); }
536
537    /** Checks if this serializeBefore is only temporarily set. */
538    bool isTempSerializeBefore() { return status[SerializeBefore]; }
539
540    /** Temporarily sets this instruction as a serialize after instruction. */
541    void setSerializeAfter() { status.set(SerializeAfter); }
542
543    /** Clears the serializeAfter part of this instruction.*/
544    void clearSerializeAfter() { status.reset(SerializeAfter); }
545
546    /** Checks if this serializeAfter is only temporarily set. */
547    bool isTempSerializeAfter() { return status[SerializeAfter]; }
548
549    /** Sets the serialization part of this instruction as handled. */
550    void setSerializeHandled() { status.set(SerializeHandled); }
551
552    /** Checks if the serialization part of this instruction has been
553     *  handled.  This does not apply to the temporary serializing
554     *  state; it only applies to this instruction's own permanent
555     *  serializing state.
556     */
557    bool isSerializeHandled() { return status[SerializeHandled]; }
558
559    /** Returns the opclass of this instruction. */
560    OpClass opClass() const { return staticInst->opClass(); }
561
562    /** Returns the branch target address. */
563    TheISA::PCState branchTarget() const
564    { return staticInst->branchTarget(pc); }
565
566    /** Returns the number of source registers. */
567    int8_t numSrcRegs() const { return staticInst->numSrcRegs(); }
568
569    /** Returns the number of destination registers. */
570    int8_t numDestRegs() const { return staticInst->numDestRegs(); }
571
572    // the following are used to track physical register usage
573    // for machines with separate int & FP reg files
574    int8_t numFPDestRegs()  const { return staticInst->numFPDestRegs(); }
575    int8_t numIntDestRegs() const { return staticInst->numIntDestRegs(); }
576
577    /** Returns the logical register index of the i'th destination register. */
578    RegIndex destRegIdx(int i) const { return staticInst->destRegIdx(i); }
579
580    /** Returns the logical register index of the i'th source register. */
581    RegIndex srcRegIdx(int i) const { return staticInst->srcRegIdx(i); }
582
583    /** Returns the result of an integer instruction. */
584    uint64_t readIntResult() { return instResult.integer; }
585
586    /** Returns the result of a floating point instruction. */
587    float readFloatResult() { return (float)instResult.dbl; }
588
589    /** Returns the result of a floating point (double) instruction. */
590    double readDoubleResult() { return instResult.dbl; }
591
592    /** Records an integer register being set to a value. */
593    void setIntRegOperand(const StaticInst *si, int idx, uint64_t val)
594    {
595        if (recordResult)
596            instResult.integer = val;
597    }
598
599    /** Records an fp register being set to a value. */
600    void setFloatRegOperand(const StaticInst *si, int idx, FloatReg val,
601                            int width)
602    {
603        if (recordResult) {
604            if (width == 32)
605                instResult.dbl = (double)val;
606            else if (width == 64)
607                instResult.dbl = val;
608            else
609                panic("Unsupported width!");
610        }
611    }
612
613    /** Records an fp register being set to a value. */
614    void setFloatRegOperand(const StaticInst *si, int idx, FloatReg val)
615    {
616        if (recordResult)
617            instResult.dbl = (double)val;
618    }
619
620    /** Records an fp register being set to an integer value. */
621    void setFloatRegOperandBits(const StaticInst *si, int idx, uint64_t val,
622                                int width)
623    {
624        if (recordResult)
625            instResult.integer = val;
626    }
627
628    /** Records an fp register being set to an integer value. */
629    void setFloatRegOperandBits(const StaticInst *si, int idx, uint64_t val)
630    {
631        if (recordResult)
632            instResult.integer = val;
633    }
634
635    /** Records that one of the source registers is ready. */
636    void markSrcRegReady();
637
638    /** Marks a specific register as ready. */
639    void markSrcRegReady(RegIndex src_idx);
640
641    /** Returns if a source register is ready. */
642    bool isReadySrcRegIdx(int idx) const
643    {
644        return this->_readySrcRegIdx[idx];
645    }
646
647    /** Sets this instruction as completed. */
648    void setCompleted() { status.set(Completed); }
649
650    /** Returns whether or not this instruction is completed. */
651    bool isCompleted() const { return status[Completed]; }
652
653    /** Marks the result as ready. */
654    void setResultReady() { status.set(ResultReady); }
655
656    /** Returns whether or not the result is ready. */
657    bool isResultReady() const { return status[ResultReady]; }
658
659    /** Sets this instruction as ready to issue. */
660    void setCanIssue() { status.set(CanIssue); }
661
662    /** Returns whether or not this instruction is ready to issue. */
663    bool readyToIssue() const { return status[CanIssue]; }
664
665    /** Clears this instruction being able to issue. */
666    void clearCanIssue() { status.reset(CanIssue); }
667
668    /** Sets this instruction as issued from the IQ. */
669    void setIssued() { status.set(Issued); }
670
671    /** Returns whether or not this instruction has issued. */
672    bool isIssued() const { return status[Issued]; }
673
674    /** Clears this instruction as being issued. */
675    void clearIssued() { status.reset(Issued); }
676
677    /** Sets this instruction as executed. */
678    void setExecuted() { status.set(Executed); }
679
680    /** Returns whether or not this instruction has executed. */
681    bool isExecuted() const { return status[Executed]; }
682
683    /** Sets this instruction as ready to commit. */
684    void setCanCommit() { status.set(CanCommit); }
685
686    /** Clears this instruction as being ready to commit. */
687    void clearCanCommit() { status.reset(CanCommit); }
688
689    /** Returns whether or not this instruction is ready to commit. */
690    bool readyToCommit() const { return status[CanCommit]; }
691
692    void setAtCommit() { status.set(AtCommit); }
693
694    bool isAtCommit() { return status[AtCommit]; }
695
696    /** Sets this instruction as committed. */
697    void setCommitted() { status.set(Committed); }
698
699    /** Returns whether or not this instruction is committed. */
700    bool isCommitted() const { return status[Committed]; }
701
702    /** Sets this instruction as squashed. */
703    void setSquashed() { status.set(Squashed); }
704
705    /** Returns whether or not this instruction is squashed. */
706    bool isSquashed() const { return status[Squashed]; }
707
708    //Instruction Queue Entry
709    //-----------------------
710    /** Sets this instruction as a entry the IQ. */
711    void setInIQ() { status.set(IqEntry); }
712
713    /** Sets this instruction as a entry the IQ. */
714    void clearInIQ() { status.reset(IqEntry); }
715
716    /** Returns whether or not this instruction has issued. */
717    bool isInIQ() const { return status[IqEntry]; }
718
719    /** Sets this instruction as squashed in the IQ. */
720    void setSquashedInIQ() { status.set(SquashedInIQ); status.set(Squashed);}
721
722    /** Returns whether or not this instruction is squashed in the IQ. */
723    bool isSquashedInIQ() const { return status[SquashedInIQ]; }
724
725
726    //Load / Store Queue Functions
727    //-----------------------
728    /** Sets this instruction as a entry the LSQ. */
729    void setInLSQ() { status.set(LsqEntry); }
730
731    /** Sets this instruction as a entry the LSQ. */
732    void removeInLSQ() { status.reset(LsqEntry); }
733
734    /** Returns whether or not this instruction is in the LSQ. */
735    bool isInLSQ() const { return status[LsqEntry]; }
736
737    /** Sets this instruction as squashed in the LSQ. */
738    void setSquashedInLSQ() { status.set(SquashedInLSQ);}
739
740    /** Returns whether or not this instruction is squashed in the LSQ. */
741    bool isSquashedInLSQ() const { return status[SquashedInLSQ]; }
742
743
744    //Reorder Buffer Functions
745    //-----------------------
746    /** Sets this instruction as a entry the ROB. */
747    void setInROB() { status.set(RobEntry); }
748
749    /** Sets this instruction as a entry the ROB. */
750    void clearInROB() { status.reset(RobEntry); }
751
752    /** Returns whether or not this instruction is in the ROB. */
753    bool isInROB() const { return status[RobEntry]; }
754
755    /** Sets this instruction as squashed in the ROB. */
756    void setSquashedInROB() { status.set(SquashedInROB); }
757
758    /** Returns whether or not this instruction is squashed in the ROB. */
759    bool isSquashedInROB() const { return status[SquashedInROB]; }
760
761    /** Read the PC state of this instruction. */
762    const TheISA::PCState pcState() const { return pc; }
763
764    /** Set the PC state of this instruction. */
765    const void pcState(const TheISA::PCState &val) { pc = val; }
766
767    /** Read the PC of this instruction. */
768    const Addr instAddr() const { return pc.instAddr(); }
769
770    /** Read the PC of the next instruction. */
771    const Addr nextInstAddr() const { return pc.nextInstAddr(); }
772
773    /**Read the micro PC of this instruction. */
774    const Addr microPC() const { return pc.microPC(); }
775
776    bool readPredicate()
777    {
778        return predicate;
779    }
780
781    void setPredicate(bool val)
782    {
783        predicate = val;
784
785        if (traceData) {
786            traceData->setPredicate(val);
787        }
788    }
789
790    /** Sets the ASID. */
791    void setASID(short addr_space_id) { asid = addr_space_id; }
792
793    /** Sets the thread id. */
794    void setTid(ThreadID tid) { threadNumber = tid; }
795
796    /** Sets the pointer to the thread state. */
797    void setThreadState(ImplState *state) { thread = state; }
798
799    /** Returns the thread context. */
800    ThreadContext *tcBase() { return thread->getTC(); }
801
802  private:
803    /** Instruction effective address.
804     *  @todo: Consider if this is necessary or not.
805     */
806    Addr instEffAddr;
807
808    /** Whether or not the effective address calculation is completed.
809     *  @todo: Consider if this is necessary or not.
810     */
811    bool eaCalcDone;
812
813    /** Is this instruction's memory access uncacheable. */
814    bool isUncacheable;
815
816    /** Has this instruction generated a memory request. */
817    bool reqMade;
818
819  public:
820    /** Sets the effective address. */
821    void setEA(Addr &ea) { instEffAddr = ea; eaCalcDone = true; }
822
823    /** Returns the effective address. */
824    const Addr &getEA() const { return instEffAddr; }
825
826    /** Returns whether or not the eff. addr. calculation has been completed. */
827    bool doneEACalc() { return eaCalcDone; }
828
829    /** Returns whether or not the eff. addr. source registers are ready. */
830    bool eaSrcsReady();
831
832    /** Whether or not the memory operation is done. */
833    bool memOpDone;
834
835    /** Is this instruction's memory access uncacheable. */
836    bool uncacheable() { return isUncacheable; }
837
838    /** Has this instruction generated a memory request. */
839    bool hasRequest() { return reqMade; }
840
841  public:
842    /** Load queue index. */
843    int16_t lqIdx;
844
845    /** Store queue index. */
846    int16_t sqIdx;
847
848    /** Iterator pointing to this BaseDynInst in the list of all insts. */
849    ListIt instListIt;
850
851    /** Returns iterator to this instruction in the list of all insts. */
852    ListIt &getInstListIt() { return instListIt; }
853
854    /** Sets iterator for this instruction in the list of all insts. */
855    void setInstListIt(ListIt _instListIt) { instListIt = _instListIt; }
856
857  public:
858    /** Returns the number of consecutive store conditional failures. */
859    unsigned readStCondFailures()
860    { return thread->storeCondFailures; }
861
862    /** Sets the number of consecutive store conditional failures. */
863    void setStCondFailures(unsigned sc_failures)
864    { thread->storeCondFailures = sc_failures; }
865};
866
867template<class Impl>
868Fault
869BaseDynInst<Impl>::readBytes(Addr addr, uint8_t *data,
870                             unsigned size, unsigned flags)
871{
872    reqMade = true;
873    Request *req = NULL;
874    Request *sreqLow = NULL;
875    Request *sreqHigh = NULL;
876
877    if (reqMade && translationStarted) {
878        req = savedReq;
879        sreqLow = savedSreqLow;
880        sreqHigh = savedSreqHigh;
881    } else {
882        req = new Request(asid, addr, size, flags, this->pc.instAddr(),
883                          thread->contextId(), threadNumber);
884
885        // Only split the request if the ISA supports unaligned accesses.
886        if (TheISA::HasUnalignedMemAcc) {
887            splitRequest(req, sreqLow, sreqHigh);
888        }
889        initiateTranslation(req, sreqLow, sreqHigh, NULL, BaseTLB::Read);
890    }
891
892    if (translationCompleted) {
893        if (fault == NoFault) {
894            effAddr = req->getVaddr();
895            effAddrValid = true;
896            fault = cpu->read(req, sreqLow, sreqHigh, data, lqIdx);
897        } else {
898            // Commit will have to clean up whatever happened.  Set this
899            // instruction as executed.
900            this->setExecuted();
901        }
902
903        if (fault != NoFault) {
904            // Return a fixed value to keep simulation deterministic even
905            // along misspeculated paths.
906            if (data)
907                bzero(data, size);
908        }
909    }
910
911    if (traceData) {
912        traceData->setAddr(addr);
913    }
914
915    return fault;
916}
917
918template<class Impl>
919template<class T>
920inline Fault
921BaseDynInst<Impl>::read(Addr addr, T &data, unsigned flags)
922{
923    Fault fault = readBytes(addr, (uint8_t *)&data, sizeof(T), flags);
924
925    data = TheISA::gtoh(data);
926
927    if (traceData) {
928        traceData->setData(data);
929    }
930
931    return fault;
932}
933
934template<class Impl>
935Fault
936BaseDynInst<Impl>::writeBytes(uint8_t *data, unsigned size,
937                              Addr addr, unsigned flags, uint64_t *res)
938{
939    if (traceData) {
940        traceData->setAddr(addr);
941    }
942
943    reqMade = true;
944    Request *req = NULL;
945    Request *sreqLow = NULL;
946    Request *sreqHigh = NULL;
947
948    if (reqMade && translationStarted) {
949        req = savedReq;
950        sreqLow = savedSreqLow;
951        sreqHigh = savedSreqHigh;
952    } else {
953        req = new Request(asid, addr, size, flags, this->pc.instAddr(),
954                          thread->contextId(), threadNumber);
955
956        // Only split the request if the ISA supports unaligned accesses.
957        if (TheISA::HasUnalignedMemAcc) {
958            splitRequest(req, sreqLow, sreqHigh);
959        }
960        initiateTranslation(req, sreqLow, sreqHigh, res, BaseTLB::Write);
961    }
962
963    if (fault == NoFault && translationCompleted) {
964        effAddr = req->getVaddr();
965        effAddrValid = true;
966        fault = cpu->write(req, sreqLow, sreqHigh, data, sqIdx);
967    }
968
969    return fault;
970}
971
972template<class Impl>
973template<class T>
974inline Fault
975BaseDynInst<Impl>::write(T data, Addr addr, unsigned flags, uint64_t *res)
976{
977    if (traceData) {
978        traceData->setData(data);
979    }
980    data = TheISA::htog(data);
981    return writeBytes((uint8_t *)&data, sizeof(T), addr, flags, res);
982}
983
984template<class Impl>
985inline void
986BaseDynInst<Impl>::splitRequest(RequestPtr req, RequestPtr &sreqLow,
987                                RequestPtr &sreqHigh)
988{
989    // Check to see if the request crosses the next level block boundary.
990    unsigned block_size = cpu->getDcachePort()->peerBlockSize();
991    Addr addr = req->getVaddr();
992    Addr split_addr = roundDown(addr + req->getSize() - 1, block_size);
993    assert(split_addr <= addr || split_addr - addr < block_size);
994
995    // Spans two blocks.
996    if (split_addr > addr) {
997        req->splitOnVaddr(split_addr, sreqLow, sreqHigh);
998    }
999}
1000
1001template<class Impl>
1002inline void
1003BaseDynInst<Impl>::initiateTranslation(RequestPtr req, RequestPtr sreqLow,
1004                                       RequestPtr sreqHigh, uint64_t *res,
1005                                       BaseTLB::Mode mode)
1006{
1007    translationStarted = true;
1008
1009    if (!TheISA::HasUnalignedMemAcc || sreqLow == NULL) {
1010        WholeTranslationState *state =
1011            new WholeTranslationState(req, NULL, res, mode);
1012
1013        // One translation if the request isn't split.
1014        DataTranslation<BaseDynInst<Impl> > *trans =
1015            new DataTranslation<BaseDynInst<Impl> >(this, state);
1016        cpu->dtb->translateTiming(req, thread->getTC(), trans, mode);
1017        if (!translationCompleted) {
1018            // Save memory requests.
1019            savedReq = state->mainReq;
1020            savedSreqLow = state->sreqLow;
1021            savedSreqHigh = state->sreqHigh;
1022        }
1023    } else {
1024        WholeTranslationState *state =
1025            new WholeTranslationState(req, sreqLow, sreqHigh, NULL, res, mode);
1026
1027        // Two translations when the request is split.
1028        DataTranslation<BaseDynInst<Impl> > *stransLow =
1029            new DataTranslation<BaseDynInst<Impl> >(this, state, 0);
1030        DataTranslation<BaseDynInst<Impl> > *stransHigh =
1031            new DataTranslation<BaseDynInst<Impl> >(this, state, 1);
1032
1033        cpu->dtb->translateTiming(sreqLow, thread->getTC(), stransLow, mode);
1034        cpu->dtb->translateTiming(sreqHigh, thread->getTC(), stransHigh, mode);
1035        if (!translationCompleted) {
1036            // Save memory requests.
1037            savedReq = state->mainReq;
1038            savedSreqLow = state->sreqLow;
1039            savedSreqHigh = state->sreqHigh;
1040        }
1041    }
1042}
1043
1044template<class Impl>
1045inline void
1046BaseDynInst<Impl>::finishTranslation(WholeTranslationState *state)
1047{
1048    fault = state->getFault();
1049
1050    if (state->isUncacheable())
1051        isUncacheable = true;
1052
1053    if (fault == NoFault) {
1054        physEffAddr = state->getPaddr();
1055        memReqFlags = state->getFlags();
1056
1057        if (state->mainReq->isCondSwap()) {
1058            assert(state->res);
1059            state->mainReq->setExtraData(*state->res);
1060        }
1061
1062    } else {
1063        state->deleteReqs();
1064    }
1065    delete state;
1066
1067    translationCompleted = true;
1068}
1069
1070#endif // __CPU_BASE_DYN_INST_HH__
1071