iew_impl.hh revision 4318:eb4241362a80
1/*
2 * Copyright (c) 2004-2006 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 * Authors: Kevin Lim
29 */
30
31// @todo: Fix the instantaneous communication among all the stages within
32// iew.  There's a clear delay between issue and execute, yet backwards
33// communication happens simultaneously.
34
35#include <queue>
36
37#include "base/timebuf.hh"
38#include "cpu/o3/fu_pool.hh"
39#include "cpu/o3/iew.hh"
40
41template<class Impl>
42DefaultIEW<Impl>::DefaultIEW(Params *params)
43    : issueToExecQueue(params->backComSize, params->forwardComSize),
44      instQueue(params),
45      ldstQueue(params),
46      fuPool(params->fuPool),
47      commitToIEWDelay(params->commitToIEWDelay),
48      renameToIEWDelay(params->renameToIEWDelay),
49      issueToExecuteDelay(params->issueToExecuteDelay),
50      dispatchWidth(params->dispatchWidth),
51      issueWidth(params->issueWidth),
52      wbOutstanding(0),
53      wbWidth(params->wbWidth),
54      numThreads(params->numberOfThreads),
55      switchedOut(false)
56{
57    _status = Active;
58    exeStatus = Running;
59    wbStatus = Idle;
60
61    // Setup wire to read instructions coming from issue.
62    fromIssue = issueToExecQueue.getWire(-issueToExecuteDelay);
63
64    // Instruction queue needs the queue between issue and execute.
65    instQueue.setIssueToExecuteQueue(&issueToExecQueue);
66
67    instQueue.setIEW(this);
68    ldstQueue.setIEW(this);
69
70    for (int i=0; i < numThreads; i++) {
71        dispatchStatus[i] = Running;
72        stalls[i].commit = false;
73        fetchRedirect[i] = false;
74        bdelayDoneSeqNum[i] = 0;
75    }
76
77    wbMax = wbWidth * params->wbDepth;
78
79    updateLSQNextCycle = false;
80
81    ableToIssue = true;
82
83    skidBufferMax = (3 * (renameToIEWDelay * params->renameWidth)) + issueWidth;
84}
85
86template <class Impl>
87std::string
88DefaultIEW<Impl>::name() const
89{
90    return cpu->name() + ".iew";
91}
92
93template <class Impl>
94void
95DefaultIEW<Impl>::regStats()
96{
97    using namespace Stats;
98
99    instQueue.regStats();
100    ldstQueue.regStats();
101
102    iewIdleCycles
103        .name(name() + ".iewIdleCycles")
104        .desc("Number of cycles IEW is idle");
105
106    iewSquashCycles
107        .name(name() + ".iewSquashCycles")
108        .desc("Number of cycles IEW is squashing");
109
110    iewBlockCycles
111        .name(name() + ".iewBlockCycles")
112        .desc("Number of cycles IEW is blocking");
113
114    iewUnblockCycles
115        .name(name() + ".iewUnblockCycles")
116        .desc("Number of cycles IEW is unblocking");
117
118    iewDispatchedInsts
119        .name(name() + ".iewDispatchedInsts")
120        .desc("Number of instructions dispatched to IQ");
121
122    iewDispSquashedInsts
123        .name(name() + ".iewDispSquashedInsts")
124        .desc("Number of squashed instructions skipped by dispatch");
125
126    iewDispLoadInsts
127        .name(name() + ".iewDispLoadInsts")
128        .desc("Number of dispatched load instructions");
129
130    iewDispStoreInsts
131        .name(name() + ".iewDispStoreInsts")
132        .desc("Number of dispatched store instructions");
133
134    iewDispNonSpecInsts
135        .name(name() + ".iewDispNonSpecInsts")
136        .desc("Number of dispatched non-speculative instructions");
137
138    iewIQFullEvents
139        .name(name() + ".iewIQFullEvents")
140        .desc("Number of times the IQ has become full, causing a stall");
141
142    iewLSQFullEvents
143        .name(name() + ".iewLSQFullEvents")
144        .desc("Number of times the LSQ has become full, causing a stall");
145
146    memOrderViolationEvents
147        .name(name() + ".memOrderViolationEvents")
148        .desc("Number of memory order violations");
149
150    predictedTakenIncorrect
151        .name(name() + ".predictedTakenIncorrect")
152        .desc("Number of branches that were predicted taken incorrectly");
153
154    predictedNotTakenIncorrect
155        .name(name() + ".predictedNotTakenIncorrect")
156        .desc("Number of branches that were predicted not taken incorrectly");
157
158    branchMispredicts
159        .name(name() + ".branchMispredicts")
160        .desc("Number of branch mispredicts detected at execute");
161
162    branchMispredicts = predictedTakenIncorrect + predictedNotTakenIncorrect;
163
164    iewExecutedInsts
165        .name(name() + ".iewExecutedInsts")
166        .desc("Number of executed instructions");
167
168    iewExecLoadInsts
169        .init(cpu->number_of_threads)
170        .name(name() + ".iewExecLoadInsts")
171        .desc("Number of load instructions executed")
172        .flags(total);
173
174    iewExecSquashedInsts
175        .name(name() + ".iewExecSquashedInsts")
176        .desc("Number of squashed instructions skipped in execute");
177
178    iewExecutedSwp
179        .init(cpu->number_of_threads)
180        .name(name() + ".EXEC:swp")
181        .desc("number of swp insts executed")
182        .flags(total);
183
184    iewExecutedNop
185        .init(cpu->number_of_threads)
186        .name(name() + ".EXEC:nop")
187        .desc("number of nop insts executed")
188        .flags(total);
189
190    iewExecutedRefs
191        .init(cpu->number_of_threads)
192        .name(name() + ".EXEC:refs")
193        .desc("number of memory reference insts executed")
194        .flags(total);
195
196    iewExecutedBranches
197        .init(cpu->number_of_threads)
198        .name(name() + ".EXEC:branches")
199        .desc("Number of branches executed")
200        .flags(total);
201
202    iewExecStoreInsts
203        .name(name() + ".EXEC:stores")
204        .desc("Number of stores executed")
205        .flags(total);
206    iewExecStoreInsts = iewExecutedRefs - iewExecLoadInsts;
207
208    iewExecRate
209        .name(name() + ".EXEC:rate")
210        .desc("Inst execution rate")
211        .flags(total);
212
213    iewExecRate = iewExecutedInsts / cpu->numCycles;
214
215    iewInstsToCommit
216        .init(cpu->number_of_threads)
217        .name(name() + ".WB:sent")
218        .desc("cumulative count of insts sent to commit")
219        .flags(total);
220
221    writebackCount
222        .init(cpu->number_of_threads)
223        .name(name() + ".WB:count")
224        .desc("cumulative count of insts written-back")
225        .flags(total);
226
227    producerInst
228        .init(cpu->number_of_threads)
229        .name(name() + ".WB:producers")
230        .desc("num instructions producing a value")
231        .flags(total);
232
233    consumerInst
234        .init(cpu->number_of_threads)
235        .name(name() + ".WB:consumers")
236        .desc("num instructions consuming a value")
237        .flags(total);
238
239    wbPenalized
240        .init(cpu->number_of_threads)
241        .name(name() + ".WB:penalized")
242        .desc("number of instrctions required to write to 'other' IQ")
243        .flags(total);
244
245    wbPenalizedRate
246        .name(name() + ".WB:penalized_rate")
247        .desc ("fraction of instructions written-back that wrote to 'other' IQ")
248        .flags(total);
249
250    wbPenalizedRate = wbPenalized / writebackCount;
251
252    wbFanout
253        .name(name() + ".WB:fanout")
254        .desc("average fanout of values written-back")
255        .flags(total);
256
257    wbFanout = producerInst / consumerInst;
258
259    wbRate
260        .name(name() + ".WB:rate")
261        .desc("insts written-back per cycle")
262        .flags(total);
263    wbRate = writebackCount / cpu->numCycles;
264}
265
266template<class Impl>
267void
268DefaultIEW<Impl>::initStage()
269{
270    for (int tid=0; tid < numThreads; tid++) {
271        toRename->iewInfo[tid].usedIQ = true;
272        toRename->iewInfo[tid].freeIQEntries =
273            instQueue.numFreeEntries(tid);
274
275        toRename->iewInfo[tid].usedLSQ = true;
276        toRename->iewInfo[tid].freeLSQEntries =
277            ldstQueue.numFreeEntries(tid);
278    }
279}
280
281template<class Impl>
282void
283DefaultIEW<Impl>::setCPU(O3CPU *cpu_ptr)
284{
285    cpu = cpu_ptr;
286    DPRINTF(IEW, "Setting CPU pointer.\n");
287
288    instQueue.setCPU(cpu_ptr);
289    ldstQueue.setCPU(cpu_ptr);
290
291    cpu->activateStage(O3CPU::IEWIdx);
292}
293
294template<class Impl>
295void
296DefaultIEW<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
297{
298    timeBuffer = tb_ptr;
299
300    // Setup wire to read information from time buffer, from commit.
301    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
302
303    // Setup wire to write information back to previous stages.
304    toRename = timeBuffer->getWire(0);
305
306    toFetch = timeBuffer->getWire(0);
307
308    // Instruction queue also needs main time buffer.
309    instQueue.setTimeBuffer(tb_ptr);
310}
311
312template<class Impl>
313void
314DefaultIEW<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
315{
316    renameQueue = rq_ptr;
317
318    // Setup wire to read information from rename queue.
319    fromRename = renameQueue->getWire(-renameToIEWDelay);
320}
321
322template<class Impl>
323void
324DefaultIEW<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
325{
326    iewQueue = iq_ptr;
327
328    // Setup wire to write instructions to commit.
329    toCommit = iewQueue->getWire(0);
330}
331
332template<class Impl>
333void
334DefaultIEW<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
335{
336    activeThreads = at_ptr;
337
338    ldstQueue.setActiveThreads(at_ptr);
339    instQueue.setActiveThreads(at_ptr);
340}
341
342template<class Impl>
343void
344DefaultIEW<Impl>::setScoreboard(Scoreboard *sb_ptr)
345{
346    scoreboard = sb_ptr;
347}
348
349template <class Impl>
350bool
351DefaultIEW<Impl>::drain()
352{
353    // IEW is ready to drain at any time.
354    cpu->signalDrained();
355    return true;
356}
357
358template <class Impl>
359void
360DefaultIEW<Impl>::resume()
361{
362}
363
364template <class Impl>
365void
366DefaultIEW<Impl>::switchOut()
367{
368    // Clear any state.
369    switchedOut = true;
370    assert(insts[0].empty());
371    assert(skidBuffer[0].empty());
372
373    instQueue.switchOut();
374    ldstQueue.switchOut();
375    fuPool->switchOut();
376
377    for (int i = 0; i < numThreads; i++) {
378        while (!insts[i].empty())
379            insts[i].pop();
380        while (!skidBuffer[i].empty())
381            skidBuffer[i].pop();
382    }
383}
384
385template <class Impl>
386void
387DefaultIEW<Impl>::takeOverFrom()
388{
389    // Reset all state.
390    _status = Active;
391    exeStatus = Running;
392    wbStatus = Idle;
393    switchedOut = false;
394
395    instQueue.takeOverFrom();
396    ldstQueue.takeOverFrom();
397    fuPool->takeOverFrom();
398
399    initStage();
400    cpu->activityThisCycle();
401
402    for (int i=0; i < numThreads; i++) {
403        dispatchStatus[i] = Running;
404        stalls[i].commit = false;
405        fetchRedirect[i] = false;
406    }
407
408    updateLSQNextCycle = false;
409
410    for (int i = 0; i < issueToExecQueue.getSize(); ++i) {
411        issueToExecQueue.advance();
412    }
413}
414
415template<class Impl>
416void
417DefaultIEW<Impl>::squash(unsigned tid)
418{
419    DPRINTF(IEW, "[tid:%i]: Squashing all instructions.\n",
420            tid);
421
422    // Tell the IQ to start squashing.
423    instQueue.squash(tid);
424
425    // Tell the LDSTQ to start squashing.
426#if ISA_HAS_DELAY_SLOT
427    ldstQueue.squash(fromCommit->commitInfo[tid].bdelayDoneSeqNum, tid);
428#else
429    ldstQueue.squash(fromCommit->commitInfo[tid].doneSeqNum, tid);
430#endif
431    updatedQueues = true;
432
433    // Clear the skid buffer in case it has any data in it.
434    DPRINTF(IEW, "[tid:%i]: Removing skidbuffer instructions until [sn:%i].\n",
435            tid, fromCommit->commitInfo[tid].bdelayDoneSeqNum);
436
437    while (!skidBuffer[tid].empty()) {
438#if ISA_HAS_DELAY_SLOT
439        if (skidBuffer[tid].front()->seqNum <=
440            fromCommit->commitInfo[tid].bdelayDoneSeqNum) {
441            DPRINTF(IEW, "[tid:%i]: Cannot remove skidbuffer instructions "
442                    "that occur before delay slot [sn:%i].\n",
443                    fromCommit->commitInfo[tid].bdelayDoneSeqNum,
444                    tid);
445            break;
446        } else {
447            DPRINTF(IEW, "[tid:%i]: Removing instruction [sn:%i] from "
448                    "skidBuffer.\n", tid, skidBuffer[tid].front()->seqNum);
449        }
450#endif
451        if (skidBuffer[tid].front()->isLoad() ||
452            skidBuffer[tid].front()->isStore() ) {
453            toRename->iewInfo[tid].dispatchedToLSQ++;
454        }
455
456        toRename->iewInfo[tid].dispatched++;
457
458        skidBuffer[tid].pop();
459    }
460
461    bdelayDoneSeqNum[tid] = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
462
463    emptyRenameInsts(tid);
464}
465
466template<class Impl>
467void
468DefaultIEW<Impl>::squashDueToBranch(DynInstPtr &inst, unsigned tid)
469{
470    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, PC: %#x "
471            "[sn:%i].\n", tid, inst->readPC(), inst->seqNum);
472
473    toCommit->squash[tid] = true;
474    toCommit->squashedSeqNum[tid] = inst->seqNum;
475    toCommit->mispredPC[tid] = inst->readPC();
476    toCommit->branchMispredict[tid] = true;
477
478    int instSize = sizeof(TheISA::MachInst);
479#if ISA_HAS_DELAY_SLOT
480    bool branch_taken =
481        !(inst->readNextPC() + instSize == inst->readNextNPC() &&
482          (inst->readNextPC() == inst->readPC() + instSize ||
483           inst->readNextPC() == inst->readPC() + 2 * instSize));
484    DPRINTF(Sparc, "Branch taken = %s [sn:%i]\n",
485            branch_taken ? "true": "false", inst->seqNum);
486
487    toCommit->branchTaken[tid] = branch_taken;
488
489    bool squashDelaySlot = true;
490//	(inst->readNextPC() != inst->readPC() + sizeof(TheISA::MachInst));
491    DPRINTF(Sparc, "Squash delay slot = %s [sn:%i]\n",
492            squashDelaySlot ? "true": "false", inst->seqNum);
493    toCommit->squashDelaySlot[tid] = squashDelaySlot;
494    //If we're squashing the delay slot, we need to pick back up at NextPC.
495    //Otherwise, NextPC isn't being squashed, so we should pick back up at
496    //NextNPC.
497    if (squashDelaySlot) {
498        toCommit->nextPC[tid] = inst->readNextPC();
499        toCommit->nextNPC[tid] = inst->readNextNPC();
500    } else {
501        toCommit->nextPC[tid] = inst->readNextNPC();
502        toCommit->nextNPC[tid] = inst->readNextNPC() + instSize;
503    }
504#else
505    toCommit->branchTaken[tid] = inst->readNextPC() !=
506        (inst->readPC() + sizeof(TheISA::MachInst));
507    toCommit->nextPC[tid] = inst->readNextPC();
508    toCommit->nextNPC[tid] = inst->readNextPC() + instSize;
509#endif
510
511    toCommit->includeSquashInst[tid] = false;
512
513    wroteToTimeBuffer = true;
514}
515
516template<class Impl>
517void
518DefaultIEW<Impl>::squashDueToMemOrder(DynInstPtr &inst, unsigned tid)
519{
520    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, "
521            "PC: %#x [sn:%i].\n", tid, inst->readPC(), inst->seqNum);
522
523    toCommit->squash[tid] = true;
524    toCommit->squashedSeqNum[tid] = inst->seqNum;
525    toCommit->nextPC[tid] = inst->readNextPC();
526#if ISA_HAS_DELAY_SLOT
527    toCommit->nextNPC[tid] = inst->readNextNPC();
528#else
529    toCommit->nextNPC[tid] = inst->readNextPC() + sizeof(TheISA::MachInst);
530#endif
531    toCommit->branchMispredict[tid] = false;
532
533    toCommit->includeSquashInst[tid] = false;
534
535    wroteToTimeBuffer = true;
536}
537
538template<class Impl>
539void
540DefaultIEW<Impl>::squashDueToMemBlocked(DynInstPtr &inst, unsigned tid)
541{
542    DPRINTF(IEW, "[tid:%i]: Memory blocked, squashing load and younger insts, "
543            "PC: %#x [sn:%i].\n", tid, inst->readPC(), inst->seqNum);
544
545    toCommit->squash[tid] = true;
546    toCommit->squashedSeqNum[tid] = inst->seqNum;
547    toCommit->nextPC[tid] = inst->readPC();
548#if ISA_HAS_DELAY_SLOT
549    toCommit->nextNPC[tid] = inst->readNextPC();
550#else
551    toCommit->nextNPC[tid] = inst->readPC() + sizeof(TheISA::MachInst);
552#endif
553    toCommit->branchMispredict[tid] = false;
554
555    // Must include the broadcasted SN in the squash.
556    toCommit->includeSquashInst[tid] = true;
557
558    ldstQueue.setLoadBlockedHandled(tid);
559
560    wroteToTimeBuffer = true;
561}
562
563template<class Impl>
564void
565DefaultIEW<Impl>::block(unsigned tid)
566{
567    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);
568
569    if (dispatchStatus[tid] != Blocked &&
570        dispatchStatus[tid] != Unblocking) {
571        toRename->iewBlock[tid] = true;
572        wroteToTimeBuffer = true;
573    }
574
575    // Add the current inputs to the skid buffer so they can be
576    // reprocessed when this stage unblocks.
577    skidInsert(tid);
578
579    dispatchStatus[tid] = Blocked;
580}
581
582template<class Impl>
583void
584DefaultIEW<Impl>::unblock(unsigned tid)
585{
586    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
587            "buffer %u.\n",tid, tid);
588
589    // If the skid bufffer is empty, signal back to previous stages to unblock.
590    // Also switch status to running.
591    if (skidBuffer[tid].empty()) {
592        toRename->iewUnblock[tid] = true;
593        wroteToTimeBuffer = true;
594        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
595        dispatchStatus[tid] = Running;
596    }
597}
598
599template<class Impl>
600void
601DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
602{
603    instQueue.wakeDependents(inst);
604}
605
606template<class Impl>
607void
608DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
609{
610    instQueue.rescheduleMemInst(inst);
611}
612
613template<class Impl>
614void
615DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
616{
617    instQueue.replayMemInst(inst);
618}
619
620template<class Impl>
621void
622DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
623{
624    // This function should not be called after writebackInsts in a
625    // single cycle.  That will cause problems with an instruction
626    // being added to the queue to commit without being processed by
627    // writebackInsts prior to being sent to commit.
628
629    // First check the time slot that this instruction will write
630    // to.  If there are free write ports at the time, then go ahead
631    // and write the instruction to that time.  If there are not,
632    // keep looking back to see where's the first time there's a
633    // free slot.
634    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
635        ++wbNumInst;
636        if (wbNumInst == wbWidth) {
637            ++wbCycle;
638            wbNumInst = 0;
639        }
640
641        assert((wbCycle * wbWidth + wbNumInst) <= wbMax);
642    }
643
644    DPRINTF(IEW, "Current wb cycle: %i, width: %i, numInst: %i\nwbActual:%i\n",
645            wbCycle, wbWidth, wbNumInst, wbCycle * wbWidth + wbNumInst);
646    // Add finished instruction to queue to commit.
647    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
648    (*iewQueue)[wbCycle].size++;
649}
650
651template <class Impl>
652unsigned
653DefaultIEW<Impl>::validInstsFromRename()
654{
655    unsigned inst_count = 0;
656
657    for (int i=0; i<fromRename->size; i++) {
658        if (!fromRename->insts[i]->isSquashed())
659            inst_count++;
660    }
661
662    return inst_count;
663}
664
665template<class Impl>
666void
667DefaultIEW<Impl>::skidInsert(unsigned tid)
668{
669    DynInstPtr inst = NULL;
670
671    while (!insts[tid].empty()) {
672        inst = insts[tid].front();
673
674        insts[tid].pop();
675
676        DPRINTF(Decode,"[tid:%i]: Inserting [sn:%lli] PC:%#x into "
677                "dispatch skidBuffer %i\n",tid, inst->seqNum,
678                inst->readPC(),tid);
679
680        skidBuffer[tid].push(inst);
681    }
682
683    assert(skidBuffer[tid].size() <= skidBufferMax &&
684           "Skidbuffer Exceeded Max Size");
685}
686
687template<class Impl>
688int
689DefaultIEW<Impl>::skidCount()
690{
691    int max=0;
692
693    std::list<unsigned>::iterator threads = activeThreads->begin();
694    std::list<unsigned>::iterator end = activeThreads->end();
695
696    while (threads != end) {
697        unsigned tid = *threads++;
698        unsigned thread_count = skidBuffer[tid].size();
699        if (max < thread_count)
700            max = thread_count;
701    }
702
703    return max;
704}
705
706template<class Impl>
707bool
708DefaultIEW<Impl>::skidsEmpty()
709{
710    std::list<unsigned>::iterator threads = activeThreads->begin();
711    std::list<unsigned>::iterator end = activeThreads->end();
712
713    while (threads != end) {
714        unsigned tid = *threads++;
715
716        if (!skidBuffer[tid].empty())
717            return false;
718    }
719
720    return true;
721}
722
723template <class Impl>
724void
725DefaultIEW<Impl>::updateStatus()
726{
727    bool any_unblocking = false;
728
729    std::list<unsigned>::iterator threads = activeThreads->begin();
730    std::list<unsigned>::iterator end = activeThreads->end();
731
732    while (threads != end) {
733        unsigned tid = *threads++;
734
735        if (dispatchStatus[tid] == Unblocking) {
736            any_unblocking = true;
737            break;
738        }
739    }
740
741    // If there are no ready instructions waiting to be scheduled by the IQ,
742    // and there's no stores waiting to write back, and dispatch is not
743    // unblocking, then there is no internal activity for the IEW stage.
744    if (_status == Active && !instQueue.hasReadyInsts() &&
745        !ldstQueue.willWB() && !any_unblocking) {
746        DPRINTF(IEW, "IEW switching to idle\n");
747
748        deactivateStage();
749
750        _status = Inactive;
751    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
752                                       ldstQueue.willWB() ||
753                                       any_unblocking)) {
754        // Otherwise there is internal activity.  Set to active.
755        DPRINTF(IEW, "IEW switching to active\n");
756
757        activateStage();
758
759        _status = Active;
760    }
761}
762
763template <class Impl>
764void
765DefaultIEW<Impl>::resetEntries()
766{
767    instQueue.resetEntries();
768    ldstQueue.resetEntries();
769}
770
771template <class Impl>
772void
773DefaultIEW<Impl>::readStallSignals(unsigned tid)
774{
775    if (fromCommit->commitBlock[tid]) {
776        stalls[tid].commit = true;
777    }
778
779    if (fromCommit->commitUnblock[tid]) {
780        assert(stalls[tid].commit);
781        stalls[tid].commit = false;
782    }
783}
784
785template <class Impl>
786bool
787DefaultIEW<Impl>::checkStall(unsigned tid)
788{
789    bool ret_val(false);
790
791    if (stalls[tid].commit) {
792        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
793        ret_val = true;
794    } else if (instQueue.isFull(tid)) {
795        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
796        ret_val = true;
797    } else if (ldstQueue.isFull(tid)) {
798        DPRINTF(IEW,"[tid:%i]: Stall: LSQ is full\n",tid);
799
800        if (ldstQueue.numLoads(tid) > 0 ) {
801
802            DPRINTF(IEW,"[tid:%i]: LSQ oldest load: [sn:%i] \n",
803                    tid,ldstQueue.getLoadHeadSeqNum(tid));
804        }
805
806        if (ldstQueue.numStores(tid) > 0) {
807
808            DPRINTF(IEW,"[tid:%i]: LSQ oldest store: [sn:%i] \n",
809                    tid,ldstQueue.getStoreHeadSeqNum(tid));
810        }
811
812        ret_val = true;
813    } else if (ldstQueue.isStalled(tid)) {
814        DPRINTF(IEW,"[tid:%i]: Stall: LSQ stall detected.\n",tid);
815        ret_val = true;
816    }
817
818    return ret_val;
819}
820
821template <class Impl>
822void
823DefaultIEW<Impl>::checkSignalsAndUpdate(unsigned tid)
824{
825    // Check if there's a squash signal, squash if there is
826    // Check stall signals, block if there is.
827    // If status was Blocked
828    //     if so then go to unblocking
829    // If status was Squashing
830    //     check if squashing is not high.  Switch to running this cycle.
831
832    readStallSignals(tid);
833
834    if (fromCommit->commitInfo[tid].squash) {
835        squash(tid);
836
837        if (dispatchStatus[tid] == Blocked ||
838            dispatchStatus[tid] == Unblocking) {
839            toRename->iewUnblock[tid] = true;
840            wroteToTimeBuffer = true;
841        }
842
843        dispatchStatus[tid] = Squashing;
844
845        fetchRedirect[tid] = false;
846        return;
847    }
848
849    if (fromCommit->commitInfo[tid].robSquashing) {
850        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);
851
852        dispatchStatus[tid] = Squashing;
853
854        emptyRenameInsts(tid);
855        wroteToTimeBuffer = true;
856        return;
857    }
858
859    if (checkStall(tid)) {
860        block(tid);
861        dispatchStatus[tid] = Blocked;
862        return;
863    }
864
865    if (dispatchStatus[tid] == Blocked) {
866        // Status from previous cycle was blocked, but there are no more stall
867        // conditions.  Switch over to unblocking.
868        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
869                tid);
870
871        dispatchStatus[tid] = Unblocking;
872
873        unblock(tid);
874
875        return;
876    }
877
878    if (dispatchStatus[tid] == Squashing) {
879        // Switch status to running if rename isn't being told to block or
880        // squash this cycle.
881        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
882                tid);
883
884        dispatchStatus[tid] = Running;
885
886        return;
887    }
888}
889
890template <class Impl>
891void
892DefaultIEW<Impl>::sortInsts()
893{
894    int insts_from_rename = fromRename->size;
895#ifdef DEBUG
896#if !ISA_HAS_DELAY_SLOT
897    for (int i = 0; i < numThreads; i++)
898        assert(insts[i].empty());
899#endif
900#endif
901    for (int i = 0; i < insts_from_rename; ++i) {
902        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
903    }
904}
905
906template <class Impl>
907void
908DefaultIEW<Impl>::emptyRenameInsts(unsigned tid)
909{
910    DPRINTF(IEW, "[tid:%i]: Removing incoming rename instructions until "
911            "[sn:%i].\n", tid, bdelayDoneSeqNum[tid]);
912
913    while (!insts[tid].empty()) {
914#if ISA_HAS_DELAY_SLOT
915        if (insts[tid].front()->seqNum <= bdelayDoneSeqNum[tid]) {
916            DPRINTF(IEW, "[tid:%i]: Done removing, cannot remove instruction"
917                    " that occurs at or before delay slot [sn:%i].\n",
918                    tid, bdelayDoneSeqNum[tid]);
919            break;
920        } else {
921            DPRINTF(IEW, "[tid:%i]: Removing incoming rename instruction "
922                    "[sn:%i].\n", tid, insts[tid].front()->seqNum);
923        }
924#endif
925
926        if (insts[tid].front()->isLoad() ||
927            insts[tid].front()->isStore() ) {
928            toRename->iewInfo[tid].dispatchedToLSQ++;
929        }
930
931        toRename->iewInfo[tid].dispatched++;
932
933        insts[tid].pop();
934    }
935}
936
937template <class Impl>
938void
939DefaultIEW<Impl>::wakeCPU()
940{
941    cpu->wakeCPU();
942}
943
944template <class Impl>
945void
946DefaultIEW<Impl>::activityThisCycle()
947{
948    DPRINTF(Activity, "Activity this cycle.\n");
949    cpu->activityThisCycle();
950}
951
952template <class Impl>
953inline void
954DefaultIEW<Impl>::activateStage()
955{
956    DPRINTF(Activity, "Activating stage.\n");
957    cpu->activateStage(O3CPU::IEWIdx);
958}
959
960template <class Impl>
961inline void
962DefaultIEW<Impl>::deactivateStage()
963{
964    DPRINTF(Activity, "Deactivating stage.\n");
965    cpu->deactivateStage(O3CPU::IEWIdx);
966}
967
968template<class Impl>
969void
970DefaultIEW<Impl>::dispatch(unsigned tid)
971{
972    // If status is Running or idle,
973    //     call dispatchInsts()
974    // If status is Unblocking,
975    //     buffer any instructions coming from rename
976    //     continue trying to empty skid buffer
977    //     check if stall conditions have passed
978
979    if (dispatchStatus[tid] == Blocked) {
980        ++iewBlockCycles;
981
982    } else if (dispatchStatus[tid] == Squashing) {
983        ++iewSquashCycles;
984    }
985
986    // Dispatch should try to dispatch as many instructions as its bandwidth
987    // will allow, as long as it is not currently blocked.
988    if (dispatchStatus[tid] == Running ||
989        dispatchStatus[tid] == Idle) {
990        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
991                "dispatch.\n", tid);
992
993        dispatchInsts(tid);
994    } else if (dispatchStatus[tid] == Unblocking) {
995        // Make sure that the skid buffer has something in it if the
996        // status is unblocking.
997        assert(!skidsEmpty());
998
999        // If the status was unblocking, then instructions from the skid
1000        // buffer were used.  Remove those instructions and handle
1001        // the rest of unblocking.
1002        dispatchInsts(tid);
1003
1004        ++iewUnblockCycles;
1005
1006        if (validInstsFromRename() && dispatchedAllInsts) {
1007            // Add the current inputs to the skid buffer so they can be
1008            // reprocessed when this stage unblocks.
1009            skidInsert(tid);
1010        }
1011
1012        unblock(tid);
1013    }
1014}
1015
1016template <class Impl>
1017void
1018DefaultIEW<Impl>::dispatchInsts(unsigned tid)
1019{
1020    dispatchedAllInsts = true;
1021
1022    // Obtain instructions from skid buffer if unblocking, or queue from rename
1023    // otherwise.
1024    std::queue<DynInstPtr> &insts_to_dispatch =
1025        dispatchStatus[tid] == Unblocking ?
1026        skidBuffer[tid] : insts[tid];
1027
1028    int insts_to_add = insts_to_dispatch.size();
1029
1030    DynInstPtr inst;
1031    bool add_to_iq = false;
1032    int dis_num_inst = 0;
1033
1034    // Loop through the instructions, putting them in the instruction
1035    // queue.
1036    for ( ; dis_num_inst < insts_to_add &&
1037              dis_num_inst < dispatchWidth;
1038          ++dis_num_inst)
1039    {
1040        inst = insts_to_dispatch.front();
1041
1042        if (dispatchStatus[tid] == Unblocking) {
1043            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
1044                    "buffer\n", tid);
1045        }
1046
1047        // Make sure there's a valid instruction there.
1048        assert(inst);
1049
1050        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %#x [sn:%lli] [tid:%i] to "
1051                "IQ.\n",
1052                tid, inst->readPC(), inst->seqNum, inst->threadNumber);
1053
1054        // Be sure to mark these instructions as ready so that the
1055        // commit stage can go ahead and execute them, and mark
1056        // them as issued so the IQ doesn't reprocess them.
1057
1058        // Check for squashed instructions.
1059        if (inst->isSquashed()) {
1060            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
1061                    "not adding to IQ.\n", tid);
1062
1063            ++iewDispSquashedInsts;
1064
1065            insts_to_dispatch.pop();
1066
1067            //Tell Rename That An Instruction has been processed
1068            if (inst->isLoad() || inst->isStore()) {
1069                toRename->iewInfo[tid].dispatchedToLSQ++;
1070            }
1071            toRename->iewInfo[tid].dispatched++;
1072
1073            continue;
1074        }
1075
1076        // Check for full conditions.
1077        if (instQueue.isFull(tid)) {
1078            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);
1079
1080            // Call function to start blocking.
1081            block(tid);
1082
1083            // Set unblock to false. Special case where we are using
1084            // skidbuffer (unblocking) instructions but then we still
1085            // get full in the IQ.
1086            toRename->iewUnblock[tid] = false;
1087
1088            dispatchedAllInsts = false;
1089
1090            ++iewIQFullEvents;
1091            break;
1092        } else if (ldstQueue.isFull(tid)) {
1093            DPRINTF(IEW, "[tid:%i]: Issue: LSQ has become full.\n",tid);
1094
1095            // Call function to start blocking.
1096            block(tid);
1097
1098            // Set unblock to false. Special case where we are using
1099            // skidbuffer (unblocking) instructions but then we still
1100            // get full in the IQ.
1101            toRename->iewUnblock[tid] = false;
1102
1103            dispatchedAllInsts = false;
1104
1105            ++iewLSQFullEvents;
1106            break;
1107        }
1108
1109        // Otherwise issue the instruction just fine.
1110        if (inst->isLoad()) {
1111            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1112                    "encountered, adding to LSQ.\n", tid);
1113
1114            // Reserve a spot in the load store queue for this
1115            // memory access.
1116            ldstQueue.insertLoad(inst);
1117
1118            ++iewDispLoadInsts;
1119
1120            add_to_iq = true;
1121
1122            toRename->iewInfo[tid].dispatchedToLSQ++;
1123        } else if (inst->isStore()) {
1124            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1125                    "encountered, adding to LSQ.\n", tid);
1126
1127            ldstQueue.insertStore(inst);
1128
1129            ++iewDispStoreInsts;
1130
1131            if (inst->isStoreConditional()) {
1132                // Store conditionals need to be set as "canCommit()"
1133                // so that commit can process them when they reach the
1134                // head of commit.
1135                // @todo: This is somewhat specific to Alpha.
1136                inst->setCanCommit();
1137                instQueue.insertNonSpec(inst);
1138                add_to_iq = false;
1139
1140                ++iewDispNonSpecInsts;
1141            } else {
1142                add_to_iq = true;
1143            }
1144
1145            toRename->iewInfo[tid].dispatchedToLSQ++;
1146        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
1147            // Same as non-speculative stores.
1148            inst->setCanCommit();
1149            instQueue.insertBarrier(inst);
1150            add_to_iq = false;
1151        } else if (inst->isNop()) {
1152            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
1153                    "skipping.\n", tid);
1154
1155            inst->setIssued();
1156            inst->setExecuted();
1157            inst->setCanCommit();
1158
1159            instQueue.recordProducer(inst);
1160
1161            iewExecutedNop[tid]++;
1162
1163            add_to_iq = false;
1164        } else if (inst->isExecuted()) {
1165            assert(0 && "Instruction shouldn't be executed.\n");
1166            DPRINTF(IEW, "Issue: Executed branch encountered, "
1167                    "skipping.\n");
1168
1169            inst->setIssued();
1170            inst->setCanCommit();
1171
1172            instQueue.recordProducer(inst);
1173
1174            add_to_iq = false;
1175        } else {
1176            add_to_iq = true;
1177        }
1178        if (inst->isNonSpeculative()) {
1179            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
1180                    "encountered, skipping.\n", tid);
1181
1182            // Same as non-speculative stores.
1183            inst->setCanCommit();
1184
1185            // Specifically insert it as nonspeculative.
1186            instQueue.insertNonSpec(inst);
1187
1188            ++iewDispNonSpecInsts;
1189
1190            add_to_iq = false;
1191        }
1192
1193        // If the instruction queue is not full, then add the
1194        // instruction.
1195        if (add_to_iq) {
1196            instQueue.insert(inst);
1197        }
1198
1199        insts_to_dispatch.pop();
1200
1201        toRename->iewInfo[tid].dispatched++;
1202
1203        ++iewDispatchedInsts;
1204    }
1205
1206    if (!insts_to_dispatch.empty()) {
1207        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n", tid);
1208        block(tid);
1209        toRename->iewUnblock[tid] = false;
1210    }
1211
1212    if (dispatchStatus[tid] == Idle && dis_num_inst) {
1213        dispatchStatus[tid] = Running;
1214
1215        updatedQueues = true;
1216    }
1217
1218    dis_num_inst = 0;
1219}
1220
1221template <class Impl>
1222void
1223DefaultIEW<Impl>::printAvailableInsts()
1224{
1225    int inst = 0;
1226
1227    std::cout << "Available Instructions: ";
1228
1229    while (fromIssue->insts[inst]) {
1230
1231        if (inst%3==0) std::cout << "\n\t";
1232
1233        std::cout << "PC: " << fromIssue->insts[inst]->readPC()
1234             << " TN: " << fromIssue->insts[inst]->threadNumber
1235             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";
1236
1237        inst++;
1238
1239    }
1240
1241    std::cout << "\n";
1242}
1243
1244template <class Impl>
1245void
1246DefaultIEW<Impl>::executeInsts()
1247{
1248    wbNumInst = 0;
1249    wbCycle = 0;
1250
1251    std::list<unsigned>::iterator threads = activeThreads->begin();
1252    std::list<unsigned>::iterator end = activeThreads->end();
1253
1254    while (threads != end) {
1255        unsigned tid = *threads++;
1256        fetchRedirect[tid] = false;
1257    }
1258
1259    // Uncomment this if you want to see all available instructions.
1260//    printAvailableInsts();
1261
1262    // Execute/writeback any instructions that are available.
1263    int insts_to_execute = fromIssue->size;
1264    int inst_num = 0;
1265    for (; inst_num < insts_to_execute;
1266          ++inst_num) {
1267
1268        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");
1269
1270        DynInstPtr inst = instQueue.getInstToExecute();
1271
1272        DPRINTF(IEW, "Execute: Processing PC %#x, [tid:%i] [sn:%i].\n",
1273                inst->readPC(), inst->threadNumber,inst->seqNum);
1274
1275        // Check if the instruction is squashed; if so then skip it
1276        if (inst->isSquashed()) {
1277            DPRINTF(IEW, "Execute: Instruction was squashed.\n");
1278
1279            // Consider this instruction executed so that commit can go
1280            // ahead and retire the instruction.
1281            inst->setExecuted();
1282
1283            // Not sure if I should set this here or just let commit try to
1284            // commit any squashed instructions.  I like the latter a bit more.
1285            inst->setCanCommit();
1286
1287            ++iewExecSquashedInsts;
1288
1289            decrWb(inst->seqNum);
1290            continue;
1291        }
1292
1293        Fault fault = NoFault;
1294
1295        // Execute instruction.
1296        // Note that if the instruction faults, it will be handled
1297        // at the commit stage.
1298        if (inst->isMemRef() &&
1299            (!inst->isDataPrefetch() && !inst->isInstPrefetch())) {
1300            DPRINTF(IEW, "Execute: Calculating address for memory "
1301                    "reference.\n");
1302
1303            // Tell the LDSTQ to execute this instruction (if it is a load).
1304            if (inst->isLoad()) {
1305                // Loads will mark themselves as executed, and their writeback
1306                // event adds the instruction to the queue to commit
1307                fault = ldstQueue.executeLoad(inst);
1308            } else if (inst->isStore()) {
1309                fault = ldstQueue.executeStore(inst);
1310
1311                // If the store had a fault then it may not have a mem req
1312                if (!inst->isStoreConditional() && fault == NoFault) {
1313                    inst->setExecuted();
1314
1315                    instToCommit(inst);
1316                } else if (fault != NoFault) {
1317                    // If the instruction faulted, then we need to send it along to commit
1318                    // without the instruction completing.
1319                    DPRINTF(IEW, "Store has fault %s! [sn:%lli]\n",
1320                            fault->name(), inst->seqNum);
1321
1322                    // Send this instruction to commit, also make sure iew stage
1323                    // realizes there is activity.
1324                    inst->setExecuted();
1325
1326                    instToCommit(inst);
1327                    activityThisCycle();
1328                }
1329
1330                // Store conditionals will mark themselves as
1331                // executed, and their writeback event will add the
1332                // instruction to the queue to commit.
1333            } else {
1334                panic("Unexpected memory type!\n");
1335            }
1336
1337        } else {
1338            inst->execute();
1339
1340            inst->setExecuted();
1341
1342            instToCommit(inst);
1343        }
1344
1345        updateExeInstStats(inst);
1346
1347        // Check if branch prediction was correct, if not then we need
1348        // to tell commit to squash in flight instructions.  Only
1349        // handle this if there hasn't already been something that
1350        // redirects fetch in this group of instructions.
1351
1352        // This probably needs to prioritize the redirects if a different
1353        // scheduler is used.  Currently the scheduler schedules the oldest
1354        // instruction first, so the branch resolution order will be correct.
1355        unsigned tid = inst->threadNumber;
1356
1357        if (!fetchRedirect[tid] ||
1358            toCommit->squashedSeqNum[tid] > inst->seqNum) {
1359
1360            if (inst->mispredicted()) {
1361                fetchRedirect[tid] = true;
1362
1363                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1364                DPRINTF(IEW, "Predicted target was %#x, %#x.\n",
1365                        inst->readPredPC(), inst->readPredNPC());
1366                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x,"
1367                        " NPC: %#x.\n", inst->readNextPC(),
1368                        inst->readNextNPC());
1369                // If incorrect, then signal the ROB that it must be squashed.
1370                squashDueToBranch(inst, tid);
1371
1372                if (inst->readPredTaken()) {
1373                    predictedTakenIncorrect++;
1374                } else {
1375                    predictedNotTakenIncorrect++;
1376                }
1377            } else if (ldstQueue.violation(tid)) {
1378                assert(inst->isMemRef());
1379                // If there was an ordering violation, then get the
1380                // DynInst that caused the violation.  Note that this
1381                // clears the violation signal.
1382                DynInstPtr violator;
1383                violator = ldstQueue.getMemDepViolator(tid);
1384
1385                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1386                        "%#x, inst PC: %#x.  Addr is: %#x.\n",
1387                        violator->readPC(), inst->readPC(), inst->physEffAddr);
1388
1389                // Ensure the violating instruction is older than
1390                // current squash
1391/*                if (fetchRedirect[tid] &&
1392                    violator->seqNum >= toCommit->squashedSeqNum[tid] + 1)
1393                    continue;
1394*/
1395                fetchRedirect[tid] = true;
1396
1397                // Tell the instruction queue that a violation has occured.
1398                instQueue.violation(inst, violator);
1399
1400                // Squash.
1401                squashDueToMemOrder(inst,tid);
1402
1403                ++memOrderViolationEvents;
1404            } else if (ldstQueue.loadBlocked(tid) &&
1405                       !ldstQueue.isLoadBlockedHandled(tid)) {
1406                fetchRedirect[tid] = true;
1407
1408                DPRINTF(IEW, "Load operation couldn't execute because the "
1409                        "memory system is blocked.  PC: %#x [sn:%lli]\n",
1410                        inst->readPC(), inst->seqNum);
1411
1412                squashDueToMemBlocked(inst, tid);
1413            }
1414        } else {
1415            // Reset any state associated with redirects that will not
1416            // be used.
1417            if (ldstQueue.violation(tid)) {
1418                assert(inst->isMemRef());
1419
1420                DynInstPtr violator = ldstQueue.getMemDepViolator(tid);
1421
1422                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1423                        "%#x, inst PC: %#x.  Addr is: %#x.\n",
1424                        violator->readPC(), inst->readPC(), inst->physEffAddr);
1425                DPRINTF(IEW, "Violation will not be handled because "
1426                        "already squashing\n");
1427
1428                ++memOrderViolationEvents;
1429            }
1430            if (ldstQueue.loadBlocked(tid) &&
1431                !ldstQueue.isLoadBlockedHandled(tid)) {
1432                DPRINTF(IEW, "Load operation couldn't execute because the "
1433                        "memory system is blocked.  PC: %#x [sn:%lli]\n",
1434                        inst->readPC(), inst->seqNum);
1435                DPRINTF(IEW, "Blocked load will not be handled because "
1436                        "already squashing\n");
1437
1438                ldstQueue.setLoadBlockedHandled(tid);
1439            }
1440
1441        }
1442    }
1443
1444    // Update and record activity if we processed any instructions.
1445    if (inst_num) {
1446        if (exeStatus == Idle) {
1447            exeStatus = Running;
1448        }
1449
1450        updatedQueues = true;
1451
1452        cpu->activityThisCycle();
1453    }
1454
1455    // Need to reset this in case a writeback event needs to write into the
1456    // iew queue.  That way the writeback event will write into the correct
1457    // spot in the queue.
1458    wbNumInst = 0;
1459}
1460
1461template <class Impl>
1462void
1463DefaultIEW<Impl>::writebackInsts()
1464{
1465    // Loop through the head of the time buffer and wake any
1466    // dependents.  These instructions are about to write back.  Also
1467    // mark scoreboard that this instruction is finally complete.
1468    // Either have IEW have direct access to scoreboard, or have this
1469    // as part of backwards communication.
1470    for (int inst_num = 0; inst_num < wbWidth &&
1471             toCommit->insts[inst_num]; inst_num++) {
1472        DynInstPtr inst = toCommit->insts[inst_num];
1473        int tid = inst->threadNumber;
1474
1475        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %#x.\n",
1476                inst->seqNum, inst->readPC());
1477
1478        iewInstsToCommit[tid]++;
1479
1480        // Some instructions will be sent to commit without having
1481        // executed because they need commit to handle them.
1482        // E.g. Uncached loads have not actually executed when they
1483        // are first sent to commit.  Instead commit must tell the LSQ
1484        // when it's ready to execute the uncached load.
1485        if (!inst->isSquashed() && inst->isExecuted() && inst->getFault() == NoFault) {
1486            int dependents = instQueue.wakeDependents(inst);
1487
1488            for (int i = 0; i < inst->numDestRegs(); i++) {
1489                //mark as Ready
1490                DPRINTF(IEW,"Setting Destination Register %i\n",
1491                        inst->renamedDestRegIdx(i));
1492                scoreboard->setReg(inst->renamedDestRegIdx(i));
1493            }
1494
1495            if (dependents) {
1496                producerInst[tid]++;
1497                consumerInst[tid]+= dependents;
1498            }
1499            writebackCount[tid]++;
1500        }
1501
1502        decrWb(inst->seqNum);
1503    }
1504}
1505
1506template<class Impl>
1507void
1508DefaultIEW<Impl>::tick()
1509{
1510    wbNumInst = 0;
1511    wbCycle = 0;
1512
1513    wroteToTimeBuffer = false;
1514    updatedQueues = false;
1515
1516    sortInsts();
1517
1518    // Free function units marked as being freed this cycle.
1519    fuPool->processFreeUnits();
1520
1521    std::list<unsigned>::iterator threads = activeThreads->begin();
1522    std::list<unsigned>::iterator end = activeThreads->end();
1523
1524    // Check stall and squash signals, dispatch any instructions.
1525    while (threads != end) {
1526        unsigned tid = *threads++;
1527
1528        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);
1529
1530        checkSignalsAndUpdate(tid);
1531        dispatch(tid);
1532    }
1533
1534    if (exeStatus != Squashing) {
1535        executeInsts();
1536
1537        writebackInsts();
1538
1539        // Have the instruction queue try to schedule any ready instructions.
1540        // (In actuality, this scheduling is for instructions that will
1541        // be executed next cycle.)
1542        instQueue.scheduleReadyInsts();
1543
1544        // Also should advance its own time buffers if the stage ran.
1545        // Not the best place for it, but this works (hopefully).
1546        issueToExecQueue.advance();
1547    }
1548
1549    bool broadcast_free_entries = false;
1550
1551    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
1552        exeStatus = Idle;
1553        updateLSQNextCycle = false;
1554
1555        broadcast_free_entries = true;
1556    }
1557
1558    // Writeback any stores using any leftover bandwidth.
1559    ldstQueue.writebackStores();
1560
1561    // Check the committed load/store signals to see if there's a load
1562    // or store to commit.  Also check if it's being told to execute a
1563    // nonspeculative instruction.
1564    // This is pretty inefficient...
1565
1566    threads = activeThreads->begin();
1567    while (threads != end) {
1568        unsigned tid = (*threads++);
1569
1570        DPRINTF(IEW,"Processing [tid:%i]\n",tid);
1571
1572        // Update structures based on instructions committed.
1573        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
1574            !fromCommit->commitInfo[tid].squash &&
1575            !fromCommit->commitInfo[tid].robSquashing) {
1576
1577            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);
1578
1579            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);
1580
1581            updateLSQNextCycle = true;
1582            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
1583        }
1584
1585        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {
1586
1587            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
1588            if (fromCommit->commitInfo[tid].uncached) {
1589                instQueue.replayMemInst(fromCommit->commitInfo[tid].uncachedLoad);
1590                fromCommit->commitInfo[tid].uncachedLoad->setAtCommit();
1591            } else {
1592                instQueue.scheduleNonSpec(
1593                    fromCommit->commitInfo[tid].nonSpecSeqNum);
1594            }
1595        }
1596
1597        if (broadcast_free_entries) {
1598            toFetch->iewInfo[tid].iqCount =
1599                instQueue.getCount(tid);
1600            toFetch->iewInfo[tid].ldstqCount =
1601                ldstQueue.getCount(tid);
1602
1603            toRename->iewInfo[tid].usedIQ = true;
1604            toRename->iewInfo[tid].freeIQEntries =
1605                instQueue.numFreeEntries();
1606            toRename->iewInfo[tid].usedLSQ = true;
1607            toRename->iewInfo[tid].freeLSQEntries =
1608                ldstQueue.numFreeEntries(tid);
1609
1610            wroteToTimeBuffer = true;
1611        }
1612
1613        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
1614                tid, toRename->iewInfo[tid].dispatched);
1615    }
1616
1617    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
1618            "LSQ has %i free entries.\n",
1619            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
1620            ldstQueue.numFreeEntries());
1621
1622    updateStatus();
1623
1624    if (wroteToTimeBuffer) {
1625        DPRINTF(Activity, "Activity this cycle.\n");
1626        cpu->activityThisCycle();
1627    }
1628}
1629
1630template <class Impl>
1631void
1632DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
1633{
1634    int thread_number = inst->threadNumber;
1635
1636    //
1637    //  Pick off the software prefetches
1638    //
1639#ifdef TARGET_ALPHA
1640    if (inst->isDataPrefetch())
1641        iewExecutedSwp[thread_number]++;
1642    else
1643        iewIewExecutedcutedInsts++;
1644#else
1645    iewExecutedInsts++;
1646#endif
1647
1648    //
1649    //  Control operations
1650    //
1651    if (inst->isControl())
1652        iewExecutedBranches[thread_number]++;
1653
1654    //
1655    //  Memory operations
1656    //
1657    if (inst->isMemRef()) {
1658        iewExecutedRefs[thread_number]++;
1659
1660        if (inst->isLoad()) {
1661            iewExecLoadInsts[thread_number]++;
1662        }
1663    }
1664}
1665