iew_impl.hh revision 9783
18706Sandreas.hansson@arm.com/*
28706Sandreas.hansson@arm.com * Copyright (c) 2010-2013 ARM Limited
38706Sandreas.hansson@arm.com * All rights reserved.
48706Sandreas.hansson@arm.com *
58706Sandreas.hansson@arm.com * The license below extends only to copyright in the software and shall
68706Sandreas.hansson@arm.com * not be construed as granting a license to any other intellectual
78706Sandreas.hansson@arm.com * property including but not limited to intellectual property relating
88706Sandreas.hansson@arm.com * to a hardware implementation of the functionality of the software
98706Sandreas.hansson@arm.com * licensed hereunder.  You may use the software subject to the license
108706Sandreas.hansson@arm.com * terms below provided that you ensure that this notice is replicated
118706Sandreas.hansson@arm.com * unmodified and in its entirety in all distributions of the software,
128706Sandreas.hansson@arm.com * modified or unmodified, in source code or in binary form.
136892SBrad.Beckmann@amd.com *
146892SBrad.Beckmann@amd.com * Copyright (c) 2004-2006 The Regents of The University of Michigan
156892SBrad.Beckmann@amd.com * All rights reserved.
166892SBrad.Beckmann@amd.com *
176892SBrad.Beckmann@amd.com * Redistribution and use in source and binary forms, with or without
186892SBrad.Beckmann@amd.com * modification, are permitted provided that the following conditions are
196892SBrad.Beckmann@amd.com * met: redistributions of source code must retain the above copyright
206892SBrad.Beckmann@amd.com * notice, this list of conditions and the following disclaimer;
216892SBrad.Beckmann@amd.com * redistributions in binary form must reproduce the above copyright
226892SBrad.Beckmann@amd.com * notice, this list of conditions and the following disclaimer in the
236892SBrad.Beckmann@amd.com * documentation and/or other materials provided with the distribution;
246892SBrad.Beckmann@amd.com * neither the name of the copyright holders nor the names of its
256892SBrad.Beckmann@amd.com * contributors may be used to endorse or promote products derived from
266892SBrad.Beckmann@amd.com * this software without specific prior written permission.
276892SBrad.Beckmann@amd.com *
286892SBrad.Beckmann@amd.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
296892SBrad.Beckmann@amd.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
306892SBrad.Beckmann@amd.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
316892SBrad.Beckmann@amd.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
326892SBrad.Beckmann@amd.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
336892SBrad.Beckmann@amd.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
346892SBrad.Beckmann@amd.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
356892SBrad.Beckmann@amd.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
366892SBrad.Beckmann@amd.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
376892SBrad.Beckmann@amd.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
386892SBrad.Beckmann@amd.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
396892SBrad.Beckmann@amd.com *
406892SBrad.Beckmann@amd.com * Authors: Kevin Lim
416892SBrad.Beckmann@amd.com */
427563SBrad.Beckmann@amd.com
436892SBrad.Beckmann@amd.com// @todo: Fix the instantaneous communication among all the stages within
446892SBrad.Beckmann@amd.com// iew.  There's a clear delay between issue and execute, yet backwards
456892SBrad.Beckmann@amd.com// communication happens simultaneously.
466892SBrad.Beckmann@amd.com
477538SBrad.Beckmann@amd.com#include <queue>
488939SBrad.Beckmann@amd.com
498939SBrad.Beckmann@amd.com#include "arch/utility.hh"
508939SBrad.Beckmann@amd.com#include "config/the_isa.hh"
517538SBrad.Beckmann@amd.com#include "cpu/checker/cpu.hh"
527538SBrad.Beckmann@amd.com#include "cpu/o3/fu_pool.hh"
537538SBrad.Beckmann@amd.com#include "cpu/o3/iew.hh"
547538SBrad.Beckmann@amd.com#include "cpu/timebuf.hh"
557538SBrad.Beckmann@amd.com#include "debug/Activity.hh"
569576Snilay@cs.wisc.edu#include "debug/Decode.hh"
579576Snilay@cs.wisc.edu#include "debug/Drain.hh"
588612Stushar@csail.mit.edu#include "debug/IEW.hh"
598612Stushar@csail.mit.edu#include "debug/O3PipeView.hh"
607538SBrad.Beckmann@amd.com#include "params/DerivO3CPU.hh"
617538SBrad.Beckmann@amd.com
627917SBrad.Beckmann@amd.comusing namespace std;
637563SBrad.Beckmann@amd.com
647563SBrad.Beckmann@amd.comtemplate<class Impl>
657538SBrad.Beckmann@amd.comDefaultIEW<Impl>::DefaultIEW(O3CPU *_cpu, DerivO3CPUParams *params)
667538SBrad.Beckmann@amd.com    : issueToExecQueue(params->backComSize, params->forwardComSize),
677538SBrad.Beckmann@amd.com      cpu(_cpu),
687538SBrad.Beckmann@amd.com      instQueue(_cpu, this, params),
697538SBrad.Beckmann@amd.com      ldstQueue(_cpu, this, params),
707566SBrad.Beckmann@amd.com      fuPool(params->fuPool),
717566SBrad.Beckmann@amd.com      commitToIEWDelay(params->commitToIEWDelay),
727809Snilay@cs.wisc.edu      renameToIEWDelay(params->renameToIEWDelay),
737809Snilay@cs.wisc.edu      issueToExecuteDelay(params->issueToExecuteDelay),
747809Snilay@cs.wisc.edu      dispatchWidth(params->dispatchWidth),
757809Snilay@cs.wisc.edu      issueWidth(params->issueWidth),
768638Sgloh      wbOutstanding(0),
778638Sgloh      wbWidth(params->wbWidth),
787538SBrad.Beckmann@amd.com      numThreads(params->numThreads)
797538SBrad.Beckmann@amd.com{
807538SBrad.Beckmann@amd.com    _status = Active;
817538SBrad.Beckmann@amd.com    exeStatus = Running;
829100SBrad.Beckmann@amd.com    wbStatus = Idle;
839100SBrad.Beckmann@amd.com
849100SBrad.Beckmann@amd.com    // Setup wire to read instructions coming from issue.
859100SBrad.Beckmann@amd.com    fromIssue = issueToExecQueue.getWire(-issueToExecuteDelay);
869100SBrad.Beckmann@amd.com
879100SBrad.Beckmann@amd.com    // Instruction queue needs the queue between issue and execute.
889100SBrad.Beckmann@amd.com    instQueue.setIssueToExecuteQueue(&issueToExecQueue);
899100SBrad.Beckmann@amd.com
909100SBrad.Beckmann@amd.com    for (ThreadID tid = 0; tid < numThreads; tid++) {
919100SBrad.Beckmann@amd.com        dispatchStatus[tid] = Running;
928929Snilay@cs.wisc.edu        stalls[tid].commit = false;
936892SBrad.Beckmann@amd.com        fetchRedirect[tid] = false;
948638Sgloh    }
958690Snilay@cs.wisc.edu
968690Snilay@cs.wisc.edu    wbMax = wbWidth * params->wbDepth;
978436SBrad.Beckmann@amd.com
988436SBrad.Beckmann@amd.com    updateLSQNextCycle = false;
997032SBrad.Beckmann@amd.com
1007032SBrad.Beckmann@amd.com    ableToIssue = true;
1016923SBrad.Beckmann@amd.com
1029100SBrad.Beckmann@amd.com    skidBufferMax = (3 * (renameToIEWDelay * params->renameWidth)) + issueWidth;
1038929Snilay@cs.wisc.edu}
1047557SBrad.Beckmann@amd.com
1056923SBrad.Beckmann@amd.comtemplate <class Impl>
1066923SBrad.Beckmann@amd.comstd::string
1077557SBrad.Beckmann@amd.comDefaultIEW<Impl>::name() const
1088257SBrad.Beckmann@amd.com{
1098706Sandreas.hansson@arm.com    return cpu->name() + ".iew";
1108706Sandreas.hansson@arm.com}
1118706Sandreas.hansson@arm.com
1128923Sandreas.hansson@arm.comtemplate <class Impl>
1138706Sandreas.hansson@arm.comvoid
1148706Sandreas.hansson@arm.comDefaultIEW<Impl>::regStats()
1158706Sandreas.hansson@arm.com{
1168706Sandreas.hansson@arm.com    using namespace Stats;
1178732Sandreas.hansson@arm.com
1188839Sandreas.hansson@arm.com    instQueue.regStats();
1198732Sandreas.hansson@arm.com    ldstQueue.regStats();
1208732Sandreas.hansson@arm.com
1218257SBrad.Beckmann@amd.com    iewIdleCycles
1228257SBrad.Beckmann@amd.com        .name(name() + ".iewIdleCycles")
1238257SBrad.Beckmann@amd.com        .desc("Number of cycles IEW is idle");
1248257SBrad.Beckmann@amd.com
1258257SBrad.Beckmann@amd.com    iewSquashCycles
1268257SBrad.Beckmann@amd.com        .name(name() + ".iewSquashCycles")
1278257SBrad.Beckmann@amd.com        .desc("Number of cycles IEW is squashing");
1288257SBrad.Beckmann@amd.com
1298257SBrad.Beckmann@amd.com    iewBlockCycles
1308257SBrad.Beckmann@amd.com        .name(name() + ".iewBlockCycles")
1318257SBrad.Beckmann@amd.com        .desc("Number of cycles IEW is blocking");
1328257SBrad.Beckmann@amd.com
1338257SBrad.Beckmann@amd.com    iewUnblockCycles
1348257SBrad.Beckmann@amd.com        .name(name() + ".iewUnblockCycles")
1358257SBrad.Beckmann@amd.com        .desc("Number of cycles IEW is unblocking");
1368258SBrad.Beckmann@amd.com
1378258SBrad.Beckmann@amd.com    iewDispatchedInsts
1389274Snilay@cs.wisc.edu        .name(name() + ".iewDispatchedInsts")
1399148Spowerjg@cs.wisc.edu        .desc("Number of instructions dispatched to IQ");
1406892SBrad.Beckmann@amd.com
1419100SBrad.Beckmann@amd.com    iewDispSquashedInsts
1429100SBrad.Beckmann@amd.com        .name(name() + ".iewDispSquashedInsts")
1439148Spowerjg@cs.wisc.edu        .desc("Number of squashed instructions skipped by dispatch");
1446892SBrad.Beckmann@amd.com
1459148Spowerjg@cs.wisc.edu    iewDispLoadInsts
1469148Spowerjg@cs.wisc.edu        .name(name() + ".iewDispLoadInsts")
1479148Spowerjg@cs.wisc.edu        .desc("Number of dispatched load instructions");
1489148Spowerjg@cs.wisc.edu
1499148Spowerjg@cs.wisc.edu    iewDispStoreInsts
1509148Spowerjg@cs.wisc.edu        .name(name() + ".iewDispStoreInsts")
1519148Spowerjg@cs.wisc.edu        .desc("Number of dispatched store instructions");
1529148Spowerjg@cs.wisc.edu
1539148Spowerjg@cs.wisc.edu    iewDispNonSpecInsts
1549148Spowerjg@cs.wisc.edu        .name(name() + ".iewDispNonSpecInsts")
1559148Spowerjg@cs.wisc.edu        .desc("Number of dispatched non-speculative instructions");
1568257SBrad.Beckmann@amd.com
1578612Stushar@csail.mit.edu    iewIQFullEvents
1588612Stushar@csail.mit.edu        .name(name() + ".iewIQFullEvents")
1598612Stushar@csail.mit.edu        .desc("Number of times the IQ has become full, causing a stall");
1608612Stushar@csail.mit.edu
1618612Stushar@csail.mit.edu    iewLSQFullEvents
1628612Stushar@csail.mit.edu        .name(name() + ".iewLSQFullEvents")
1638612Stushar@csail.mit.edu        .desc("Number of times the LSQ has become full, causing a stall");
1646892SBrad.Beckmann@amd.com
1656903SBrad.Beckmann@amd.com    memOrderViolationEvents
1667563SBrad.Beckmann@amd.com        .name(name() + ".memOrderViolationEvents")
1677025SBrad.Beckmann@amd.com        .desc("Number of memory order violations");
1689148Spowerjg@cs.wisc.edu
1697025SBrad.Beckmann@amd.com    predictedTakenIncorrect
1707025SBrad.Beckmann@amd.com        .name(name() + ".predictedTakenIncorrect")
1717563SBrad.Beckmann@amd.com        .desc("Number of branches that were predicted taken incorrectly");
1726903SBrad.Beckmann@amd.com
1736903SBrad.Beckmann@amd.com    predictedNotTakenIncorrect
1747563SBrad.Beckmann@amd.com        .name(name() + ".predictedNotTakenIncorrect")
1757563SBrad.Beckmann@amd.com        .desc("Number of branches that were predicted not taken incorrectly");
1769318Spower.jg@gmail.com
1779318Spower.jg@gmail.com    branchMispredicts
1787563SBrad.Beckmann@amd.com        .name(name() + ".branchMispredicts")
1797563SBrad.Beckmann@amd.com        .desc("Number of branch mispredicts detected at execute");
1807563SBrad.Beckmann@amd.com
1817563SBrad.Beckmann@amd.com    branchMispredicts = predictedTakenIncorrect + predictedNotTakenIncorrect;
1829318Spower.jg@gmail.com
1839318Spower.jg@gmail.com    iewExecutedInsts
1849318Spower.jg@gmail.com        .name(name() + ".iewExecutedInsts")
1859318Spower.jg@gmail.com        .desc("Number of executed instructions");
1869148Spowerjg@cs.wisc.edu
1876903SBrad.Beckmann@amd.com    iewExecLoadInsts
1886903SBrad.Beckmann@amd.com        .init(cpu->numThreads)
1897563SBrad.Beckmann@amd.com        .name(name() + ".iewExecLoadInsts")
1909148Spowerjg@cs.wisc.edu        .desc("Number of load instructions executed")
1919232Sandreas.hansson@arm.com        .flags(total);
1929232Sandreas.hansson@arm.com
1938931Sandreas.hansson@arm.com    iewExecSquashedInsts
1946892SBrad.Beckmann@amd.com        .name(name() + ".iewExecSquashedInsts")
1958436SBrad.Beckmann@amd.com        .desc("Number of squashed instructions skipped in execute");
1968436SBrad.Beckmann@amd.com
1978436SBrad.Beckmann@amd.com    iewExecutedSwp
1988436SBrad.Beckmann@amd.com        .init(cpu->numThreads)
1998436SBrad.Beckmann@amd.com        .name(name() + ".exec_swp")
2008322Ssteve.reinhardt@amd.com        .desc("number of swp insts executed")
2017809Snilay@cs.wisc.edu        .flags(total);
202
203    iewExecutedNop
204        .init(cpu->numThreads)
205        .name(name() + ".exec_nop")
206        .desc("number of nop insts executed")
207        .flags(total);
208
209    iewExecutedRefs
210        .init(cpu->numThreads)
211        .name(name() + ".exec_refs")
212        .desc("number of memory reference insts executed")
213        .flags(total);
214
215    iewExecutedBranches
216        .init(cpu->numThreads)
217        .name(name() + ".exec_branches")
218        .desc("Number of branches executed")
219        .flags(total);
220
221    iewExecStoreInsts
222        .name(name() + ".exec_stores")
223        .desc("Number of stores executed")
224        .flags(total);
225    iewExecStoreInsts = iewExecutedRefs - iewExecLoadInsts;
226
227    iewExecRate
228        .name(name() + ".exec_rate")
229        .desc("Inst execution rate")
230        .flags(total);
231
232    iewExecRate = iewExecutedInsts / cpu->numCycles;
233
234    iewInstsToCommit
235        .init(cpu->numThreads)
236        .name(name() + ".wb_sent")
237        .desc("cumulative count of insts sent to commit")
238        .flags(total);
239
240    writebackCount
241        .init(cpu->numThreads)
242        .name(name() + ".wb_count")
243        .desc("cumulative count of insts written-back")
244        .flags(total);
245
246    producerInst
247        .init(cpu->numThreads)
248        .name(name() + ".wb_producers")
249        .desc("num instructions producing a value")
250        .flags(total);
251
252    consumerInst
253        .init(cpu->numThreads)
254        .name(name() + ".wb_consumers")
255        .desc("num instructions consuming a value")
256        .flags(total);
257
258    wbPenalized
259        .init(cpu->numThreads)
260        .name(name() + ".wb_penalized")
261        .desc("number of instrctions required to write to 'other' IQ")
262        .flags(total);
263
264    wbPenalizedRate
265        .name(name() + ".wb_penalized_rate")
266        .desc ("fraction of instructions written-back that wrote to 'other' IQ")
267        .flags(total);
268
269    wbPenalizedRate = wbPenalized / writebackCount;
270
271    wbFanout
272        .name(name() + ".wb_fanout")
273        .desc("average fanout of values written-back")
274        .flags(total);
275
276    wbFanout = producerInst / consumerInst;
277
278    wbRate
279        .name(name() + ".wb_rate")
280        .desc("insts written-back per cycle")
281        .flags(total);
282    wbRate = writebackCount / cpu->numCycles;
283}
284
285template<class Impl>
286void
287DefaultIEW<Impl>::startupStage()
288{
289    for (ThreadID tid = 0; tid < numThreads; tid++) {
290        toRename->iewInfo[tid].usedIQ = true;
291        toRename->iewInfo[tid].freeIQEntries =
292            instQueue.numFreeEntries(tid);
293
294        toRename->iewInfo[tid].usedLSQ = true;
295        toRename->iewInfo[tid].freeLSQEntries =
296            ldstQueue.numFreeEntries(tid);
297    }
298
299    // Initialize the checker's dcache port here
300    if (cpu->checker) {
301        cpu->checker->setDcachePort(&cpu->getDataPort());
302    }
303
304    cpu->activateStage(O3CPU::IEWIdx);
305}
306
307template<class Impl>
308void
309DefaultIEW<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
310{
311    timeBuffer = tb_ptr;
312
313    // Setup wire to read information from time buffer, from commit.
314    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
315
316    // Setup wire to write information back to previous stages.
317    toRename = timeBuffer->getWire(0);
318
319    toFetch = timeBuffer->getWire(0);
320
321    // Instruction queue also needs main time buffer.
322    instQueue.setTimeBuffer(tb_ptr);
323}
324
325template<class Impl>
326void
327DefaultIEW<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
328{
329    renameQueue = rq_ptr;
330
331    // Setup wire to read information from rename queue.
332    fromRename = renameQueue->getWire(-renameToIEWDelay);
333}
334
335template<class Impl>
336void
337DefaultIEW<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
338{
339    iewQueue = iq_ptr;
340
341    // Setup wire to write instructions to commit.
342    toCommit = iewQueue->getWire(0);
343}
344
345template<class Impl>
346void
347DefaultIEW<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
348{
349    activeThreads = at_ptr;
350
351    ldstQueue.setActiveThreads(at_ptr);
352    instQueue.setActiveThreads(at_ptr);
353}
354
355template<class Impl>
356void
357DefaultIEW<Impl>::setScoreboard(Scoreboard *sb_ptr)
358{
359    scoreboard = sb_ptr;
360}
361
362template <class Impl>
363bool
364DefaultIEW<Impl>::isDrained() const
365{
366    bool drained(ldstQueue.isDrained());
367
368    for (ThreadID tid = 0; tid < numThreads; tid++) {
369        if (!insts[tid].empty()) {
370            DPRINTF(Drain, "%i: Insts not empty.\n", tid);
371            drained = false;
372        }
373        if (!skidBuffer[tid].empty()) {
374            DPRINTF(Drain, "%i: Skid buffer not empty.\n", tid);
375            drained = false;
376        }
377    }
378
379    // Also check the FU pool as instructions are "stored" in FU
380    // completion events until they are done and not accounted for
381    // above
382    if (drained && !fuPool->isDrained()) {
383        DPRINTF(Drain, "FU pool still busy.\n");
384        drained = false;
385    }
386
387    return drained;
388}
389
390template <class Impl>
391void
392DefaultIEW<Impl>::drainSanityCheck() const
393{
394    assert(isDrained());
395
396    instQueue.drainSanityCheck();
397    ldstQueue.drainSanityCheck();
398}
399
400template <class Impl>
401void
402DefaultIEW<Impl>::takeOverFrom()
403{
404    // Reset all state.
405    _status = Active;
406    exeStatus = Running;
407    wbStatus = Idle;
408
409    instQueue.takeOverFrom();
410    ldstQueue.takeOverFrom();
411    fuPool->takeOverFrom();
412
413    startupStage();
414    cpu->activityThisCycle();
415
416    for (ThreadID tid = 0; tid < numThreads; tid++) {
417        dispatchStatus[tid] = Running;
418        stalls[tid].commit = false;
419        fetchRedirect[tid] = false;
420    }
421
422    updateLSQNextCycle = false;
423
424    for (int i = 0; i < issueToExecQueue.getSize(); ++i) {
425        issueToExecQueue.advance();
426    }
427}
428
429template<class Impl>
430void
431DefaultIEW<Impl>::squash(ThreadID tid)
432{
433    DPRINTF(IEW, "[tid:%i]: Squashing all instructions.\n", tid);
434
435    // Tell the IQ to start squashing.
436    instQueue.squash(tid);
437
438    // Tell the LDSTQ to start squashing.
439    ldstQueue.squash(fromCommit->commitInfo[tid].doneSeqNum, tid);
440    updatedQueues = true;
441
442    // Clear the skid buffer in case it has any data in it.
443    DPRINTF(IEW, "[tid:%i]: Removing skidbuffer instructions until [sn:%i].\n",
444            tid, fromCommit->commitInfo[tid].doneSeqNum);
445
446    while (!skidBuffer[tid].empty()) {
447        if (skidBuffer[tid].front()->isLoad() ||
448            skidBuffer[tid].front()->isStore() ) {
449            toRename->iewInfo[tid].dispatchedToLSQ++;
450        }
451
452        toRename->iewInfo[tid].dispatched++;
453
454        skidBuffer[tid].pop();
455    }
456
457    emptyRenameInsts(tid);
458}
459
460template<class Impl>
461void
462DefaultIEW<Impl>::squashDueToBranch(DynInstPtr &inst, ThreadID tid)
463{
464    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, PC: %s "
465            "[sn:%i].\n", tid, inst->pcState(), inst->seqNum);
466
467    if (toCommit->squash[tid] == false ||
468            inst->seqNum < toCommit->squashedSeqNum[tid]) {
469        toCommit->squash[tid] = true;
470        toCommit->squashedSeqNum[tid] = inst->seqNum;
471        toCommit->branchTaken[tid] = inst->pcState().branching();
472
473        TheISA::PCState pc = inst->pcState();
474        TheISA::advancePC(pc, inst->staticInst);
475
476        toCommit->pc[tid] = pc;
477        toCommit->mispredictInst[tid] = inst;
478        toCommit->includeSquashInst[tid] = false;
479
480        wroteToTimeBuffer = true;
481    }
482
483}
484
485template<class Impl>
486void
487DefaultIEW<Impl>::squashDueToMemOrder(DynInstPtr &inst, ThreadID tid)
488{
489    DPRINTF(IEW, "[tid:%i]: Memory violation, squashing violator and younger "
490            "insts, PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
491    // Need to include inst->seqNum in the following comparison to cover the
492    // corner case when a branch misprediction and a memory violation for the
493    // same instruction (e.g. load PC) are detected in the same cycle.  In this
494    // case the memory violator should take precedence over the branch
495    // misprediction because it requires the violator itself to be included in
496    // the squash.
497    if (toCommit->squash[tid] == false ||
498            inst->seqNum <= toCommit->squashedSeqNum[tid]) {
499        toCommit->squash[tid] = true;
500
501        toCommit->squashedSeqNum[tid] = inst->seqNum;
502        toCommit->pc[tid] = inst->pcState();
503        toCommit->mispredictInst[tid] = NULL;
504
505        // Must include the memory violator in the squash.
506        toCommit->includeSquashInst[tid] = true;
507
508        wroteToTimeBuffer = true;
509    }
510}
511
512template<class Impl>
513void
514DefaultIEW<Impl>::squashDueToMemBlocked(DynInstPtr &inst, ThreadID tid)
515{
516    DPRINTF(IEW, "[tid:%i]: Memory blocked, squashing load and younger insts, "
517            "PC: %s [sn:%i].\n", tid, inst->pcState(), inst->seqNum);
518    if (toCommit->squash[tid] == false ||
519            inst->seqNum < toCommit->squashedSeqNum[tid]) {
520        toCommit->squash[tid] = true;
521
522        toCommit->squashedSeqNum[tid] = inst->seqNum;
523        toCommit->pc[tid] = inst->pcState();
524        toCommit->mispredictInst[tid] = NULL;
525
526        // Must include the broadcasted SN in the squash.
527        toCommit->includeSquashInst[tid] = true;
528
529        ldstQueue.setLoadBlockedHandled(tid);
530
531        wroteToTimeBuffer = true;
532    }
533}
534
535template<class Impl>
536void
537DefaultIEW<Impl>::block(ThreadID tid)
538{
539    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);
540
541    if (dispatchStatus[tid] != Blocked &&
542        dispatchStatus[tid] != Unblocking) {
543        toRename->iewBlock[tid] = true;
544        wroteToTimeBuffer = true;
545    }
546
547    // Add the current inputs to the skid buffer so they can be
548    // reprocessed when this stage unblocks.
549    skidInsert(tid);
550
551    dispatchStatus[tid] = Blocked;
552}
553
554template<class Impl>
555void
556DefaultIEW<Impl>::unblock(ThreadID tid)
557{
558    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
559            "buffer %u.\n",tid, tid);
560
561    // If the skid bufffer is empty, signal back to previous stages to unblock.
562    // Also switch status to running.
563    if (skidBuffer[tid].empty()) {
564        toRename->iewUnblock[tid] = true;
565        wroteToTimeBuffer = true;
566        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
567        dispatchStatus[tid] = Running;
568    }
569}
570
571template<class Impl>
572void
573DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
574{
575    instQueue.wakeDependents(inst);
576}
577
578template<class Impl>
579void
580DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
581{
582    instQueue.rescheduleMemInst(inst);
583}
584
585template<class Impl>
586void
587DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
588{
589    instQueue.replayMemInst(inst);
590}
591
592template<class Impl>
593void
594DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
595{
596    // This function should not be called after writebackInsts in a
597    // single cycle.  That will cause problems with an instruction
598    // being added to the queue to commit without being processed by
599    // writebackInsts prior to being sent to commit.
600
601    // First check the time slot that this instruction will write
602    // to.  If there are free write ports at the time, then go ahead
603    // and write the instruction to that time.  If there are not,
604    // keep looking back to see where's the first time there's a
605    // free slot.
606    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
607        ++wbNumInst;
608        if (wbNumInst == wbWidth) {
609            ++wbCycle;
610            wbNumInst = 0;
611        }
612
613        assert((wbCycle * wbWidth + wbNumInst) <= wbMax);
614    }
615
616    DPRINTF(IEW, "Current wb cycle: %i, width: %i, numInst: %i\nwbActual:%i\n",
617            wbCycle, wbWidth, wbNumInst, wbCycle * wbWidth + wbNumInst);
618    // Add finished instruction to queue to commit.
619    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
620    (*iewQueue)[wbCycle].size++;
621}
622
623template <class Impl>
624unsigned
625DefaultIEW<Impl>::validInstsFromRename()
626{
627    unsigned inst_count = 0;
628
629    for (int i=0; i<fromRename->size; i++) {
630        if (!fromRename->insts[i]->isSquashed())
631            inst_count++;
632    }
633
634    return inst_count;
635}
636
637template<class Impl>
638void
639DefaultIEW<Impl>::skidInsert(ThreadID tid)
640{
641    DynInstPtr inst = NULL;
642
643    while (!insts[tid].empty()) {
644        inst = insts[tid].front();
645
646        insts[tid].pop();
647
648        DPRINTF(Decode,"[tid:%i]: Inserting [sn:%lli] PC:%s into "
649                "dispatch skidBuffer %i\n",tid, inst->seqNum,
650                inst->pcState(),tid);
651
652        skidBuffer[tid].push(inst);
653    }
654
655    assert(skidBuffer[tid].size() <= skidBufferMax &&
656           "Skidbuffer Exceeded Max Size");
657}
658
659template<class Impl>
660int
661DefaultIEW<Impl>::skidCount()
662{
663    int max=0;
664
665    list<ThreadID>::iterator threads = activeThreads->begin();
666    list<ThreadID>::iterator end = activeThreads->end();
667
668    while (threads != end) {
669        ThreadID tid = *threads++;
670        unsigned thread_count = skidBuffer[tid].size();
671        if (max < thread_count)
672            max = thread_count;
673    }
674
675    return max;
676}
677
678template<class Impl>
679bool
680DefaultIEW<Impl>::skidsEmpty()
681{
682    list<ThreadID>::iterator threads = activeThreads->begin();
683    list<ThreadID>::iterator end = activeThreads->end();
684
685    while (threads != end) {
686        ThreadID tid = *threads++;
687
688        if (!skidBuffer[tid].empty())
689            return false;
690    }
691
692    return true;
693}
694
695template <class Impl>
696void
697DefaultIEW<Impl>::updateStatus()
698{
699    bool any_unblocking = false;
700
701    list<ThreadID>::iterator threads = activeThreads->begin();
702    list<ThreadID>::iterator end = activeThreads->end();
703
704    while (threads != end) {
705        ThreadID tid = *threads++;
706
707        if (dispatchStatus[tid] == Unblocking) {
708            any_unblocking = true;
709            break;
710        }
711    }
712
713    // If there are no ready instructions waiting to be scheduled by the IQ,
714    // and there's no stores waiting to write back, and dispatch is not
715    // unblocking, then there is no internal activity for the IEW stage.
716    instQueue.intInstQueueReads++;
717    if (_status == Active && !instQueue.hasReadyInsts() &&
718        !ldstQueue.willWB() && !any_unblocking) {
719        DPRINTF(IEW, "IEW switching to idle\n");
720
721        deactivateStage();
722
723        _status = Inactive;
724    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
725                                       ldstQueue.willWB() ||
726                                       any_unblocking)) {
727        // Otherwise there is internal activity.  Set to active.
728        DPRINTF(IEW, "IEW switching to active\n");
729
730        activateStage();
731
732        _status = Active;
733    }
734}
735
736template <class Impl>
737void
738DefaultIEW<Impl>::resetEntries()
739{
740    instQueue.resetEntries();
741    ldstQueue.resetEntries();
742}
743
744template <class Impl>
745void
746DefaultIEW<Impl>::readStallSignals(ThreadID tid)
747{
748    if (fromCommit->commitBlock[tid]) {
749        stalls[tid].commit = true;
750    }
751
752    if (fromCommit->commitUnblock[tid]) {
753        assert(stalls[tid].commit);
754        stalls[tid].commit = false;
755    }
756}
757
758template <class Impl>
759bool
760DefaultIEW<Impl>::checkStall(ThreadID tid)
761{
762    bool ret_val(false);
763
764    if (stalls[tid].commit) {
765        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
766        ret_val = true;
767    } else if (instQueue.isFull(tid)) {
768        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
769        ret_val = true;
770    } else if (ldstQueue.isFull(tid)) {
771        DPRINTF(IEW,"[tid:%i]: Stall: LSQ is full\n",tid);
772
773        if (ldstQueue.numLoads(tid) > 0 ) {
774
775            DPRINTF(IEW,"[tid:%i]: LSQ oldest load: [sn:%i] \n",
776                    tid,ldstQueue.getLoadHeadSeqNum(tid));
777        }
778
779        if (ldstQueue.numStores(tid) > 0) {
780
781            DPRINTF(IEW,"[tid:%i]: LSQ oldest store: [sn:%i] \n",
782                    tid,ldstQueue.getStoreHeadSeqNum(tid));
783        }
784
785        ret_val = true;
786    } else if (ldstQueue.isStalled(tid)) {
787        DPRINTF(IEW,"[tid:%i]: Stall: LSQ stall detected.\n",tid);
788        ret_val = true;
789    }
790
791    return ret_val;
792}
793
794template <class Impl>
795void
796DefaultIEW<Impl>::checkSignalsAndUpdate(ThreadID tid)
797{
798    // Check if there's a squash signal, squash if there is
799    // Check stall signals, block if there is.
800    // If status was Blocked
801    //     if so then go to unblocking
802    // If status was Squashing
803    //     check if squashing is not high.  Switch to running this cycle.
804
805    readStallSignals(tid);
806
807    if (fromCommit->commitInfo[tid].squash) {
808        squash(tid);
809
810        if (dispatchStatus[tid] == Blocked ||
811            dispatchStatus[tid] == Unblocking) {
812            toRename->iewUnblock[tid] = true;
813            wroteToTimeBuffer = true;
814        }
815
816        dispatchStatus[tid] = Squashing;
817        fetchRedirect[tid] = false;
818        return;
819    }
820
821    if (fromCommit->commitInfo[tid].robSquashing) {
822        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);
823
824        dispatchStatus[tid] = Squashing;
825        emptyRenameInsts(tid);
826        wroteToTimeBuffer = true;
827        return;
828    }
829
830    if (checkStall(tid)) {
831        block(tid);
832        dispatchStatus[tid] = Blocked;
833        return;
834    }
835
836    if (dispatchStatus[tid] == Blocked) {
837        // Status from previous cycle was blocked, but there are no more stall
838        // conditions.  Switch over to unblocking.
839        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
840                tid);
841
842        dispatchStatus[tid] = Unblocking;
843
844        unblock(tid);
845
846        return;
847    }
848
849    if (dispatchStatus[tid] == Squashing) {
850        // Switch status to running if rename isn't being told to block or
851        // squash this cycle.
852        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
853                tid);
854
855        dispatchStatus[tid] = Running;
856
857        return;
858    }
859}
860
861template <class Impl>
862void
863DefaultIEW<Impl>::sortInsts()
864{
865    int insts_from_rename = fromRename->size;
866#ifdef DEBUG
867    for (ThreadID tid = 0; tid < numThreads; tid++)
868        assert(insts[tid].empty());
869#endif
870    for (int i = 0; i < insts_from_rename; ++i) {
871        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
872    }
873}
874
875template <class Impl>
876void
877DefaultIEW<Impl>::emptyRenameInsts(ThreadID tid)
878{
879    DPRINTF(IEW, "[tid:%i]: Removing incoming rename instructions\n", tid);
880
881    while (!insts[tid].empty()) {
882
883        if (insts[tid].front()->isLoad() ||
884            insts[tid].front()->isStore() ) {
885            toRename->iewInfo[tid].dispatchedToLSQ++;
886        }
887
888        toRename->iewInfo[tid].dispatched++;
889
890        insts[tid].pop();
891    }
892}
893
894template <class Impl>
895void
896DefaultIEW<Impl>::wakeCPU()
897{
898    cpu->wakeCPU();
899}
900
901template <class Impl>
902void
903DefaultIEW<Impl>::activityThisCycle()
904{
905    DPRINTF(Activity, "Activity this cycle.\n");
906    cpu->activityThisCycle();
907}
908
909template <class Impl>
910inline void
911DefaultIEW<Impl>::activateStage()
912{
913    DPRINTF(Activity, "Activating stage.\n");
914    cpu->activateStage(O3CPU::IEWIdx);
915}
916
917template <class Impl>
918inline void
919DefaultIEW<Impl>::deactivateStage()
920{
921    DPRINTF(Activity, "Deactivating stage.\n");
922    cpu->deactivateStage(O3CPU::IEWIdx);
923}
924
925template<class Impl>
926void
927DefaultIEW<Impl>::dispatch(ThreadID tid)
928{
929    // If status is Running or idle,
930    //     call dispatchInsts()
931    // If status is Unblocking,
932    //     buffer any instructions coming from rename
933    //     continue trying to empty skid buffer
934    //     check if stall conditions have passed
935
936    if (dispatchStatus[tid] == Blocked) {
937        ++iewBlockCycles;
938
939    } else if (dispatchStatus[tid] == Squashing) {
940        ++iewSquashCycles;
941    }
942
943    // Dispatch should try to dispatch as many instructions as its bandwidth
944    // will allow, as long as it is not currently blocked.
945    if (dispatchStatus[tid] == Running ||
946        dispatchStatus[tid] == Idle) {
947        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
948                "dispatch.\n", tid);
949
950        dispatchInsts(tid);
951    } else if (dispatchStatus[tid] == Unblocking) {
952        // Make sure that the skid buffer has something in it if the
953        // status is unblocking.
954        assert(!skidsEmpty());
955
956        // If the status was unblocking, then instructions from the skid
957        // buffer were used.  Remove those instructions and handle
958        // the rest of unblocking.
959        dispatchInsts(tid);
960
961        ++iewUnblockCycles;
962
963        if (validInstsFromRename()) {
964            // Add the current inputs to the skid buffer so they can be
965            // reprocessed when this stage unblocks.
966            skidInsert(tid);
967        }
968
969        unblock(tid);
970    }
971}
972
973template <class Impl>
974void
975DefaultIEW<Impl>::dispatchInsts(ThreadID tid)
976{
977    // Obtain instructions from skid buffer if unblocking, or queue from rename
978    // otherwise.
979    std::queue<DynInstPtr> &insts_to_dispatch =
980        dispatchStatus[tid] == Unblocking ?
981        skidBuffer[tid] : insts[tid];
982
983    int insts_to_add = insts_to_dispatch.size();
984
985    DynInstPtr inst;
986    bool add_to_iq = false;
987    int dis_num_inst = 0;
988
989    // Loop through the instructions, putting them in the instruction
990    // queue.
991    for ( ; dis_num_inst < insts_to_add &&
992              dis_num_inst < dispatchWidth;
993          ++dis_num_inst)
994    {
995        inst = insts_to_dispatch.front();
996
997        if (dispatchStatus[tid] == Unblocking) {
998            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
999                    "buffer\n", tid);
1000        }
1001
1002        // Make sure there's a valid instruction there.
1003        assert(inst);
1004
1005        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %s [sn:%lli] [tid:%i] to "
1006                "IQ.\n",
1007                tid, inst->pcState(), inst->seqNum, inst->threadNumber);
1008
1009        // Be sure to mark these instructions as ready so that the
1010        // commit stage can go ahead and execute them, and mark
1011        // them as issued so the IQ doesn't reprocess them.
1012
1013        // Check for squashed instructions.
1014        if (inst->isSquashed()) {
1015            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
1016                    "not adding to IQ.\n", tid);
1017
1018            ++iewDispSquashedInsts;
1019
1020            insts_to_dispatch.pop();
1021
1022            //Tell Rename That An Instruction has been processed
1023            if (inst->isLoad() || inst->isStore()) {
1024                toRename->iewInfo[tid].dispatchedToLSQ++;
1025            }
1026            toRename->iewInfo[tid].dispatched++;
1027
1028            continue;
1029        }
1030
1031        // Check for full conditions.
1032        if (instQueue.isFull(tid)) {
1033            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);
1034
1035            // Call function to start blocking.
1036            block(tid);
1037
1038            // Set unblock to false. Special case where we are using
1039            // skidbuffer (unblocking) instructions but then we still
1040            // get full in the IQ.
1041            toRename->iewUnblock[tid] = false;
1042
1043            ++iewIQFullEvents;
1044            break;
1045        } else if (ldstQueue.isFull(tid)) {
1046            DPRINTF(IEW, "[tid:%i]: Issue: LSQ has become full.\n",tid);
1047
1048            // Call function to start blocking.
1049            block(tid);
1050
1051            // Set unblock to false. Special case where we are using
1052            // skidbuffer (unblocking) instructions but then we still
1053            // get full in the IQ.
1054            toRename->iewUnblock[tid] = false;
1055
1056            ++iewLSQFullEvents;
1057            break;
1058        }
1059
1060        // Otherwise issue the instruction just fine.
1061        if (inst->isLoad()) {
1062            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1063                    "encountered, adding to LSQ.\n", tid);
1064
1065            // Reserve a spot in the load store queue for this
1066            // memory access.
1067            ldstQueue.insertLoad(inst);
1068
1069            ++iewDispLoadInsts;
1070
1071            add_to_iq = true;
1072
1073            toRename->iewInfo[tid].dispatchedToLSQ++;
1074        } else if (inst->isStore()) {
1075            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1076                    "encountered, adding to LSQ.\n", tid);
1077
1078            ldstQueue.insertStore(inst);
1079
1080            ++iewDispStoreInsts;
1081
1082            if (inst->isStoreConditional()) {
1083                // Store conditionals need to be set as "canCommit()"
1084                // so that commit can process them when they reach the
1085                // head of commit.
1086                // @todo: This is somewhat specific to Alpha.
1087                inst->setCanCommit();
1088                instQueue.insertNonSpec(inst);
1089                add_to_iq = false;
1090
1091                ++iewDispNonSpecInsts;
1092            } else {
1093                add_to_iq = true;
1094            }
1095
1096            toRename->iewInfo[tid].dispatchedToLSQ++;
1097        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
1098            // Same as non-speculative stores.
1099            inst->setCanCommit();
1100            instQueue.insertBarrier(inst);
1101            add_to_iq = false;
1102        } else if (inst->isNop()) {
1103            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
1104                    "skipping.\n", tid);
1105
1106            inst->setIssued();
1107            inst->setExecuted();
1108            inst->setCanCommit();
1109
1110            instQueue.recordProducer(inst);
1111
1112            iewExecutedNop[tid]++;
1113
1114            add_to_iq = false;
1115        } else if (inst->isExecuted()) {
1116            assert(0 && "Instruction shouldn't be executed.\n");
1117            DPRINTF(IEW, "Issue: Executed branch encountered, "
1118                    "skipping.\n");
1119
1120            inst->setIssued();
1121            inst->setCanCommit();
1122
1123            instQueue.recordProducer(inst);
1124
1125            add_to_iq = false;
1126        } else {
1127            add_to_iq = true;
1128        }
1129        if (inst->isNonSpeculative()) {
1130            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
1131                    "encountered, skipping.\n", tid);
1132
1133            // Same as non-speculative stores.
1134            inst->setCanCommit();
1135
1136            // Specifically insert it as nonspeculative.
1137            instQueue.insertNonSpec(inst);
1138
1139            ++iewDispNonSpecInsts;
1140
1141            add_to_iq = false;
1142        }
1143
1144        // If the instruction queue is not full, then add the
1145        // instruction.
1146        if (add_to_iq) {
1147            instQueue.insert(inst);
1148        }
1149
1150        insts_to_dispatch.pop();
1151
1152        toRename->iewInfo[tid].dispatched++;
1153
1154        ++iewDispatchedInsts;
1155
1156#if TRACING_ON
1157        inst->dispatchTick = curTick() - inst->fetchTick;
1158#endif
1159    }
1160
1161    if (!insts_to_dispatch.empty()) {
1162        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n", tid);
1163        block(tid);
1164        toRename->iewUnblock[tid] = false;
1165    }
1166
1167    if (dispatchStatus[tid] == Idle && dis_num_inst) {
1168        dispatchStatus[tid] = Running;
1169
1170        updatedQueues = true;
1171    }
1172
1173    dis_num_inst = 0;
1174}
1175
1176template <class Impl>
1177void
1178DefaultIEW<Impl>::printAvailableInsts()
1179{
1180    int inst = 0;
1181
1182    std::cout << "Available Instructions: ";
1183
1184    while (fromIssue->insts[inst]) {
1185
1186        if (inst%3==0) std::cout << "\n\t";
1187
1188        std::cout << "PC: " << fromIssue->insts[inst]->pcState()
1189             << " TN: " << fromIssue->insts[inst]->threadNumber
1190             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";
1191
1192        inst++;
1193
1194    }
1195
1196    std::cout << "\n";
1197}
1198
1199template <class Impl>
1200void
1201DefaultIEW<Impl>::executeInsts()
1202{
1203    wbNumInst = 0;
1204    wbCycle = 0;
1205
1206    list<ThreadID>::iterator threads = activeThreads->begin();
1207    list<ThreadID>::iterator end = activeThreads->end();
1208
1209    while (threads != end) {
1210        ThreadID tid = *threads++;
1211        fetchRedirect[tid] = false;
1212    }
1213
1214    // Uncomment this if you want to see all available instructions.
1215    // @todo This doesn't actually work anymore, we should fix it.
1216//    printAvailableInsts();
1217
1218    // Execute/writeback any instructions that are available.
1219    int insts_to_execute = fromIssue->size;
1220    int inst_num = 0;
1221    for (; inst_num < insts_to_execute;
1222          ++inst_num) {
1223
1224        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");
1225
1226        DynInstPtr inst = instQueue.getInstToExecute();
1227
1228        DPRINTF(IEW, "Execute: Processing PC %s, [tid:%i] [sn:%i].\n",
1229                inst->pcState(), inst->threadNumber,inst->seqNum);
1230
1231        // Check if the instruction is squashed; if so then skip it
1232        if (inst->isSquashed()) {
1233            DPRINTF(IEW, "Execute: Instruction was squashed. PC: %s, [tid:%i]"
1234                         " [sn:%i]\n", inst->pcState(), inst->threadNumber,
1235                         inst->seqNum);
1236
1237            // Consider this instruction executed so that commit can go
1238            // ahead and retire the instruction.
1239            inst->setExecuted();
1240
1241            // Not sure if I should set this here or just let commit try to
1242            // commit any squashed instructions.  I like the latter a bit more.
1243            inst->setCanCommit();
1244
1245            ++iewExecSquashedInsts;
1246
1247            decrWb(inst->seqNum);
1248            continue;
1249        }
1250
1251        Fault fault = NoFault;
1252
1253        // Execute instruction.
1254        // Note that if the instruction faults, it will be handled
1255        // at the commit stage.
1256        if (inst->isMemRef()) {
1257            DPRINTF(IEW, "Execute: Calculating address for memory "
1258                    "reference.\n");
1259
1260            // Tell the LDSTQ to execute this instruction (if it is a load).
1261            if (inst->isLoad()) {
1262                // Loads will mark themselves as executed, and their writeback
1263                // event adds the instruction to the queue to commit
1264                fault = ldstQueue.executeLoad(inst);
1265
1266                if (inst->isTranslationDelayed() &&
1267                    fault == NoFault) {
1268                    // A hw page table walk is currently going on; the
1269                    // instruction must be deferred.
1270                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1271                            "load.\n");
1272                    instQueue.deferMemInst(inst);
1273                    continue;
1274                }
1275
1276                if (inst->isDataPrefetch() || inst->isInstPrefetch()) {
1277                    inst->fault = NoFault;
1278                }
1279            } else if (inst->isStore()) {
1280                fault = ldstQueue.executeStore(inst);
1281
1282                if (inst->isTranslationDelayed() &&
1283                    fault == NoFault) {
1284                    // A hw page table walk is currently going on; the
1285                    // instruction must be deferred.
1286                    DPRINTF(IEW, "Execute: Delayed translation, deferring "
1287                            "store.\n");
1288                    instQueue.deferMemInst(inst);
1289                    continue;
1290                }
1291
1292                // If the store had a fault then it may not have a mem req
1293                if (fault != NoFault || inst->readPredicate() == false ||
1294                        !inst->isStoreConditional()) {
1295                    // If the instruction faulted, then we need to send it along
1296                    // to commit without the instruction completing.
1297                    // Send this instruction to commit, also make sure iew stage
1298                    // realizes there is activity.
1299                    inst->setExecuted();
1300                    instToCommit(inst);
1301                    activityThisCycle();
1302                }
1303
1304                // Store conditionals will mark themselves as
1305                // executed, and their writeback event will add the
1306                // instruction to the queue to commit.
1307            } else {
1308                panic("Unexpected memory type!\n");
1309            }
1310
1311        } else {
1312            // If the instruction has already faulted, then skip executing it.
1313            // Such case can happen when it faulted during ITLB translation.
1314            // If we execute the instruction (even if it's a nop) the fault
1315            // will be replaced and we will lose it.
1316            if (inst->getFault() == NoFault) {
1317                inst->execute();
1318                if (inst->readPredicate() == false)
1319                    inst->forwardOldRegs();
1320            }
1321
1322            inst->setExecuted();
1323
1324            instToCommit(inst);
1325        }
1326
1327        updateExeInstStats(inst);
1328
1329        // Check if branch prediction was correct, if not then we need
1330        // to tell commit to squash in flight instructions.  Only
1331        // handle this if there hasn't already been something that
1332        // redirects fetch in this group of instructions.
1333
1334        // This probably needs to prioritize the redirects if a different
1335        // scheduler is used.  Currently the scheduler schedules the oldest
1336        // instruction first, so the branch resolution order will be correct.
1337        ThreadID tid = inst->threadNumber;
1338
1339        if (!fetchRedirect[tid] ||
1340            !toCommit->squash[tid] ||
1341            toCommit->squashedSeqNum[tid] > inst->seqNum) {
1342
1343            // Prevent testing for misprediction on load instructions,
1344            // that have not been executed.
1345            bool loadNotExecuted = !inst->isExecuted() && inst->isLoad();
1346
1347            if (inst->mispredicted() && !loadNotExecuted) {
1348                fetchRedirect[tid] = true;
1349
1350                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1351                DPRINTF(IEW, "Predicted target was PC: %s.\n",
1352                        inst->readPredTarg());
1353                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %s.\n",
1354                        inst->pcState());
1355                // If incorrect, then signal the ROB that it must be squashed.
1356                squashDueToBranch(inst, tid);
1357
1358                if (inst->readPredTaken()) {
1359                    predictedTakenIncorrect++;
1360                } else {
1361                    predictedNotTakenIncorrect++;
1362                }
1363            } else if (ldstQueue.violation(tid)) {
1364                assert(inst->isMemRef());
1365                // If there was an ordering violation, then get the
1366                // DynInst that caused the violation.  Note that this
1367                // clears the violation signal.
1368                DynInstPtr violator;
1369                violator = ldstQueue.getMemDepViolator(tid);
1370
1371                DPRINTF(IEW, "LDSTQ detected a violation. Violator PC: %s "
1372                        "[sn:%lli], inst PC: %s [sn:%lli]. Addr is: %#x.\n",
1373                        violator->pcState(), violator->seqNum,
1374                        inst->pcState(), inst->seqNum, inst->physEffAddr);
1375
1376                fetchRedirect[tid] = true;
1377
1378                // Tell the instruction queue that a violation has occured.
1379                instQueue.violation(inst, violator);
1380
1381                // Squash.
1382                squashDueToMemOrder(violator, tid);
1383
1384                ++memOrderViolationEvents;
1385            } else if (ldstQueue.loadBlocked(tid) &&
1386                       !ldstQueue.isLoadBlockedHandled(tid)) {
1387                fetchRedirect[tid] = true;
1388
1389                DPRINTF(IEW, "Load operation couldn't execute because the "
1390                        "memory system is blocked.  PC: %s [sn:%lli]\n",
1391                        inst->pcState(), inst->seqNum);
1392
1393                squashDueToMemBlocked(inst, tid);
1394            }
1395        } else {
1396            // Reset any state associated with redirects that will not
1397            // be used.
1398            if (ldstQueue.violation(tid)) {
1399                assert(inst->isMemRef());
1400
1401                DynInstPtr violator = ldstQueue.getMemDepViolator(tid);
1402
1403                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1404                        "%s, inst PC: %s.  Addr is: %#x.\n",
1405                        violator->pcState(), inst->pcState(),
1406                        inst->physEffAddr);
1407                DPRINTF(IEW, "Violation will not be handled because "
1408                        "already squashing\n");
1409
1410                ++memOrderViolationEvents;
1411            }
1412            if (ldstQueue.loadBlocked(tid) &&
1413                !ldstQueue.isLoadBlockedHandled(tid)) {
1414                DPRINTF(IEW, "Load operation couldn't execute because the "
1415                        "memory system is blocked.  PC: %s [sn:%lli]\n",
1416                        inst->pcState(), inst->seqNum);
1417                DPRINTF(IEW, "Blocked load will not be handled because "
1418                        "already squashing\n");
1419
1420                ldstQueue.setLoadBlockedHandled(tid);
1421            }
1422
1423        }
1424    }
1425
1426    // Update and record activity if we processed any instructions.
1427    if (inst_num) {
1428        if (exeStatus == Idle) {
1429            exeStatus = Running;
1430        }
1431
1432        updatedQueues = true;
1433
1434        cpu->activityThisCycle();
1435    }
1436
1437    // Need to reset this in case a writeback event needs to write into the
1438    // iew queue.  That way the writeback event will write into the correct
1439    // spot in the queue.
1440    wbNumInst = 0;
1441
1442}
1443
1444template <class Impl>
1445void
1446DefaultIEW<Impl>::writebackInsts()
1447{
1448    // Loop through the head of the time buffer and wake any
1449    // dependents.  These instructions are about to write back.  Also
1450    // mark scoreboard that this instruction is finally complete.
1451    // Either have IEW have direct access to scoreboard, or have this
1452    // as part of backwards communication.
1453    for (int inst_num = 0; inst_num < wbWidth &&
1454             toCommit->insts[inst_num]; inst_num++) {
1455        DynInstPtr inst = toCommit->insts[inst_num];
1456        ThreadID tid = inst->threadNumber;
1457
1458        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %s.\n",
1459                inst->seqNum, inst->pcState());
1460
1461        iewInstsToCommit[tid]++;
1462
1463        // Some instructions will be sent to commit without having
1464        // executed because they need commit to handle them.
1465        // E.g. Uncached loads have not actually executed when they
1466        // are first sent to commit.  Instead commit must tell the LSQ
1467        // when it's ready to execute the uncached load.
1468        if (!inst->isSquashed() && inst->isExecuted() && inst->getFault() == NoFault) {
1469            int dependents = instQueue.wakeDependents(inst);
1470
1471            for (int i = 0; i < inst->numDestRegs(); i++) {
1472                //mark as Ready
1473                DPRINTF(IEW,"Setting Destination Register %i\n",
1474                        inst->renamedDestRegIdx(i));
1475                scoreboard->setReg(inst->renamedDestRegIdx(i));
1476            }
1477
1478            if (dependents) {
1479                producerInst[tid]++;
1480                consumerInst[tid]+= dependents;
1481            }
1482            writebackCount[tid]++;
1483        }
1484
1485        decrWb(inst->seqNum);
1486    }
1487}
1488
1489template<class Impl>
1490void
1491DefaultIEW<Impl>::tick()
1492{
1493    wbNumInst = 0;
1494    wbCycle = 0;
1495
1496    wroteToTimeBuffer = false;
1497    updatedQueues = false;
1498
1499    sortInsts();
1500
1501    // Free function units marked as being freed this cycle.
1502    fuPool->processFreeUnits();
1503
1504    list<ThreadID>::iterator threads = activeThreads->begin();
1505    list<ThreadID>::iterator end = activeThreads->end();
1506
1507    // Check stall and squash signals, dispatch any instructions.
1508    while (threads != end) {
1509        ThreadID tid = *threads++;
1510
1511        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);
1512
1513        checkSignalsAndUpdate(tid);
1514        dispatch(tid);
1515    }
1516
1517    if (exeStatus != Squashing) {
1518        executeInsts();
1519
1520        writebackInsts();
1521
1522        // Have the instruction queue try to schedule any ready instructions.
1523        // (In actuality, this scheduling is for instructions that will
1524        // be executed next cycle.)
1525        instQueue.scheduleReadyInsts();
1526
1527        // Also should advance its own time buffers if the stage ran.
1528        // Not the best place for it, but this works (hopefully).
1529        issueToExecQueue.advance();
1530    }
1531
1532    bool broadcast_free_entries = false;
1533
1534    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
1535        exeStatus = Idle;
1536        updateLSQNextCycle = false;
1537
1538        broadcast_free_entries = true;
1539    }
1540
1541    // Writeback any stores using any leftover bandwidth.
1542    ldstQueue.writebackStores();
1543
1544    // Check the committed load/store signals to see if there's a load
1545    // or store to commit.  Also check if it's being told to execute a
1546    // nonspeculative instruction.
1547    // This is pretty inefficient...
1548
1549    threads = activeThreads->begin();
1550    while (threads != end) {
1551        ThreadID tid = (*threads++);
1552
1553        DPRINTF(IEW,"Processing [tid:%i]\n",tid);
1554
1555        // Update structures based on instructions committed.
1556        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
1557            !fromCommit->commitInfo[tid].squash &&
1558            !fromCommit->commitInfo[tid].robSquashing) {
1559
1560            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);
1561
1562            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);
1563
1564            updateLSQNextCycle = true;
1565            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
1566        }
1567
1568        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {
1569
1570            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
1571            if (fromCommit->commitInfo[tid].uncached) {
1572                instQueue.replayMemInst(fromCommit->commitInfo[tid].uncachedLoad);
1573                fromCommit->commitInfo[tid].uncachedLoad->setAtCommit();
1574            } else {
1575                instQueue.scheduleNonSpec(
1576                    fromCommit->commitInfo[tid].nonSpecSeqNum);
1577            }
1578        }
1579
1580        if (broadcast_free_entries) {
1581            toFetch->iewInfo[tid].iqCount =
1582                instQueue.getCount(tid);
1583            toFetch->iewInfo[tid].ldstqCount =
1584                ldstQueue.getCount(tid);
1585
1586            toRename->iewInfo[tid].usedIQ = true;
1587            toRename->iewInfo[tid].freeIQEntries =
1588                instQueue.numFreeEntries();
1589            toRename->iewInfo[tid].usedLSQ = true;
1590            toRename->iewInfo[tid].freeLSQEntries =
1591                ldstQueue.numFreeEntries(tid);
1592
1593            wroteToTimeBuffer = true;
1594        }
1595
1596        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
1597                tid, toRename->iewInfo[tid].dispatched);
1598    }
1599
1600    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
1601            "LSQ has %i free entries.\n",
1602            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
1603            ldstQueue.numFreeEntries());
1604
1605    updateStatus();
1606
1607    if (wroteToTimeBuffer) {
1608        DPRINTF(Activity, "Activity this cycle.\n");
1609        cpu->activityThisCycle();
1610    }
1611}
1612
1613template <class Impl>
1614void
1615DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
1616{
1617    ThreadID tid = inst->threadNumber;
1618
1619    iewExecutedInsts++;
1620
1621#if TRACING_ON
1622    if (DTRACE(O3PipeView)) {
1623        inst->completeTick = curTick() - inst->fetchTick;
1624    }
1625#endif
1626
1627    //
1628    //  Control operations
1629    //
1630    if (inst->isControl())
1631        iewExecutedBranches[tid]++;
1632
1633    //
1634    //  Memory operations
1635    //
1636    if (inst->isMemRef()) {
1637        iewExecutedRefs[tid]++;
1638
1639        if (inst->isLoad()) {
1640            iewExecLoadInsts[tid]++;
1641        }
1642    }
1643}
1644
1645template <class Impl>
1646void
1647DefaultIEW<Impl>::checkMisprediction(DynInstPtr &inst)
1648{
1649    ThreadID tid = inst->threadNumber;
1650
1651    if (!fetchRedirect[tid] ||
1652        !toCommit->squash[tid] ||
1653        toCommit->squashedSeqNum[tid] > inst->seqNum) {
1654
1655        if (inst->mispredicted()) {
1656            fetchRedirect[tid] = true;
1657
1658            DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1659            DPRINTF(IEW, "Predicted target was PC:%#x, NPC:%#x.\n",
1660                    inst->predInstAddr(), inst->predNextInstAddr());
1661            DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x,"
1662                    " NPC: %#x.\n", inst->nextInstAddr(),
1663                    inst->nextInstAddr());
1664            // If incorrect, then signal the ROB that it must be squashed.
1665            squashDueToBranch(inst, tid);
1666
1667            if (inst->readPredTaken()) {
1668                predictedTakenIncorrect++;
1669            } else {
1670                predictedNotTakenIncorrect++;
1671            }
1672        }
1673    }
1674}
1675