iew.hh revision 8229:78bf55f23338
1/*
2 * Copyright (c) 2010 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 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Kevin Lim
41 */
42
43#ifndef __CPU_O3_IEW_HH__
44#define __CPU_O3_IEW_HH__
45
46#include <queue>
47
48#include "base/statistics.hh"
49#include "config/full_system.hh"
50#include "cpu/o3/comm.hh"
51#include "cpu/o3/lsq.hh"
52#include "cpu/o3/scoreboard.hh"
53#include "cpu/timebuf.hh"
54
55class DerivO3CPUParams;
56class FUPool;
57
58/**
59 * DefaultIEW handles both single threaded and SMT IEW
60 * (issue/execute/writeback).  It handles the dispatching of
61 * instructions to the LSQ/IQ as part of the issue stage, and has the
62 * IQ try to issue instructions each cycle. The execute latency is
63 * actually tied into the issue latency to allow the IQ to be able to
64 * do back-to-back scheduling without having to speculatively schedule
65 * instructions. This happens by having the IQ have access to the
66 * functional units, and the IQ gets the execution latencies from the
67 * FUs when it issues instructions. Instructions reach the execute
68 * stage on the last cycle of their execution, which is when the IQ
69 * knows to wake up any dependent instructions, allowing back to back
70 * scheduling. The execute portion of IEW separates memory
71 * instructions from non-memory instructions, either telling the LSQ
72 * to execute the instruction, or executing the instruction directly.
73 * The writeback portion of IEW completes the instructions by waking
74 * up any dependents, and marking the register ready on the
75 * scoreboard.
76 */
77template<class Impl>
78class DefaultIEW
79{
80  private:
81    //Typedefs from Impl
82    typedef typename Impl::CPUPol CPUPol;
83    typedef typename Impl::DynInstPtr DynInstPtr;
84    typedef typename Impl::O3CPU O3CPU;
85
86    typedef typename CPUPol::IQ IQ;
87    typedef typename CPUPol::RenameMap RenameMap;
88    typedef typename CPUPol::LSQ LSQ;
89
90    typedef typename CPUPol::TimeStruct TimeStruct;
91    typedef typename CPUPol::IEWStruct IEWStruct;
92    typedef typename CPUPol::RenameStruct RenameStruct;
93    typedef typename CPUPol::IssueStruct IssueStruct;
94
95    friend class Impl::O3CPU;
96    friend class CPUPol::IQ;
97
98  public:
99    /** Overall IEW stage status. Used to determine if the CPU can
100     * deschedule itself due to a lack of activity.
101     */
102    enum Status {
103        Active,
104        Inactive
105    };
106
107    /** Status for Issue, Execute, and Writeback stages. */
108    enum StageStatus {
109        Running,
110        Blocked,
111        Idle,
112        StartSquash,
113        Squashing,
114        Unblocking
115    };
116
117  private:
118    /** Overall stage status. */
119    Status _status;
120    /** Dispatch status. */
121    StageStatus dispatchStatus[Impl::MaxThreads];
122    /** Execute status. */
123    StageStatus exeStatus;
124    /** Writeback status. */
125    StageStatus wbStatus;
126
127  public:
128    /** Constructs a DefaultIEW with the given parameters. */
129    DefaultIEW(O3CPU *_cpu, DerivO3CPUParams *params);
130
131    /** Returns the name of the DefaultIEW stage. */
132    std::string name() const;
133
134    /** Registers statistics. */
135    void regStats();
136
137    /** Initializes stage; sends back the number of free IQ and LSQ entries. */
138    void initStage();
139
140    /** Returns the dcache port. */
141    Port *getDcachePort() { return ldstQueue.getDcachePort(); }
142
143    /** Sets main time buffer used for backwards communication. */
144    void setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr);
145
146    /** Sets time buffer for getting instructions coming from rename. */
147    void setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr);
148
149    /** Sets time buffer to pass on instructions to commit. */
150    void setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr);
151
152    /** Sets pointer to list of active threads. */
153    void setActiveThreads(std::list<ThreadID> *at_ptr);
154
155    /** Sets pointer to the scoreboard. */
156    void setScoreboard(Scoreboard *sb_ptr);
157
158    /** Drains IEW stage. */
159    bool drain();
160
161    /** Resumes execution after a drain. */
162    void resume();
163
164    /** Completes switch out of IEW stage. */
165    void switchOut();
166
167    /** Takes over from another CPU's thread. */
168    void takeOverFrom();
169
170    /** Returns if IEW is switched out. */
171    bool isSwitchedOut() { return switchedOut; }
172
173    /** Squashes instructions in IEW for a specific thread. */
174    void squash(ThreadID tid);
175
176    /** Wakes all dependents of a completed instruction. */
177    void wakeDependents(DynInstPtr &inst);
178
179    /** Tells memory dependence unit that a memory instruction needs to be
180     * rescheduled. It will re-execute once replayMemInst() is called.
181     */
182    void rescheduleMemInst(DynInstPtr &inst);
183
184    /** Re-executes all rescheduled memory instructions. */
185    void replayMemInst(DynInstPtr &inst);
186
187    /** Sends an instruction to commit through the time buffer. */
188    void instToCommit(DynInstPtr &inst);
189
190    /** Inserts unused instructions of a thread into the skid buffer. */
191    void skidInsert(ThreadID tid);
192
193    /** Returns the max of the number of entries in all of the skid buffers. */
194    int skidCount();
195
196    /** Returns if all of the skid buffers are empty. */
197    bool skidsEmpty();
198
199    /** Updates overall IEW status based on all of the stages' statuses. */
200    void updateStatus();
201
202    /** Resets entries of the IQ and the LSQ. */
203    void resetEntries();
204
205    /** Tells the CPU to wakeup if it has descheduled itself due to no
206     * activity. Used mainly by the LdWritebackEvent.
207     */
208    void wakeCPU();
209
210    /** Reports to the CPU that there is activity this cycle. */
211    void activityThisCycle();
212
213    /** Tells CPU that the IEW stage is active and running. */
214    inline void activateStage();
215
216    /** Tells CPU that the IEW stage is inactive and idle. */
217    inline void deactivateStage();
218
219    /** Returns if the LSQ has any stores to writeback. */
220    bool hasStoresToWB() { return ldstQueue.hasStoresToWB(); }
221
222    /** Returns if the LSQ has any stores to writeback. */
223    bool hasStoresToWB(ThreadID tid) { return ldstQueue.hasStoresToWB(tid); }
224
225    void incrWb(InstSeqNum &sn)
226    {
227        if (++wbOutstanding == wbMax)
228            ableToIssue = false;
229        DPRINTF(IEW, "wbOutstanding: %i\n", wbOutstanding);
230        assert(wbOutstanding <= wbMax);
231#ifdef DEBUG
232        wbList.insert(sn);
233#endif
234    }
235
236    void decrWb(InstSeqNum &sn)
237    {
238        if (wbOutstanding-- == wbMax)
239            ableToIssue = true;
240        DPRINTF(IEW, "wbOutstanding: %i [sn:%lli]\n", wbOutstanding, sn);
241        assert(wbOutstanding >= 0);
242#ifdef DEBUG
243        assert(wbList.find(sn) != wbList.end());
244        wbList.erase(sn);
245#endif
246    }
247
248#ifdef DEBUG
249    std::set<InstSeqNum> wbList;
250
251    void dumpWb()
252    {
253        std::set<InstSeqNum>::iterator wb_it = wbList.begin();
254        while (wb_it != wbList.end()) {
255            cprintf("[sn:%lli]\n",
256                    (*wb_it));
257            wb_it++;
258        }
259    }
260#endif
261
262    bool canIssue() { return ableToIssue; }
263
264    bool ableToIssue;
265
266    /** Check misprediction  */
267    void checkMisprediction(DynInstPtr &inst);
268
269  private:
270    /** Sends commit proper information for a squash due to a branch
271     * mispredict.
272     */
273    void squashDueToBranch(DynInstPtr &inst, ThreadID tid);
274
275    /** Sends commit proper information for a squash due to a memory order
276     * violation.
277     */
278    void squashDueToMemOrder(DynInstPtr &inst, ThreadID tid);
279
280    /** Sends commit proper information for a squash due to memory becoming
281     * blocked (younger issued instructions must be retried).
282     */
283    void squashDueToMemBlocked(DynInstPtr &inst, ThreadID tid);
284
285    /** Sets Dispatch to blocked, and signals back to other stages to block. */
286    void block(ThreadID tid);
287
288    /** Unblocks Dispatch if the skid buffer is empty, and signals back to
289     * other stages to unblock.
290     */
291    void unblock(ThreadID tid);
292
293    /** Determines proper actions to take given Dispatch's status. */
294    void dispatch(ThreadID tid);
295
296    /** Dispatches instructions to IQ and LSQ. */
297    void dispatchInsts(ThreadID tid);
298
299    /** Executes instructions. In the case of memory operations, it informs the
300     * LSQ to execute the instructions. Also handles any redirects that occur
301     * due to the executed instructions.
302     */
303    void executeInsts();
304
305    /** Writebacks instructions. In our model, the instruction's execute()
306     * function atomically reads registers, executes, and writes registers.
307     * Thus this writeback only wakes up dependent instructions, and informs
308     * the scoreboard of registers becoming ready.
309     */
310    void writebackInsts();
311
312    /** Returns the number of valid, non-squashed instructions coming from
313     * rename to dispatch.
314     */
315    unsigned validInstsFromRename();
316
317    /** Reads the stall signals. */
318    void readStallSignals(ThreadID tid);
319
320    /** Checks if any of the stall conditions are currently true. */
321    bool checkStall(ThreadID tid);
322
323    /** Processes inputs and changes state accordingly. */
324    void checkSignalsAndUpdate(ThreadID tid);
325
326    /** Removes instructions from rename from a thread's instruction list. */
327    void emptyRenameInsts(ThreadID tid);
328
329    /** Sorts instructions coming from rename into lists separated by thread. */
330    void sortInsts();
331
332  public:
333    /** Ticks IEW stage, causing Dispatch, the IQ, the LSQ, Execute, and
334     * Writeback to run for one cycle.
335     */
336    void tick();
337
338  private:
339    /** Updates execution stats based on the instruction. */
340    void updateExeInstStats(DynInstPtr &inst);
341
342    /** Pointer to main time buffer used for backwards communication. */
343    TimeBuffer<TimeStruct> *timeBuffer;
344
345    /** Wire to write information heading to previous stages. */
346    typename TimeBuffer<TimeStruct>::wire toFetch;
347
348    /** Wire to get commit's output from backwards time buffer. */
349    typename TimeBuffer<TimeStruct>::wire fromCommit;
350
351    /** Wire to write information heading to previous stages. */
352    typename TimeBuffer<TimeStruct>::wire toRename;
353
354    /** Rename instruction queue interface. */
355    TimeBuffer<RenameStruct> *renameQueue;
356
357    /** Wire to get rename's output from rename queue. */
358    typename TimeBuffer<RenameStruct>::wire fromRename;
359
360    /** Issue stage queue. */
361    TimeBuffer<IssueStruct> issueToExecQueue;
362
363    /** Wire to read information from the issue stage time queue. */
364    typename TimeBuffer<IssueStruct>::wire fromIssue;
365
366    /**
367     * IEW stage time buffer.  Holds ROB indices of instructions that
368     * can be marked as completed.
369     */
370    TimeBuffer<IEWStruct> *iewQueue;
371
372    /** Wire to write infromation heading to commit. */
373    typename TimeBuffer<IEWStruct>::wire toCommit;
374
375    /** Queue of all instructions coming from rename this cycle. */
376    std::queue<DynInstPtr> insts[Impl::MaxThreads];
377
378    /** Skid buffer between rename and IEW. */
379    std::queue<DynInstPtr> skidBuffer[Impl::MaxThreads];
380
381    /** Scoreboard pointer. */
382    Scoreboard* scoreboard;
383
384  private:
385    /** CPU pointer. */
386    O3CPU *cpu;
387
388    /** Records if IEW has written to the time buffer this cycle, so that the
389     * CPU can deschedule itself if there is no activity.
390     */
391    bool wroteToTimeBuffer;
392
393    /** Source of possible stalls. */
394    struct Stalls {
395        bool commit;
396    };
397
398    /** Stages that are telling IEW to stall. */
399    Stalls stalls[Impl::MaxThreads];
400
401    /** Debug function to print instructions that are issued this cycle. */
402    void printAvailableInsts();
403
404  public:
405    /** Instruction queue. */
406    IQ instQueue;
407
408    /** Load / store queue. */
409    LSQ ldstQueue;
410
411    /** Pointer to the functional unit pool. */
412    FUPool *fuPool;
413    /** Records if the LSQ needs to be updated on the next cycle, so that
414     * IEW knows if there will be activity on the next cycle.
415     */
416    bool updateLSQNextCycle;
417
418  private:
419    /** Records if there is a fetch redirect on this cycle for each thread. */
420    bool fetchRedirect[Impl::MaxThreads];
421
422    /** Records if the queues have been changed (inserted or issued insts),
423     * so that IEW knows to broadcast the updated amount of free entries.
424     */
425    bool updatedQueues;
426
427    /** Commit to IEW delay, in ticks. */
428    unsigned commitToIEWDelay;
429
430    /** Rename to IEW delay, in ticks. */
431    unsigned renameToIEWDelay;
432
433    /**
434     * Issue to execute delay, in ticks.  What this actually represents is
435     * the amount of time it takes for an instruction to wake up, be
436     * scheduled, and sent to a FU for execution.
437     */
438    unsigned issueToExecuteDelay;
439
440    /** Width of dispatch, in instructions. */
441    unsigned dispatchWidth;
442
443    /** Width of issue, in instructions. */
444    unsigned issueWidth;
445
446    /** Index into queue of instructions being written back. */
447    unsigned wbNumInst;
448
449    /** Cycle number within the queue of instructions being written back.
450     * Used in case there are too many instructions writing back at the current
451     * cycle and writesbacks need to be scheduled for the future. See comments
452     * in instToCommit().
453     */
454    unsigned wbCycle;
455
456    /** Number of instructions in flight that will writeback. */
457
458    /** Number of instructions in flight that will writeback. */
459    int wbOutstanding;
460
461    /** Writeback width. */
462    unsigned wbWidth;
463
464    /** Writeback width * writeback depth, where writeback depth is
465     * the number of cycles of writing back instructions that can be
466     * buffered. */
467    unsigned wbMax;
468
469    /** Number of active threads. */
470    ThreadID numThreads;
471
472    /** Pointer to list of active threads. */
473    std::list<ThreadID> *activeThreads;
474
475    /** Maximum size of the skid buffer. */
476    unsigned skidBufferMax;
477
478    /** Is this stage switched out. */
479    bool switchedOut;
480
481    /** Stat for total number of idle cycles. */
482    Stats::Scalar iewIdleCycles;
483    /** Stat for total number of squashing cycles. */
484    Stats::Scalar iewSquashCycles;
485    /** Stat for total number of blocking cycles. */
486    Stats::Scalar iewBlockCycles;
487    /** Stat for total number of unblocking cycles. */
488    Stats::Scalar iewUnblockCycles;
489    /** Stat for total number of instructions dispatched. */
490    Stats::Scalar iewDispatchedInsts;
491    /** Stat for total number of squashed instructions dispatch skips. */
492    Stats::Scalar iewDispSquashedInsts;
493    /** Stat for total number of dispatched load instructions. */
494    Stats::Scalar iewDispLoadInsts;
495    /** Stat for total number of dispatched store instructions. */
496    Stats::Scalar iewDispStoreInsts;
497    /** Stat for total number of dispatched non speculative instructions. */
498    Stats::Scalar iewDispNonSpecInsts;
499    /** Stat for number of times the IQ becomes full. */
500    Stats::Scalar iewIQFullEvents;
501    /** Stat for number of times the LSQ becomes full. */
502    Stats::Scalar iewLSQFullEvents;
503    /** Stat for total number of memory ordering violation events. */
504    Stats::Scalar memOrderViolationEvents;
505    /** Stat for total number of incorrect predicted taken branches. */
506    Stats::Scalar predictedTakenIncorrect;
507    /** Stat for total number of incorrect predicted not taken branches. */
508    Stats::Scalar predictedNotTakenIncorrect;
509    /** Stat for total number of mispredicted branches detected at execute. */
510    Stats::Formula branchMispredicts;
511
512    /** Stat for total number of executed instructions. */
513    Stats::Scalar iewExecutedInsts;
514    /** Stat for total number of executed load instructions. */
515    Stats::Vector iewExecLoadInsts;
516    /** Stat for total number of executed store instructions. */
517//    Stats::Scalar iewExecStoreInsts;
518    /** Stat for total number of squashed instructions skipped at execute. */
519    Stats::Scalar iewExecSquashedInsts;
520    /** Number of executed software prefetches. */
521    Stats::Vector iewExecutedSwp;
522    /** Number of executed nops. */
523    Stats::Vector iewExecutedNop;
524    /** Number of executed meomory references. */
525    Stats::Vector iewExecutedRefs;
526    /** Number of executed branches. */
527    Stats::Vector iewExecutedBranches;
528    /** Number of executed store instructions. */
529    Stats::Formula iewExecStoreInsts;
530    /** Number of instructions executed per cycle. */
531    Stats::Formula iewExecRate;
532
533    /** Number of instructions sent to commit. */
534    Stats::Vector iewInstsToCommit;
535    /** Number of instructions that writeback. */
536    Stats::Vector writebackCount;
537    /** Number of instructions that wake consumers. */
538    Stats::Vector producerInst;
539    /** Number of instructions that wake up from producers. */
540    Stats::Vector consumerInst;
541    /** Number of instructions that were delayed in writing back due
542     * to resource contention.
543     */
544    Stats::Vector wbPenalized;
545    /** Number of instructions per cycle written back. */
546    Stats::Formula wbRate;
547    /** Average number of woken instructions per writeback. */
548    Stats::Formula wbFanout;
549    /** Number of instructions per cycle delayed in writing back . */
550    Stats::Formula wbPenalizedRate;
551};
552
553#endif // __CPU_O3_IEW_HH__
554