iew_impl.hh revision 2843
18839Sandreas.hansson@arm.com/*
28839Sandreas.hansson@arm.com * Copyright (c) 2004-2006 The Regents of The University of Michigan
38839Sandreas.hansson@arm.com * All rights reserved.
48839Sandreas.hansson@arm.com *
58839Sandreas.hansson@arm.com * Redistribution and use in source and binary forms, with or without
68839Sandreas.hansson@arm.com * modification, are permitted provided that the following conditions are
78839Sandreas.hansson@arm.com * met: redistributions of source code must retain the above copyright
88839Sandreas.hansson@arm.com * notice, this list of conditions and the following disclaimer;
98839Sandreas.hansson@arm.com * redistributions in binary form must reproduce the above copyright
108839Sandreas.hansson@arm.com * notice, this list of conditions and the following disclaimer in the
118839Sandreas.hansson@arm.com * documentation and/or other materials provided with the distribution;
128839Sandreas.hansson@arm.com * neither the name of the copyright holders nor the names of its
135335Shines@cs.fsu.edu * contributors may be used to endorse or promote products derived from
147897Shestness@cs.utexas.edu * this software without specific prior written permission.
154486Sbinkertn@umich.edu *
164486Sbinkertn@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
174486Sbinkertn@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
184486Sbinkertn@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
194486Sbinkertn@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
204486Sbinkertn@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
214486Sbinkertn@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
224486Sbinkertn@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
234486Sbinkertn@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
244486Sbinkertn@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
254486Sbinkertn@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
264486Sbinkertn@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
274486Sbinkertn@umich.edu *
284486Sbinkertn@umich.edu * Authors: Kevin Lim
294486Sbinkertn@umich.edu */
304486Sbinkertn@umich.edu
314486Sbinkertn@umich.edu// @todo: Fix the instantaneous communication among all the stages within
324486Sbinkertn@umich.edu// iew.  There's a clear delay between issue and execute, yet backwards
334486Sbinkertn@umich.edu// communication happens simultaneously.
344486Sbinkertn@umich.edu
354486Sbinkertn@umich.edu#include <queue>
364486Sbinkertn@umich.edu
374486Sbinkertn@umich.edu#include "base/timebuf.hh"
384486Sbinkertn@umich.edu#include "cpu/o3/fu_pool.hh"
394486Sbinkertn@umich.edu#include "cpu/o3/iew.hh"
404486Sbinkertn@umich.edu
417897Shestness@cs.utexas.eduusing namespace std;
428839Sandreas.hansson@arm.com
434486Sbinkertn@umich.edutemplate<class Impl>
446654Snate@binkert.orgDefaultIEW<Impl>::DefaultIEW(Params *params)
456654Snate@binkert.org    : // @todo: Make this into a parameter.
466654Snate@binkert.org      issueToExecQueue(5, 5),
473102SN/A      instQueue(params),
483102SN/A      ldstQueue(params),
496654Snate@binkert.org      fuPool(params->fuPool),
509036Sandreas.hansson@arm.com      commitToIEWDelay(params->commitToIEWDelay),
514776Sgblack@eecs.umich.edu      renameToIEWDelay(params->renameToIEWDelay),
524776Sgblack@eecs.umich.edu      issueToExecuteDelay(params->issueToExecuteDelay),
536654Snate@binkert.org      dispatchWidth(params->dispatchWidth),
542667SN/A      issueWidth(params->issueWidth),
554776Sgblack@eecs.umich.edu      wbOutstanding(0),
564776Sgblack@eecs.umich.edu      wbWidth(params->wbWidth),
576654Snate@binkert.org      numThreads(params->numberOfThreads),
586023Snate@binkert.org      switchedOut(false)
598745Sgblack@eecs.umich.edu{
609384SAndreas.Sandberg@arm.com    _status = Active;
619384SAndreas.Sandberg@arm.com    exeStatus = Running;
626654Snate@binkert.org    wbStatus = Idle;
636022Sgblack@eecs.umich.edu
648745Sgblack@eecs.umich.edu    // Setup wire to read instructions coming from issue.
659384SAndreas.Sandberg@arm.com    fromIssue = issueToExecQueue.getWire(-issueToExecuteDelay);
669384SAndreas.Sandberg@arm.com
676654Snate@binkert.org    // Instruction queue needs the queue between issue and execute.
686022Sgblack@eecs.umich.edu    instQueue.setIssueToExecuteQueue(&issueToExecQueue);
698745Sgblack@eecs.umich.edu
709384SAndreas.Sandberg@arm.com    instQueue.setIEW(this);
719384SAndreas.Sandberg@arm.com    ldstQueue.setIEW(this);
726654Snate@binkert.org
736022Sgblack@eecs.umich.edu    for (int i=0; i < numThreads; i++) {
748745Sgblack@eecs.umich.edu        dispatchStatus[i] = Running;
759384SAndreas.Sandberg@arm.com        stalls[i].commit = false;
769384SAndreas.Sandberg@arm.com        fetchRedirect[i] = false;
776654Snate@binkert.org    }
786116Snate@binkert.org
798745Sgblack@eecs.umich.edu    wbMax = wbWidth * params->wbDepth;
809384SAndreas.Sandberg@arm.com
819384SAndreas.Sandberg@arm.com    updateLSQNextCycle = false;
826691Stjones1@inf.ed.ac.uk
836691Stjones1@inf.ed.ac.uk    ableToIssue = true;
848745Sgblack@eecs.umich.edu
859384SAndreas.Sandberg@arm.com    skidBufferMax = (3 * (renameToIEWDelay * params->renameWidth)) + issueWidth;
869384SAndreas.Sandberg@arm.com}
874486Sbinkertn@umich.edu
885529Snate@binkert.orgtemplate <class Impl>
891366SN/Astd::string
901310SN/ADefaultIEW<Impl>::name() const
919338SAndreas.Sandberg@arm.com{
929254SAndreas.Sandberg@arm.com    return cpu->name() + ".iew";
939254SAndreas.Sandberg@arm.com}
949254SAndreas.Sandberg@arm.com
959254SAndreas.Sandberg@arm.comtemplate <class Impl>
969254SAndreas.Sandberg@arm.comvoid
979254SAndreas.Sandberg@arm.comDefaultIEW<Impl>::regStats()
989254SAndreas.Sandberg@arm.com{
999254SAndreas.Sandberg@arm.com    using namespace Stats;
1009254SAndreas.Sandberg@arm.com
1019254SAndreas.Sandberg@arm.com    instQueue.regStats();
1029254SAndreas.Sandberg@arm.com    ldstQueue.regStats();
1039254SAndreas.Sandberg@arm.com
1042901SN/A    iewIdleCycles
1055712Shsul@eecs.umich.edu        .name(name() + ".iewIdleCycles")
1065529Snate@binkert.org        .desc("Number of cycles IEW is idle");
1075529Snate@binkert.org
1085529Snate@binkert.org    iewSquashCycles
1099161Sandreas.hansson@arm.com        .name(name() + ".iewSquashCycles")
1105529Snate@binkert.org        .desc("Number of cycles IEW is squashing");
1115821Ssaidi@eecs.umich.edu
1123170SN/A    iewBlockCycles
1135780Ssteve.reinhardt@amd.com        .name(name() + ".iewBlockCycles")
1145780Ssteve.reinhardt@amd.com        .desc("Number of cycles IEW is blocking");
1155780Ssteve.reinhardt@amd.com
1165780Ssteve.reinhardt@amd.com    iewUnblockCycles
1175780Ssteve.reinhardt@amd.com        .name(name() + ".iewUnblockCycles")
1188784Sgblack@eecs.umich.edu        .desc("Number of cycles IEW is unblocking");
1198784Sgblack@eecs.umich.edu
1208784Sgblack@eecs.umich.edu    iewDispatchedInsts
1218793Sgblack@eecs.umich.edu        .name(name() + ".iewDispatchedInsts")
1221310SN/A        .desc("Number of instructions dispatched to IQ");
1236654Snate@binkert.org
1246022Sgblack@eecs.umich.edu    iewDispSquashedInsts
1256022Sgblack@eecs.umich.edu        .name(name() + ".iewDispSquashedInsts")
1268745Sgblack@eecs.umich.edu        .desc("Number of squashed instructions skipped by dispatch");
1278863Snilay@cs.wisc.edu
1289384SAndreas.Sandberg@arm.com    iewDispLoadInsts
1296654Snate@binkert.org        .name(name() + ".iewDispLoadInsts")
1306023Snate@binkert.org        .desc("Number of dispatched load instructions");
1316023Snate@binkert.org
1328745Sgblack@eecs.umich.edu    iewDispStoreInsts
1338863Snilay@cs.wisc.edu        .name(name() + ".iewDispStoreInsts")
1349384SAndreas.Sandberg@arm.com        .desc("Number of dispatched store instructions");
1356654Snate@binkert.org
1366022Sgblack@eecs.umich.edu    iewDispNonSpecInsts
1376022Sgblack@eecs.umich.edu        .name(name() + ".iewDispNonSpecInsts")
1388863Snilay@cs.wisc.edu        .desc("Number of dispatched non-speculative instructions");
1399384SAndreas.Sandberg@arm.com
1406654Snate@binkert.org    iewIQFullEvents
1416022Sgblack@eecs.umich.edu        .name(name() + ".iewIQFullEvents")
1426022Sgblack@eecs.umich.edu        .desc("Number of times the IQ has become full, causing a stall");
1438745Sgblack@eecs.umich.edu
1448863Snilay@cs.wisc.edu    iewLSQFullEvents
1459384SAndreas.Sandberg@arm.com        .name(name() + ".iewLSQFullEvents")
1466654Snate@binkert.org        .desc("Number of times the LSQ has become full, causing a stall");
1476116Snate@binkert.org
1486116Snate@binkert.org    memOrderViolationEvents
1498745Sgblack@eecs.umich.edu        .name(name() + ".memOrderViolationEvents")
1508863Snilay@cs.wisc.edu        .desc("Number of memory order violations");
1519384SAndreas.Sandberg@arm.com
1526691Stjones1@inf.ed.ac.uk    predictedTakenIncorrect
1536691Stjones1@inf.ed.ac.uk        .name(name() + ".predictedTakenIncorrect")
1546691Stjones1@inf.ed.ac.uk        .desc("Number of branches that were predicted taken incorrectly");
1556691Stjones1@inf.ed.ac.uk
1568745Sgblack@eecs.umich.edu    predictedNotTakenIncorrect
1578863Snilay@cs.wisc.edu        .name(name() + ".predictedNotTakenIncorrect")
1589384SAndreas.Sandberg@arm.com        .desc("Number of branches that were predicted not taken incorrectly");
1594997Sgblack@eecs.umich.edu
1604997Sgblack@eecs.umich.edu    branchMispredicts
1616654Snate@binkert.org        .name(name() + ".branchMispredicts")
1624997Sgblack@eecs.umich.edu        .desc("Number of branch mispredicts detected at execute");
1634997Sgblack@eecs.umich.edu
1641310SN/A    branchMispredicts = predictedTakenIncorrect + predictedNotTakenIncorrect;
1651310SN/A
1661310SN/A    iewExecutedInsts
1671310SN/A        .name(name() + ".EXEC:insts")
1681310SN/A        .desc("Number of executed instructions");
1691310SN/A
1701310SN/A    iewExecLoadInsts
1711310SN/A        .init(cpu->number_of_threads)
1729180Sandreas.hansson@arm.com        .name(name() + ".EXEC:loads")
1739180Sandreas.hansson@arm.com        .desc("Number of load instructions executed")
1741310SN/A        .flags(total);
1751369SN/A
1761310SN/A    iewExecSquashedInsts
1771634SN/A        .name(name() + ".EXEC:squashedInsts")
1784776Sgblack@eecs.umich.edu        .desc("Number of squashed instructions skipped in execute");
1794776Sgblack@eecs.umich.edu
1808839Sandreas.hansson@arm.com    iewExecutedSwp
1818839Sandreas.hansson@arm.com        .init(cpu->number_of_threads)
1828707Sandreas.hansson@arm.com        .name(name() + ".EXEC:swp")
1838707Sandreas.hansson@arm.com        .desc("number of swp insts executed")
1848756Sgblack@eecs.umich.edu        .flags(total);
1858707Sandreas.hansson@arm.com
1867876Sgblack@eecs.umich.edu    iewExecutedNop
1878839Sandreas.hansson@arm.com        .init(cpu->number_of_threads)
1888839Sandreas.hansson@arm.com        .name(name() + ".EXEC:nop")
1898745Sgblack@eecs.umich.edu        .desc("number of nop insts executed")
1908839Sandreas.hansson@arm.com        .flags(total);
1918839Sandreas.hansson@arm.com
1922998SN/A    iewExecutedRefs
1938863Snilay@cs.wisc.edu        .init(cpu->number_of_threads)
1948863Snilay@cs.wisc.edu        .name(name() + ".EXEC:refs")
1958863Snilay@cs.wisc.edu        .desc("number of memory reference insts executed")
1968863Snilay@cs.wisc.edu        .flags(total);
1978863Snilay@cs.wisc.edu
1988863Snilay@cs.wisc.edu    iewExecutedBranches
1998863Snilay@cs.wisc.edu        .init(cpu->number_of_threads)
2008863Snilay@cs.wisc.edu        .name(name() + ".EXEC:branches")
2018863Snilay@cs.wisc.edu        .desc("Number of branches executed")
2028863Snilay@cs.wisc.edu        .flags(total);
2038863Snilay@cs.wisc.edu
2048863Snilay@cs.wisc.edu    iewExecStoreInsts
2058863Snilay@cs.wisc.edu        .name(name() + ".EXEC:stores")
2068863Snilay@cs.wisc.edu        .desc("Number of stores executed")
2078863Snilay@cs.wisc.edu        .flags(total);
2088863Snilay@cs.wisc.edu    iewExecStoreInsts = iewExecutedRefs - iewExecLoadInsts;
2098863Snilay@cs.wisc.edu
2108863Snilay@cs.wisc.edu    iewExecRate
2118863Snilay@cs.wisc.edu        .name(name() + ".EXEC:rate")
2127876Sgblack@eecs.umich.edu        .desc("Inst execution rate")
2137876Sgblack@eecs.umich.edu        .flags(total);
2148839Sandreas.hansson@arm.com
2157404SAli.Saidi@ARM.com    iewExecRate = iewExecutedInsts / cpu->numCycles;
2167876Sgblack@eecs.umich.edu
2178839Sandreas.hansson@arm.com    iewInstsToCommit
2188839Sandreas.hansson@arm.com        .init(cpu->number_of_threads)
2198839Sandreas.hansson@arm.com        .name(name() + ".WB:sent")
2208839Sandreas.hansson@arm.com        .desc("cumulative count of insts sent to commit")
2217876Sgblack@eecs.umich.edu        .flags(total);
2227876Sgblack@eecs.umich.edu
2237876Sgblack@eecs.umich.edu    writebackCount
2247876Sgblack@eecs.umich.edu        .init(cpu->number_of_threads)
2257876Sgblack@eecs.umich.edu        .name(name() + ".WB:count")
2267876Sgblack@eecs.umich.edu        .desc("cumulative count of insts written-back")
2272998SN/A        .flags(total);
2287868Sgblack@eecs.umich.edu
2292998SN/A    producerInst
2302998SN/A        .init(cpu->number_of_threads)
2312998SN/A        .name(name() + ".WB:producers")
2322998SN/A        .desc("num instructions producing a value")
2337876Sgblack@eecs.umich.edu        .flags(total);
2348796Sgblack@eecs.umich.edu
2358796Sgblack@eecs.umich.edu    consumerInst
2368796Sgblack@eecs.umich.edu        .init(cpu->number_of_threads)
2378796Sgblack@eecs.umich.edu        .name(name() + ".WB:consumers")
2388796Sgblack@eecs.umich.edu        .desc("num instructions consuming a value")
2398796Sgblack@eecs.umich.edu        .flags(total);
2408796Sgblack@eecs.umich.edu
2418796Sgblack@eecs.umich.edu    wbPenalized
2428796Sgblack@eecs.umich.edu        .init(cpu->number_of_threads)
2438796Sgblack@eecs.umich.edu        .name(name() + ".WB:penalized")
2448887Sgeoffrey.blake@arm.com        .desc("number of instrctions required to write to 'other' IQ")
2458809Sgblack@eecs.umich.edu        .flags(total);
2468809Sgblack@eecs.umich.edu
2478887Sgeoffrey.blake@arm.com    wbPenalizedRate
2488809Sgblack@eecs.umich.edu        .name(name() + ".WB:penalized_rate")
2498809Sgblack@eecs.umich.edu        .desc ("fraction of instructions written-back that wrote to 'other' IQ")
2502998SN/A        .flags(total);
2517868Sgblack@eecs.umich.edu
2527868Sgblack@eecs.umich.edu    wbPenalizedRate = wbPenalized / writebackCount;
2539284Sandreas.hansson@arm.com
2549284Sandreas.hansson@arm.com    wbFanout
2559284Sandreas.hansson@arm.com        .name(name() + ".WB:fanout")
2569284Sandreas.hansson@arm.com        .desc("average fanout of values written-back")
2577876Sgblack@eecs.umich.edu        .flags(total);
2582998SN/A
2598839Sandreas.hansson@arm.com    wbFanout = producerInst / consumerInst;
2607876Sgblack@eecs.umich.edu
2618887Sgeoffrey.blake@arm.com    wbRate
2629384SAndreas.Sandberg@arm.com        .name(name() + ".WB:rate")
2639384SAndreas.Sandberg@arm.com        .desc("insts written-back per cycle")
2649384SAndreas.Sandberg@arm.com        .flags(total);
2659384SAndreas.Sandberg@arm.com    wbRate = writebackCount / cpu->numCycles;
2669384SAndreas.Sandberg@arm.com}
2678887Sgeoffrey.blake@arm.com
2688887Sgeoffrey.blake@arm.comtemplate<class Impl>
269void
270DefaultIEW<Impl>::initStage()
271{
272    for (int tid=0; tid < numThreads; tid++) {
273        toRename->iewInfo[tid].usedIQ = true;
274        toRename->iewInfo[tid].freeIQEntries =
275            instQueue.numFreeEntries(tid);
276
277        toRename->iewInfo[tid].usedLSQ = true;
278        toRename->iewInfo[tid].freeLSQEntries =
279            ldstQueue.numFreeEntries(tid);
280    }
281}
282
283template<class Impl>
284void
285DefaultIEW<Impl>::setCPU(O3CPU *cpu_ptr)
286{
287    DPRINTF(IEW, "Setting CPU pointer.\n");
288    cpu = cpu_ptr;
289
290    instQueue.setCPU(cpu_ptr);
291    ldstQueue.setCPU(cpu_ptr);
292
293    cpu->activateStage(O3CPU::IEWIdx);
294}
295
296template<class Impl>
297void
298DefaultIEW<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
299{
300    DPRINTF(IEW, "Setting time buffer pointer.\n");
301    timeBuffer = tb_ptr;
302
303    // Setup wire to read information from time buffer, from commit.
304    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
305
306    // Setup wire to write information back to previous stages.
307    toRename = timeBuffer->getWire(0);
308
309    toFetch = timeBuffer->getWire(0);
310
311    // Instruction queue also needs main time buffer.
312    instQueue.setTimeBuffer(tb_ptr);
313}
314
315template<class Impl>
316void
317DefaultIEW<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
318{
319    DPRINTF(IEW, "Setting rename queue pointer.\n");
320    renameQueue = rq_ptr;
321
322    // Setup wire to read information from rename queue.
323    fromRename = renameQueue->getWire(-renameToIEWDelay);
324}
325
326template<class Impl>
327void
328DefaultIEW<Impl>::setIEWQueue(TimeBuffer<IEWStruct> *iq_ptr)
329{
330    DPRINTF(IEW, "Setting IEW queue pointer.\n");
331    iewQueue = iq_ptr;
332
333    // Setup wire to write instructions to commit.
334    toCommit = iewQueue->getWire(0);
335}
336
337template<class Impl>
338void
339DefaultIEW<Impl>::setActiveThreads(list<unsigned> *at_ptr)
340{
341    DPRINTF(IEW, "Setting active threads list pointer.\n");
342    activeThreads = at_ptr;
343
344    ldstQueue.setActiveThreads(at_ptr);
345    instQueue.setActiveThreads(at_ptr);
346}
347
348template<class Impl>
349void
350DefaultIEW<Impl>::setScoreboard(Scoreboard *sb_ptr)
351{
352    DPRINTF(IEW, "Setting scoreboard pointer.\n");
353    scoreboard = sb_ptr;
354}
355
356template <class Impl>
357void
358DefaultIEW<Impl>::drain()
359{
360    // IEW is ready to drain at any time.
361    cpu->signalDrained();
362}
363
364template <class Impl>
365void
366DefaultIEW<Impl>::resume()
367{
368}
369
370template <class Impl>
371void
372DefaultIEW<Impl>::switchOut()
373{
374    // Clear any state.
375    switchedOut = true;
376
377    instQueue.switchOut();
378    ldstQueue.switchOut();
379    fuPool->switchOut();
380
381    for (int i = 0; i < numThreads; i++) {
382        while (!insts[i].empty())
383            insts[i].pop();
384        while (!skidBuffer[i].empty())
385            skidBuffer[i].pop();
386    }
387}
388
389template <class Impl>
390void
391DefaultIEW<Impl>::takeOverFrom()
392{
393    // Reset all state.
394    _status = Active;
395    exeStatus = Running;
396    wbStatus = Idle;
397    switchedOut = false;
398
399    instQueue.takeOverFrom();
400    ldstQueue.takeOverFrom();
401    fuPool->takeOverFrom();
402
403    initStage();
404    cpu->activityThisCycle();
405
406    for (int i=0; i < numThreads; i++) {
407        dispatchStatus[i] = Running;
408        stalls[i].commit = false;
409        fetchRedirect[i] = false;
410    }
411
412    updateLSQNextCycle = false;
413
414    // @todo: Fix hardcoded number
415    for (int i = 0; i < 6; ++i) {
416        issueToExecQueue.advance();
417    }
418}
419
420template<class Impl>
421void
422DefaultIEW<Impl>::squash(unsigned tid)
423{
424    DPRINTF(IEW, "[tid:%i]: Squashing all instructions.\n",
425            tid);
426
427    // Tell the IQ to start squashing.
428    instQueue.squash(tid);
429
430    // Tell the LDSTQ to start squashing.
431    ldstQueue.squash(fromCommit->commitInfo[tid].doneSeqNum, tid);
432
433    updatedQueues = true;
434
435    // Clear the skid buffer in case it has any data in it.
436    while (!skidBuffer[tid].empty()) {
437
438        if (skidBuffer[tid].front()->isLoad() ||
439            skidBuffer[tid].front()->isStore() ) {
440            toRename->iewInfo[tid].dispatchedToLSQ++;
441        }
442
443        toRename->iewInfo[tid].dispatched++;
444
445        skidBuffer[tid].pop();
446    }
447
448    emptyRenameInsts(tid);
449}
450
451template<class Impl>
452void
453DefaultIEW<Impl>::squashDueToBranch(DynInstPtr &inst, unsigned tid)
454{
455    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, PC: %#x "
456            "[sn:%i].\n", tid, inst->readPC(), inst->seqNum);
457
458    toCommit->squash[tid] = true;
459    toCommit->squashedSeqNum[tid] = inst->seqNum;
460    toCommit->mispredPC[tid] = inst->readPC();
461    toCommit->nextPC[tid] = inst->readNextPC();
462    toCommit->branchMispredict[tid] = true;
463    toCommit->branchTaken[tid] = inst->readNextPC() !=
464        (inst->readPC() + sizeof(TheISA::MachInst));
465
466    toCommit->includeSquashInst[tid] = false;
467
468    wroteToTimeBuffer = true;
469}
470
471template<class Impl>
472void
473DefaultIEW<Impl>::squashDueToMemOrder(DynInstPtr &inst, unsigned tid)
474{
475    DPRINTF(IEW, "[tid:%i]: Squashing from a specific instruction, "
476            "PC: %#x [sn:%i].\n", tid, inst->readPC(), inst->seqNum);
477
478    toCommit->squash[tid] = true;
479    toCommit->squashedSeqNum[tid] = inst->seqNum;
480    toCommit->nextPC[tid] = inst->readNextPC();
481
482    toCommit->includeSquashInst[tid] = false;
483
484    wroteToTimeBuffer = true;
485}
486
487template<class Impl>
488void
489DefaultIEW<Impl>::squashDueToMemBlocked(DynInstPtr &inst, unsigned tid)
490{
491    DPRINTF(IEW, "[tid:%i]: Memory blocked, squashing load and younger insts, "
492            "PC: %#x [sn:%i].\n", tid, inst->readPC(), inst->seqNum);
493
494    toCommit->squash[tid] = true;
495    toCommit->squashedSeqNum[tid] = inst->seqNum;
496    toCommit->nextPC[tid] = inst->readPC();
497
498    // Must include the broadcasted SN in the squash.
499    toCommit->includeSquashInst[tid] = true;
500
501    ldstQueue.setLoadBlockedHandled(tid);
502
503    wroteToTimeBuffer = true;
504}
505
506template<class Impl>
507void
508DefaultIEW<Impl>::block(unsigned tid)
509{
510    DPRINTF(IEW, "[tid:%u]: Blocking.\n", tid);
511
512    if (dispatchStatus[tid] != Blocked &&
513        dispatchStatus[tid] != Unblocking) {
514        toRename->iewBlock[tid] = true;
515        wroteToTimeBuffer = true;
516    }
517
518    // Add the current inputs to the skid buffer so they can be
519    // reprocessed when this stage unblocks.
520    skidInsert(tid);
521
522    dispatchStatus[tid] = Blocked;
523}
524
525template<class Impl>
526void
527DefaultIEW<Impl>::unblock(unsigned tid)
528{
529    DPRINTF(IEW, "[tid:%i]: Reading instructions out of the skid "
530            "buffer %u.\n",tid, tid);
531
532    // If the skid bufffer is empty, signal back to previous stages to unblock.
533    // Also switch status to running.
534    if (skidBuffer[tid].empty()) {
535        toRename->iewUnblock[tid] = true;
536        wroteToTimeBuffer = true;
537        DPRINTF(IEW, "[tid:%i]: Done unblocking.\n",tid);
538        dispatchStatus[tid] = Running;
539    }
540}
541
542template<class Impl>
543void
544DefaultIEW<Impl>::wakeDependents(DynInstPtr &inst)
545{
546    instQueue.wakeDependents(inst);
547}
548
549template<class Impl>
550void
551DefaultIEW<Impl>::rescheduleMemInst(DynInstPtr &inst)
552{
553    instQueue.rescheduleMemInst(inst);
554}
555
556template<class Impl>
557void
558DefaultIEW<Impl>::replayMemInst(DynInstPtr &inst)
559{
560    instQueue.replayMemInst(inst);
561}
562
563template<class Impl>
564void
565DefaultIEW<Impl>::instToCommit(DynInstPtr &inst)
566{
567    // First check the time slot that this instruction will write
568    // to.  If there are free write ports at the time, then go ahead
569    // and write the instruction to that time.  If there are not,
570    // keep looking back to see where's the first time there's a
571    // free slot.
572    while ((*iewQueue)[wbCycle].insts[wbNumInst]) {
573        ++wbNumInst;
574        if (wbNumInst == wbWidth) {
575            ++wbCycle;
576            wbNumInst = 0;
577        }
578
579        assert((wbCycle * wbWidth + wbNumInst) < wbMax);
580    }
581
582    // Add finished instruction to queue to commit.
583    (*iewQueue)[wbCycle].insts[wbNumInst] = inst;
584    (*iewQueue)[wbCycle].size++;
585}
586
587template <class Impl>
588unsigned
589DefaultIEW<Impl>::validInstsFromRename()
590{
591    unsigned inst_count = 0;
592
593    for (int i=0; i<fromRename->size; i++) {
594        if (!fromRename->insts[i]->isSquashed())
595            inst_count++;
596    }
597
598    return inst_count;
599}
600
601template<class Impl>
602void
603DefaultIEW<Impl>::skidInsert(unsigned tid)
604{
605    DynInstPtr inst = NULL;
606
607    while (!insts[tid].empty()) {
608        inst = insts[tid].front();
609
610        insts[tid].pop();
611
612        DPRINTF(Decode,"[tid:%i]: Inserting [sn:%lli] PC:%#x into "
613                "dispatch skidBuffer %i\n",tid, inst->seqNum,
614                inst->readPC(),tid);
615
616        skidBuffer[tid].push(inst);
617    }
618
619    assert(skidBuffer[tid].size() <= skidBufferMax &&
620           "Skidbuffer Exceeded Max Size");
621}
622
623template<class Impl>
624int
625DefaultIEW<Impl>::skidCount()
626{
627    int max=0;
628
629    list<unsigned>::iterator threads = (*activeThreads).begin();
630
631    while (threads != (*activeThreads).end()) {
632        unsigned thread_count = skidBuffer[*threads++].size();
633        if (max < thread_count)
634            max = thread_count;
635    }
636
637    return max;
638}
639
640template<class Impl>
641bool
642DefaultIEW<Impl>::skidsEmpty()
643{
644    list<unsigned>::iterator threads = (*activeThreads).begin();
645
646    while (threads != (*activeThreads).end()) {
647        if (!skidBuffer[*threads++].empty())
648            return false;
649    }
650
651    return true;
652}
653
654template <class Impl>
655void
656DefaultIEW<Impl>::updateStatus()
657{
658    bool any_unblocking = false;
659
660    list<unsigned>::iterator threads = (*activeThreads).begin();
661
662    threads = (*activeThreads).begin();
663
664    while (threads != (*activeThreads).end()) {
665        unsigned tid = *threads++;
666
667        if (dispatchStatus[tid] == Unblocking) {
668            any_unblocking = true;
669            break;
670        }
671    }
672
673    // If there are no ready instructions waiting to be scheduled by the IQ,
674    // and there's no stores waiting to write back, and dispatch is not
675    // unblocking, then there is no internal activity for the IEW stage.
676    if (_status == Active && !instQueue.hasReadyInsts() &&
677        !ldstQueue.willWB() && !any_unblocking) {
678        DPRINTF(IEW, "IEW switching to idle\n");
679
680        deactivateStage();
681
682        _status = Inactive;
683    } else if (_status == Inactive && (instQueue.hasReadyInsts() ||
684                                       ldstQueue.willWB() ||
685                                       any_unblocking)) {
686        // Otherwise there is internal activity.  Set to active.
687        DPRINTF(IEW, "IEW switching to active\n");
688
689        activateStage();
690
691        _status = Active;
692    }
693}
694
695template <class Impl>
696void
697DefaultIEW<Impl>::resetEntries()
698{
699    instQueue.resetEntries();
700    ldstQueue.resetEntries();
701}
702
703template <class Impl>
704void
705DefaultIEW<Impl>::readStallSignals(unsigned tid)
706{
707    if (fromCommit->commitBlock[tid]) {
708        stalls[tid].commit = true;
709    }
710
711    if (fromCommit->commitUnblock[tid]) {
712        assert(stalls[tid].commit);
713        stalls[tid].commit = false;
714    }
715}
716
717template <class Impl>
718bool
719DefaultIEW<Impl>::checkStall(unsigned tid)
720{
721    bool ret_val(false);
722
723    if (stalls[tid].commit) {
724        DPRINTF(IEW,"[tid:%i]: Stall from Commit stage detected.\n",tid);
725        ret_val = true;
726    } else if (instQueue.isFull(tid)) {
727        DPRINTF(IEW,"[tid:%i]: Stall: IQ  is full.\n",tid);
728        ret_val = true;
729    } else if (ldstQueue.isFull(tid)) {
730        DPRINTF(IEW,"[tid:%i]: Stall: LSQ is full\n",tid);
731
732        if (ldstQueue.numLoads(tid) > 0 ) {
733
734            DPRINTF(IEW,"[tid:%i]: LSQ oldest load: [sn:%i] \n",
735                    tid,ldstQueue.getLoadHeadSeqNum(tid));
736        }
737
738        if (ldstQueue.numStores(tid) > 0) {
739
740            DPRINTF(IEW,"[tid:%i]: LSQ oldest store: [sn:%i] \n",
741                    tid,ldstQueue.getStoreHeadSeqNum(tid));
742        }
743
744        ret_val = true;
745    } else if (ldstQueue.isStalled(tid)) {
746        DPRINTF(IEW,"[tid:%i]: Stall: LSQ stall detected.\n",tid);
747        ret_val = true;
748    }
749
750    return ret_val;
751}
752
753template <class Impl>
754void
755DefaultIEW<Impl>::checkSignalsAndUpdate(unsigned tid)
756{
757    // Check if there's a squash signal, squash if there is
758    // Check stall signals, block if there is.
759    // If status was Blocked
760    //     if so then go to unblocking
761    // If status was Squashing
762    //     check if squashing is not high.  Switch to running this cycle.
763
764    readStallSignals(tid);
765
766    if (fromCommit->commitInfo[tid].squash) {
767        squash(tid);
768
769        if (dispatchStatus[tid] == Blocked ||
770            dispatchStatus[tid] == Unblocking) {
771            toRename->iewUnblock[tid] = true;
772            wroteToTimeBuffer = true;
773        }
774
775        dispatchStatus[tid] = Squashing;
776
777        fetchRedirect[tid] = false;
778        return;
779    }
780
781    if (fromCommit->commitInfo[tid].robSquashing) {
782        DPRINTF(IEW, "[tid:%i]: ROB is still squashing.\n", tid);
783
784        dispatchStatus[tid] = Squashing;
785
786        emptyRenameInsts(tid);
787        wroteToTimeBuffer = true;
788        return;
789    }
790
791    if (checkStall(tid)) {
792        block(tid);
793        dispatchStatus[tid] = Blocked;
794        return;
795    }
796
797    if (dispatchStatus[tid] == Blocked) {
798        // Status from previous cycle was blocked, but there are no more stall
799        // conditions.  Switch over to unblocking.
800        DPRINTF(IEW, "[tid:%i]: Done blocking, switching to unblocking.\n",
801                tid);
802
803        dispatchStatus[tid] = Unblocking;
804
805        unblock(tid);
806
807        return;
808    }
809
810    if (dispatchStatus[tid] == Squashing) {
811        // Switch status to running if rename isn't being told to block or
812        // squash this cycle.
813        DPRINTF(IEW, "[tid:%i]: Done squashing, switching to running.\n",
814                tid);
815
816        dispatchStatus[tid] = Running;
817
818        return;
819    }
820}
821
822template <class Impl>
823void
824DefaultIEW<Impl>::sortInsts()
825{
826    int insts_from_rename = fromRename->size;
827#ifdef DEBUG
828    for (int i = 0; i < numThreads; i++)
829        assert(insts[i].empty());
830#endif
831    for (int i = 0; i < insts_from_rename; ++i) {
832        insts[fromRename->insts[i]->threadNumber].push(fromRename->insts[i]);
833    }
834}
835
836template <class Impl>
837void
838DefaultIEW<Impl>::emptyRenameInsts(unsigned tid)
839{
840    while (!insts[tid].empty()) {
841        if (insts[tid].front()->isLoad() ||
842            insts[tid].front()->isStore() ) {
843            toRename->iewInfo[tid].dispatchedToLSQ++;
844        }
845
846        toRename->iewInfo[tid].dispatched++;
847
848        insts[tid].pop();
849    }
850}
851
852template <class Impl>
853void
854DefaultIEW<Impl>::wakeCPU()
855{
856    cpu->wakeCPU();
857}
858
859template <class Impl>
860void
861DefaultIEW<Impl>::activityThisCycle()
862{
863    DPRINTF(Activity, "Activity this cycle.\n");
864    cpu->activityThisCycle();
865}
866
867template <class Impl>
868inline void
869DefaultIEW<Impl>::activateStage()
870{
871    DPRINTF(Activity, "Activating stage.\n");
872    cpu->activateStage(O3CPU::IEWIdx);
873}
874
875template <class Impl>
876inline void
877DefaultIEW<Impl>::deactivateStage()
878{
879    DPRINTF(Activity, "Deactivating stage.\n");
880    cpu->deactivateStage(O3CPU::IEWIdx);
881}
882
883template<class Impl>
884void
885DefaultIEW<Impl>::dispatch(unsigned tid)
886{
887    // If status is Running or idle,
888    //     call dispatchInsts()
889    // If status is Unblocking,
890    //     buffer any instructions coming from rename
891    //     continue trying to empty skid buffer
892    //     check if stall conditions have passed
893
894    if (dispatchStatus[tid] == Blocked) {
895        ++iewBlockCycles;
896
897    } else if (dispatchStatus[tid] == Squashing) {
898        ++iewSquashCycles;
899    }
900
901    // Dispatch should try to dispatch as many instructions as its bandwidth
902    // will allow, as long as it is not currently blocked.
903    if (dispatchStatus[tid] == Running ||
904        dispatchStatus[tid] == Idle) {
905        DPRINTF(IEW, "[tid:%i] Not blocked, so attempting to run "
906                "dispatch.\n", tid);
907
908        dispatchInsts(tid);
909    } else if (dispatchStatus[tid] == Unblocking) {
910        // Make sure that the skid buffer has something in it if the
911        // status is unblocking.
912        assert(!skidsEmpty());
913
914        // If the status was unblocking, then instructions from the skid
915        // buffer were used.  Remove those instructions and handle
916        // the rest of unblocking.
917        dispatchInsts(tid);
918
919        ++iewUnblockCycles;
920
921        if (validInstsFromRename() && dispatchedAllInsts) {
922            // Add the current inputs to the skid buffer so they can be
923            // reprocessed when this stage unblocks.
924            skidInsert(tid);
925        }
926
927        unblock(tid);
928    }
929}
930
931template <class Impl>
932void
933DefaultIEW<Impl>::dispatchInsts(unsigned tid)
934{
935    dispatchedAllInsts = true;
936
937    // Obtain instructions from skid buffer if unblocking, or queue from rename
938    // otherwise.
939    std::queue<DynInstPtr> &insts_to_dispatch =
940        dispatchStatus[tid] == Unblocking ?
941        skidBuffer[tid] : insts[tid];
942
943    int insts_to_add = insts_to_dispatch.size();
944
945    DynInstPtr inst;
946    bool add_to_iq = false;
947    int dis_num_inst = 0;
948
949    // Loop through the instructions, putting them in the instruction
950    // queue.
951    for ( ; dis_num_inst < insts_to_add &&
952              dis_num_inst < dispatchWidth;
953          ++dis_num_inst)
954    {
955        inst = insts_to_dispatch.front();
956
957        if (dispatchStatus[tid] == Unblocking) {
958            DPRINTF(IEW, "[tid:%i]: Issue: Examining instruction from skid "
959                    "buffer\n", tid);
960        }
961
962        // Make sure there's a valid instruction there.
963        assert(inst);
964
965        DPRINTF(IEW, "[tid:%i]: Issue: Adding PC %#x [sn:%lli] [tid:%i] to "
966                "IQ.\n",
967                tid, inst->readPC(), inst->seqNum, inst->threadNumber);
968
969        // Be sure to mark these instructions as ready so that the
970        // commit stage can go ahead and execute them, and mark
971        // them as issued so the IQ doesn't reprocess them.
972
973        // Check for squashed instructions.
974        if (inst->isSquashed()) {
975            DPRINTF(IEW, "[tid:%i]: Issue: Squashed instruction encountered, "
976                    "not adding to IQ.\n", tid);
977
978            ++iewDispSquashedInsts;
979
980            insts_to_dispatch.pop();
981
982            //Tell Rename That An Instruction has been processed
983            if (inst->isLoad() || inst->isStore()) {
984                toRename->iewInfo[tid].dispatchedToLSQ++;
985            }
986            toRename->iewInfo[tid].dispatched++;
987
988            continue;
989        }
990
991        // Check for full conditions.
992        if (instQueue.isFull(tid)) {
993            DPRINTF(IEW, "[tid:%i]: Issue: IQ has become full.\n", tid);
994
995            // Call function to start blocking.
996            block(tid);
997
998            // Set unblock to false. Special case where we are using
999            // skidbuffer (unblocking) instructions but then we still
1000            // get full in the IQ.
1001            toRename->iewUnblock[tid] = false;
1002
1003            dispatchedAllInsts = false;
1004
1005            ++iewIQFullEvents;
1006            break;
1007        } else if (ldstQueue.isFull(tid)) {
1008            DPRINTF(IEW, "[tid:%i]: Issue: LSQ has become full.\n",tid);
1009
1010            // Call function to start blocking.
1011            block(tid);
1012
1013            // Set unblock to false. Special case where we are using
1014            // skidbuffer (unblocking) instructions but then we still
1015            // get full in the IQ.
1016            toRename->iewUnblock[tid] = false;
1017
1018            dispatchedAllInsts = false;
1019
1020            ++iewLSQFullEvents;
1021            break;
1022        }
1023
1024        // Otherwise issue the instruction just fine.
1025        if (inst->isLoad()) {
1026            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1027                    "encountered, adding to LSQ.\n", tid);
1028
1029            // Reserve a spot in the load store queue for this
1030            // memory access.
1031            ldstQueue.insertLoad(inst);
1032
1033            ++iewDispLoadInsts;
1034
1035            add_to_iq = true;
1036
1037            toRename->iewInfo[tid].dispatchedToLSQ++;
1038        } else if (inst->isStore()) {
1039            DPRINTF(IEW, "[tid:%i]: Issue: Memory instruction "
1040                    "encountered, adding to LSQ.\n", tid);
1041
1042            ldstQueue.insertStore(inst);
1043
1044            ++iewDispStoreInsts;
1045
1046            if (inst->isStoreConditional()) {
1047                // Store conditionals need to be set as "canCommit()"
1048                // so that commit can process them when they reach the
1049                // head of commit.
1050                // @todo: This is somewhat specific to Alpha.
1051                inst->setCanCommit();
1052                instQueue.insertNonSpec(inst);
1053                add_to_iq = false;
1054
1055                ++iewDispNonSpecInsts;
1056            } else {
1057                add_to_iq = true;
1058            }
1059
1060            toRename->iewInfo[tid].dispatchedToLSQ++;
1061#if FULL_SYSTEM
1062        } else if (inst->isMemBarrier() || inst->isWriteBarrier()) {
1063            // Same as non-speculative stores.
1064            inst->setCanCommit();
1065            instQueue.insertBarrier(inst);
1066            add_to_iq = false;
1067#endif
1068        } else if (inst->isNonSpeculative()) {
1069            DPRINTF(IEW, "[tid:%i]: Issue: Nonspeculative instruction "
1070                    "encountered, skipping.\n", tid);
1071
1072            // Same as non-speculative stores.
1073            inst->setCanCommit();
1074
1075            // Specifically insert it as nonspeculative.
1076            instQueue.insertNonSpec(inst);
1077
1078            ++iewDispNonSpecInsts;
1079
1080            add_to_iq = false;
1081        } else if (inst->isNop()) {
1082            DPRINTF(IEW, "[tid:%i]: Issue: Nop instruction encountered, "
1083                    "skipping.\n", tid);
1084
1085            inst->setIssued();
1086            inst->setExecuted();
1087            inst->setCanCommit();
1088
1089            instQueue.recordProducer(inst);
1090
1091            iewExecutedNop[tid]++;
1092
1093            add_to_iq = false;
1094        } else if (inst->isExecuted()) {
1095            assert(0 && "Instruction shouldn't be executed.\n");
1096            DPRINTF(IEW, "Issue: Executed branch encountered, "
1097                    "skipping.\n");
1098
1099            inst->setIssued();
1100            inst->setCanCommit();
1101
1102            instQueue.recordProducer(inst);
1103
1104            add_to_iq = false;
1105        } else {
1106            add_to_iq = true;
1107        }
1108
1109        // If the instruction queue is not full, then add the
1110        // instruction.
1111        if (add_to_iq) {
1112            instQueue.insert(inst);
1113        }
1114
1115        insts_to_dispatch.pop();
1116
1117        toRename->iewInfo[tid].dispatched++;
1118
1119        ++iewDispatchedInsts;
1120    }
1121
1122    if (!insts_to_dispatch.empty()) {
1123        DPRINTF(IEW,"[tid:%i]: Issue: Bandwidth Full. Blocking.\n");
1124        block(tid);
1125        toRename->iewUnblock[tid] = false;
1126    }
1127
1128    if (dispatchStatus[tid] == Idle && dis_num_inst) {
1129        dispatchStatus[tid] = Running;
1130
1131        updatedQueues = true;
1132    }
1133
1134    dis_num_inst = 0;
1135}
1136
1137template <class Impl>
1138void
1139DefaultIEW<Impl>::printAvailableInsts()
1140{
1141    int inst = 0;
1142
1143    cout << "Available Instructions: ";
1144
1145    while (fromIssue->insts[inst]) {
1146
1147        if (inst%3==0) cout << "\n\t";
1148
1149        cout << "PC: " << fromIssue->insts[inst]->readPC()
1150             << " TN: " << fromIssue->insts[inst]->threadNumber
1151             << " SN: " << fromIssue->insts[inst]->seqNum << " | ";
1152
1153        inst++;
1154
1155    }
1156
1157    cout << "\n";
1158}
1159
1160template <class Impl>
1161void
1162DefaultIEW<Impl>::executeInsts()
1163{
1164    wbNumInst = 0;
1165    wbCycle = 0;
1166
1167    list<unsigned>::iterator threads = (*activeThreads).begin();
1168
1169    while (threads != (*activeThreads).end()) {
1170        unsigned tid = *threads++;
1171        fetchRedirect[tid] = false;
1172    }
1173
1174    // Uncomment this if you want to see all available instructions.
1175//    printAvailableInsts();
1176
1177    // Execute/writeback any instructions that are available.
1178    int insts_to_execute = fromIssue->size;
1179    int inst_num = 0;
1180    for (; inst_num < insts_to_execute;
1181          ++inst_num) {
1182
1183        DPRINTF(IEW, "Execute: Executing instructions from IQ.\n");
1184
1185        DynInstPtr inst = instQueue.getInstToExecute();
1186
1187        DPRINTF(IEW, "Execute: Processing PC %#x, [tid:%i] [sn:%i].\n",
1188                inst->readPC(), inst->threadNumber,inst->seqNum);
1189
1190        // Check if the instruction is squashed; if so then skip it
1191        if (inst->isSquashed()) {
1192            DPRINTF(IEW, "Execute: Instruction was squashed.\n");
1193
1194            // Consider this instruction executed so that commit can go
1195            // ahead and retire the instruction.
1196            inst->setExecuted();
1197
1198            // Not sure if I should set this here or just let commit try to
1199            // commit any squashed instructions.  I like the latter a bit more.
1200            inst->setCanCommit();
1201
1202            ++iewExecSquashedInsts;
1203
1204            decrWb(inst->seqNum);
1205            continue;
1206        }
1207
1208        Fault fault = NoFault;
1209
1210        // Execute instruction.
1211        // Note that if the instruction faults, it will be handled
1212        // at the commit stage.
1213        if (inst->isMemRef() &&
1214            (!inst->isDataPrefetch() && !inst->isInstPrefetch())) {
1215            DPRINTF(IEW, "Execute: Calculating address for memory "
1216                    "reference.\n");
1217
1218            // Tell the LDSTQ to execute this instruction (if it is a load).
1219            if (inst->isLoad()) {
1220                // Loads will mark themselves as executed, and their writeback
1221                // event adds the instruction to the queue to commit
1222                fault = ldstQueue.executeLoad(inst);
1223            } else if (inst->isStore()) {
1224                ldstQueue.executeStore(inst);
1225
1226                // If the store had a fault then it may not have a mem req
1227                if (inst->req && !(inst->req->getFlags() & LOCKED)) {
1228                    inst->setExecuted();
1229
1230                    instToCommit(inst);
1231                }
1232
1233                // Store conditionals will mark themselves as
1234                // executed, and their writeback event will add the
1235                // instruction to the queue to commit.
1236            } else {
1237                panic("Unexpected memory type!\n");
1238            }
1239
1240        } else {
1241            inst->execute();
1242
1243            inst->setExecuted();
1244
1245            instToCommit(inst);
1246        }
1247
1248        updateExeInstStats(inst);
1249
1250        // Check if branch prediction was correct, if not then we need
1251        // to tell commit to squash in flight instructions.  Only
1252        // handle this if there hasn't already been something that
1253        // redirects fetch in this group of instructions.
1254
1255        // This probably needs to prioritize the redirects if a different
1256        // scheduler is used.  Currently the scheduler schedules the oldest
1257        // instruction first, so the branch resolution order will be correct.
1258        unsigned tid = inst->threadNumber;
1259
1260        if (!fetchRedirect[tid]) {
1261
1262            if (inst->mispredicted()) {
1263                fetchRedirect[tid] = true;
1264
1265                DPRINTF(IEW, "Execute: Branch mispredict detected.\n");
1266                DPRINTF(IEW, "Execute: Redirecting fetch to PC: %#x.\n",
1267                        inst->nextPC);
1268
1269                // If incorrect, then signal the ROB that it must be squashed.
1270                squashDueToBranch(inst, tid);
1271
1272                if (inst->predTaken()) {
1273                    predictedTakenIncorrect++;
1274                } else {
1275                    predictedNotTakenIncorrect++;
1276                }
1277            } else if (ldstQueue.violation(tid)) {
1278                fetchRedirect[tid] = true;
1279
1280                // If there was an ordering violation, then get the
1281                // DynInst that caused the violation.  Note that this
1282                // clears the violation signal.
1283                DynInstPtr violator;
1284                violator = ldstQueue.getMemDepViolator(tid);
1285
1286                DPRINTF(IEW, "LDSTQ detected a violation.  Violator PC: "
1287                        "%#x, inst PC: %#x.  Addr is: %#x.\n",
1288                        violator->readPC(), inst->readPC(), inst->physEffAddr);
1289
1290                // Tell the instruction queue that a violation has occured.
1291                instQueue.violation(inst, violator);
1292
1293                // Squash.
1294                squashDueToMemOrder(inst,tid);
1295
1296                ++memOrderViolationEvents;
1297            } else if (ldstQueue.loadBlocked(tid) &&
1298                       !ldstQueue.isLoadBlockedHandled(tid)) {
1299                fetchRedirect[tid] = true;
1300
1301                DPRINTF(IEW, "Load operation couldn't execute because the "
1302                        "memory system is blocked.  PC: %#x [sn:%lli]\n",
1303                        inst->readPC(), inst->seqNum);
1304
1305                squashDueToMemBlocked(inst, tid);
1306            }
1307        }
1308    }
1309
1310    // Update and record activity if we processed any instructions.
1311    if (inst_num) {
1312        if (exeStatus == Idle) {
1313            exeStatus = Running;
1314        }
1315
1316        updatedQueues = true;
1317
1318        cpu->activityThisCycle();
1319    }
1320
1321    // Need to reset this in case a writeback event needs to write into the
1322    // iew queue.  That way the writeback event will write into the correct
1323    // spot in the queue.
1324    wbNumInst = 0;
1325}
1326
1327template <class Impl>
1328void
1329DefaultIEW<Impl>::writebackInsts()
1330{
1331    // Loop through the head of the time buffer and wake any
1332    // dependents.  These instructions are about to write back.  Also
1333    // mark scoreboard that this instruction is finally complete.
1334    // Either have IEW have direct access to scoreboard, or have this
1335    // as part of backwards communication.
1336    for (int inst_num = 0; inst_num < issueWidth &&
1337             toCommit->insts[inst_num]; inst_num++) {
1338        DynInstPtr inst = toCommit->insts[inst_num];
1339        int tid = inst->threadNumber;
1340
1341        DPRINTF(IEW, "Sending instructions to commit, [sn:%lli] PC %#x.\n",
1342                inst->seqNum, inst->readPC());
1343
1344        iewInstsToCommit[tid]++;
1345
1346        // Some instructions will be sent to commit without having
1347        // executed because they need commit to handle them.
1348        // E.g. Uncached loads have not actually executed when they
1349        // are first sent to commit.  Instead commit must tell the LSQ
1350        // when it's ready to execute the uncached load.
1351        if (!inst->isSquashed() && inst->isExecuted()) {
1352            int dependents = instQueue.wakeDependents(inst);
1353
1354            for (int i = 0; i < inst->numDestRegs(); i++) {
1355                //mark as Ready
1356                DPRINTF(IEW,"Setting Destination Register %i\n",
1357                        inst->renamedDestRegIdx(i));
1358                scoreboard->setReg(inst->renamedDestRegIdx(i));
1359            }
1360
1361            if (dependents) {
1362                producerInst[tid]++;
1363                consumerInst[tid]+= dependents;
1364            }
1365            writebackCount[tid]++;
1366        }
1367
1368        decrWb(inst->seqNum);
1369    }
1370}
1371
1372template<class Impl>
1373void
1374DefaultIEW<Impl>::tick()
1375{
1376    wbNumInst = 0;
1377    wbCycle = 0;
1378
1379    wroteToTimeBuffer = false;
1380    updatedQueues = false;
1381
1382    sortInsts();
1383
1384    // Free function units marked as being freed this cycle.
1385    fuPool->processFreeUnits();
1386
1387    list<unsigned>::iterator threads = (*activeThreads).begin();
1388
1389    // Check stall and squash signals, dispatch any instructions.
1390    while (threads != (*activeThreads).end()) {
1391           unsigned tid = *threads++;
1392
1393        DPRINTF(IEW,"Issue: Processing [tid:%i]\n",tid);
1394
1395        checkSignalsAndUpdate(tid);
1396        dispatch(tid);
1397    }
1398
1399    if (exeStatus != Squashing) {
1400        executeInsts();
1401
1402        writebackInsts();
1403
1404        // Have the instruction queue try to schedule any ready instructions.
1405        // (In actuality, this scheduling is for instructions that will
1406        // be executed next cycle.)
1407        instQueue.scheduleReadyInsts();
1408
1409        // Also should advance its own time buffers if the stage ran.
1410        // Not the best place for it, but this works (hopefully).
1411        issueToExecQueue.advance();
1412    }
1413
1414    bool broadcast_free_entries = false;
1415
1416    if (updatedQueues || exeStatus == Running || updateLSQNextCycle) {
1417        exeStatus = Idle;
1418        updateLSQNextCycle = false;
1419
1420        broadcast_free_entries = true;
1421    }
1422
1423    // Writeback any stores using any leftover bandwidth.
1424    ldstQueue.writebackStores();
1425
1426    // Check the committed load/store signals to see if there's a load
1427    // or store to commit.  Also check if it's being told to execute a
1428    // nonspeculative instruction.
1429    // This is pretty inefficient...
1430
1431    threads = (*activeThreads).begin();
1432    while (threads != (*activeThreads).end()) {
1433        unsigned tid = (*threads++);
1434
1435        DPRINTF(IEW,"Processing [tid:%i]\n",tid);
1436
1437        // Update structures based on instructions committed.
1438        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
1439            !fromCommit->commitInfo[tid].squash &&
1440            !fromCommit->commitInfo[tid].robSquashing) {
1441
1442            ldstQueue.commitStores(fromCommit->commitInfo[tid].doneSeqNum,tid);
1443
1444            ldstQueue.commitLoads(fromCommit->commitInfo[tid].doneSeqNum,tid);
1445
1446            updateLSQNextCycle = true;
1447            instQueue.commit(fromCommit->commitInfo[tid].doneSeqNum,tid);
1448        }
1449
1450        if (fromCommit->commitInfo[tid].nonSpecSeqNum != 0) {
1451
1452            //DPRINTF(IEW,"NonspecInst from thread %i",tid);
1453            if (fromCommit->commitInfo[tid].uncached) {
1454                instQueue.replayMemInst(fromCommit->commitInfo[tid].uncachedLoad);
1455            } else {
1456                instQueue.scheduleNonSpec(
1457                    fromCommit->commitInfo[tid].nonSpecSeqNum);
1458            }
1459        }
1460
1461        if (broadcast_free_entries) {
1462            toFetch->iewInfo[tid].iqCount =
1463                instQueue.getCount(tid);
1464            toFetch->iewInfo[tid].ldstqCount =
1465                ldstQueue.getCount(tid);
1466
1467            toRename->iewInfo[tid].usedIQ = true;
1468            toRename->iewInfo[tid].freeIQEntries =
1469                instQueue.numFreeEntries();
1470            toRename->iewInfo[tid].usedLSQ = true;
1471            toRename->iewInfo[tid].freeLSQEntries =
1472                ldstQueue.numFreeEntries(tid);
1473
1474            wroteToTimeBuffer = true;
1475        }
1476
1477        DPRINTF(IEW, "[tid:%i], Dispatch dispatched %i instructions.\n",
1478                tid, toRename->iewInfo[tid].dispatched);
1479    }
1480
1481    DPRINTF(IEW, "IQ has %i free entries (Can schedule: %i).  "
1482            "LSQ has %i free entries.\n",
1483            instQueue.numFreeEntries(), instQueue.hasReadyInsts(),
1484            ldstQueue.numFreeEntries());
1485
1486    updateStatus();
1487
1488    if (wroteToTimeBuffer) {
1489        DPRINTF(Activity, "Activity this cycle.\n");
1490        cpu->activityThisCycle();
1491    }
1492}
1493
1494template <class Impl>
1495void
1496DefaultIEW<Impl>::updateExeInstStats(DynInstPtr &inst)
1497{
1498    int thread_number = inst->threadNumber;
1499
1500    //
1501    //  Pick off the software prefetches
1502    //
1503#ifdef TARGET_ALPHA
1504    if (inst->isDataPrefetch())
1505        iewExecutedSwp[thread_number]++;
1506    else
1507        iewIewExecutedcutedInsts++;
1508#else
1509    iewExecutedInsts++;
1510#endif
1511
1512    //
1513    //  Control operations
1514    //
1515    if (inst->isControl())
1516        iewExecutedBranches[thread_number]++;
1517
1518    //
1519    //  Memory operations
1520    //
1521    if (inst->isMemRef()) {
1522        iewExecutedRefs[thread_number]++;
1523
1524        if (inst->isLoad()) {
1525            iewExecLoadInsts[thread_number]++;
1526        }
1527    }
1528}
1529