fetch_impl.hh revision 6036:f0841ee466a5
12929Sktlim@umich.edu/*
22929Sktlim@umich.edu * Copyright (c) 2004-2006 The Regents of The University of Michigan
32932Sktlim@umich.edu * All rights reserved.
42929Sktlim@umich.edu *
52929Sktlim@umich.edu * Redistribution and use in source and binary forms, with or without
62929Sktlim@umich.edu * modification, are permitted provided that the following conditions are
72929Sktlim@umich.edu * met: redistributions of source code must retain the above copyright
82929Sktlim@umich.edu * notice, this list of conditions and the following disclaimer;
92929Sktlim@umich.edu * redistributions in binary form must reproduce the above copyright
102929Sktlim@umich.edu * notice, this list of conditions and the following disclaimer in the
112929Sktlim@umich.edu * documentation and/or other materials provided with the distribution;
122929Sktlim@umich.edu * neither the name of the copyright holders nor the names of its
132929Sktlim@umich.edu * contributors may be used to endorse or promote products derived from
142929Sktlim@umich.edu * this software without specific prior written permission.
152929Sktlim@umich.edu *
162929Sktlim@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
172929Sktlim@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
182929Sktlim@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
192929Sktlim@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
202929Sktlim@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
212929Sktlim@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
222929Sktlim@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
232929Sktlim@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
242929Sktlim@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
252929Sktlim@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
262929Sktlim@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272929Sktlim@umich.edu *
282932Sktlim@umich.edu * Authors: Kevin Lim
292932Sktlim@umich.edu *          Korey Sewell
302932Sktlim@umich.edu */
312929Sktlim@umich.edu
326007Ssteve.reinhardt@amd.com#include <algorithm>
337735SAli.Saidi@ARM.com#include <cstring>
342929Sktlim@umich.edu
352929Sktlim@umich.edu#include "config/use_checker.hh"
362929Sktlim@umich.edu
372929Sktlim@umich.edu#include "arch/isa_traits.hh"
382929Sktlim@umich.edu#include "arch/utility.hh"
392929Sktlim@umich.edu#include "cpu/checker/cpu.hh"
402929Sktlim@umich.edu#include "cpu/exetrace.hh"
412929Sktlim@umich.edu#include "cpu/o3/fetch.hh"
422929Sktlim@umich.edu#include "mem/packet.hh"
432929Sktlim@umich.edu#include "mem/request.hh"
442929Sktlim@umich.edu#include "sim/byteswap.hh"
452929Sktlim@umich.edu#include "sim/host.hh"
462929Sktlim@umich.edu#include "sim/core.hh"
476007Ssteve.reinhardt@amd.com
486007Ssteve.reinhardt@amd.com#if FULL_SYSTEM
496007Ssteve.reinhardt@amd.com#include "arch/tlb.hh"
506007Ssteve.reinhardt@amd.com#include "arch/vtophys.hh"
516007Ssteve.reinhardt@amd.com#include "sim/system.hh"
526007Ssteve.reinhardt@amd.com#endif // FULL_SYSTEM
536007Ssteve.reinhardt@amd.com
546007Ssteve.reinhardt@amd.com#include "params/DerivO3CPU.hh"
556007Ssteve.reinhardt@amd.com
566007Ssteve.reinhardt@amd.comtemplate<class Impl>
576007Ssteve.reinhardt@amd.comvoid
586007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::setPeer(Port *port)
596007Ssteve.reinhardt@amd.com{
606007Ssteve.reinhardt@amd.com    Port::setPeer(port);
616007Ssteve.reinhardt@amd.com
626007Ssteve.reinhardt@amd.com    fetch->setIcache();
636007Ssteve.reinhardt@amd.com}
646007Ssteve.reinhardt@amd.com
656007Ssteve.reinhardt@amd.comtemplate<class Impl>
666007Ssteve.reinhardt@amd.comTick
676007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
686007Ssteve.reinhardt@amd.com{
696007Ssteve.reinhardt@amd.com    panic("DefaultFetch doesn't expect recvAtomic callback!");
706007Ssteve.reinhardt@amd.com    return curTick;
716007Ssteve.reinhardt@amd.com}
726007Ssteve.reinhardt@amd.com
736007Ssteve.reinhardt@amd.comtemplate<class Impl>
746007Ssteve.reinhardt@amd.comvoid
756007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
762929Sktlim@umich.edu{
772929Sktlim@umich.edu    DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
782929Sktlim@umich.edu            "functional call.");
796007Ssteve.reinhardt@amd.com}
806007Ssteve.reinhardt@amd.com
816007Ssteve.reinhardt@amd.comtemplate<class Impl>
826007Ssteve.reinhardt@amd.comvoid
836007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
846007Ssteve.reinhardt@amd.com{
852929Sktlim@umich.edu    if (status == RangeChange) {
862929Sktlim@umich.edu        if (!snoopRangeSent) {
872929Sktlim@umich.edu            snoopRangeSent = true;
882929Sktlim@umich.edu            sendStatusChange(Port::RangeChange);
892929Sktlim@umich.edu        }
906011Ssteve.reinhardt@amd.com        return;
916007Ssteve.reinhardt@amd.com    }
926007Ssteve.reinhardt@amd.com
936007Ssteve.reinhardt@amd.com    panic("DefaultFetch doesn't expect recvStatusChange callback!");
946007Ssteve.reinhardt@amd.com}
956007Ssteve.reinhardt@amd.com
966007Ssteve.reinhardt@amd.comtemplate<class Impl>
976007Ssteve.reinhardt@amd.combool
986007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
996007Ssteve.reinhardt@amd.com{
1006007Ssteve.reinhardt@amd.com    DPRINTF(Fetch, "Received timing\n");
1016007Ssteve.reinhardt@amd.com    if (pkt->isResponse()) {
1026007Ssteve.reinhardt@amd.com        fetch->processCacheCompletion(pkt);
1036007Ssteve.reinhardt@amd.com    }
1046007Ssteve.reinhardt@amd.com    //else Snooped a coherence request, just return
1057735SAli.Saidi@ARM.com    return true;
1066011Ssteve.reinhardt@amd.com}
1076007Ssteve.reinhardt@amd.com
1086007Ssteve.reinhardt@amd.comtemplate<class Impl>
1096007Ssteve.reinhardt@amd.comvoid
1106007Ssteve.reinhardt@amd.comDefaultFetch<Impl>::IcachePort::recvRetry()
1117735SAli.Saidi@ARM.com{
1127735SAli.Saidi@ARM.com    fetch->recvRetry();
1137735SAli.Saidi@ARM.com}
1147735SAli.Saidi@ARM.com
1157735SAli.Saidi@ARM.comtemplate<class Impl>
1167735SAli.Saidi@ARM.comDefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
1177735SAli.Saidi@ARM.com    : cpu(_cpu),
1187735SAli.Saidi@ARM.com      branchPred(params),
1197735SAli.Saidi@ARM.com      predecoder(NULL),
1207735SAli.Saidi@ARM.com      decodeToFetchDelay(params->decodeToFetchDelay),
1217735SAli.Saidi@ARM.com      renameToFetchDelay(params->renameToFetchDelay),
1227735SAli.Saidi@ARM.com      iewToFetchDelay(params->iewToFetchDelay),
1237735SAli.Saidi@ARM.com      commitToFetchDelay(params->commitToFetchDelay),
1247735SAli.Saidi@ARM.com      fetchWidth(params->fetchWidth),
1256007Ssteve.reinhardt@amd.com      cacheBlocked(false),
1268599Ssteve.reinhardt@amd.com      retryPkt(NULL),
1278599Ssteve.reinhardt@amd.com      retryTid(-1),
1288599Ssteve.reinhardt@amd.com      numThreads(params->numThreads),
1296007Ssteve.reinhardt@amd.com      numFetchingThreads(params->smtNumFetchingThreads),
1306011Ssteve.reinhardt@amd.com      interruptPending(false),
1316007Ssteve.reinhardt@amd.com      drainPending(false),
1326007Ssteve.reinhardt@amd.com      switchedOut(false)
1336007Ssteve.reinhardt@amd.com{
1346007Ssteve.reinhardt@amd.com    if (numThreads > Impl::MaxThreads)
1356007Ssteve.reinhardt@amd.com        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
1366007Ssteve.reinhardt@amd.com              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
1376011Ssteve.reinhardt@amd.com              numThreads, static_cast<int>(Impl::MaxThreads));
1386007Ssteve.reinhardt@amd.com
1396007Ssteve.reinhardt@amd.com    // Set fetch stage's status to inactive.
1406007Ssteve.reinhardt@amd.com    _status = Inactive;
1416007Ssteve.reinhardt@amd.com
1426007Ssteve.reinhardt@amd.com    std::string policy = params->smtFetchPolicy;
1436008Ssteve.reinhardt@amd.com
1446007Ssteve.reinhardt@amd.com    // Convert string to lowercase
1456008Ssteve.reinhardt@amd.com    std::transform(policy.begin(), policy.end(), policy.begin(),
1466008Ssteve.reinhardt@amd.com                   (int(*)(int)) tolower);
1476008Ssteve.reinhardt@amd.com
1486008Ssteve.reinhardt@amd.com    // Figure out fetch policy
1496008Ssteve.reinhardt@amd.com    if (policy == "singlethread") {
1506008Ssteve.reinhardt@amd.com        fetchPolicy = SingleThread;
1516008Ssteve.reinhardt@amd.com        if (numThreads > 1)
1526007Ssteve.reinhardt@amd.com            panic("Invalid Fetch Policy for a SMT workload.");
1536007Ssteve.reinhardt@amd.com    } else if (policy == "roundrobin") {
1546007Ssteve.reinhardt@amd.com        fetchPolicy = RoundRobin;
1556007Ssteve.reinhardt@amd.com        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
1566007Ssteve.reinhardt@amd.com    } else if (policy == "branch") {
1572929Sktlim@umich.edu        fetchPolicy = Branch;
1582929Sktlim@umich.edu        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
1592929Sktlim@umich.edu    } else if (policy == "iqcount") {
1602929Sktlim@umich.edu        fetchPolicy = IQ;
1616007Ssteve.reinhardt@amd.com        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
1626007Ssteve.reinhardt@amd.com    } else if (policy == "lsqcount") {
1632929Sktlim@umich.edu        fetchPolicy = LSQ;
1642929Sktlim@umich.edu        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
1652929Sktlim@umich.edu    } else {
1662929Sktlim@umich.edu        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
1676007Ssteve.reinhardt@amd.com              " RoundRobin,LSQcount,IQcount}\n");
1686007Ssteve.reinhardt@amd.com    }
1692929Sktlim@umich.edu
1702929Sktlim@umich.edu    // Get the size of an instruction.
1716007Ssteve.reinhardt@amd.com    instSize = sizeof(TheISA::MachInst);
1722929Sktlim@umich.edu
1732929Sktlim@umich.edu    // Name is finally available, so create the port.
1742929Sktlim@umich.edu    icachePort = new IcachePort(this);
1752929Sktlim@umich.edu
1762929Sktlim@umich.edu    icachePort->snoopRangeSent = false;
1772929Sktlim@umich.edu
1782929Sktlim@umich.edu#if USE_CHECKER
1794937Sstever@gmail.com    if (cpu->checker) {
1804937Sstever@gmail.com        cpu->checker->setIcachePort(icachePort);
1814937Sstever@gmail.com    }
1824937Sstever@gmail.com#endif
1838120Sgblack@eecs.umich.edu}
1844937Sstever@gmail.com
1854937Sstever@gmail.comtemplate <class Impl>
1864937Sstever@gmail.comstd::string
1874937Sstever@gmail.comDefaultFetch<Impl>::name() const
1885773Snate@binkert.org{
1894937Sstever@gmail.com    return cpu->name() + ".fetch";
1904937Sstever@gmail.com}
1914937Sstever@gmail.com
1922929Sktlim@umich.edutemplate <class Impl>
1932929Sktlim@umich.eduvoid
1942929Sktlim@umich.eduDefaultFetch<Impl>::regStats()
1955773Snate@binkert.org{
1962929Sktlim@umich.edu    icacheStallCycles
1972929Sktlim@umich.edu        .name(name() + ".icacheStallCycles")
1982929Sktlim@umich.edu        .desc("Number of cycles fetch is stalled on an Icache miss")
1992929Sktlim@umich.edu        .prereq(icacheStallCycles);
2002929Sktlim@umich.edu
2012929Sktlim@umich.edu    fetchedInsts
2024937Sstever@gmail.com        .name(name() + ".Insts")
2034937Sstever@gmail.com        .desc("Number of instructions fetch has processed")
2044937Sstever@gmail.com        .prereq(fetchedInsts);
2054937Sstever@gmail.com
2064937Sstever@gmail.com    fetchedBranches
2074937Sstever@gmail.com        .name(name() + ".Branches")
2084937Sstever@gmail.com        .desc("Number of branches that fetch encountered")
2094937Sstever@gmail.com        .prereq(fetchedBranches);
2104937Sstever@gmail.com
2114937Sstever@gmail.com    predictedBranches
2124937Sstever@gmail.com        .name(name() + ".predictedBranches")
2134937Sstever@gmail.com        .desc("Number of branches that fetch has predicted taken")
2144937Sstever@gmail.com        .prereq(predictedBranches);
2154937Sstever@gmail.com
2164937Sstever@gmail.com    fetchCycles
2172929Sktlim@umich.edu        .name(name() + ".Cycles")
2182929Sktlim@umich.edu        .desc("Number of cycles fetch has run and was not squashing or"
2192929Sktlim@umich.edu              " blocked")
2202929Sktlim@umich.edu        .prereq(fetchCycles);
2212929Sktlim@umich.edu
2222929Sktlim@umich.edu    fetchSquashCycles
2232929Sktlim@umich.edu        .name(name() + ".SquashCycles")
2246011Ssteve.reinhardt@amd.com        .desc("Number of cycles fetch has spent squashing")
2252929Sktlim@umich.edu        .prereq(fetchSquashCycles);
2262929Sktlim@umich.edu
2272929Sktlim@umich.edu    fetchIdleCycles
2282929Sktlim@umich.edu        .name(name() + ".IdleCycles")
2292929Sktlim@umich.edu        .desc("Number of cycles fetch was idle")
2302929Sktlim@umich.edu        .prereq(fetchIdleCycles);
2312929Sktlim@umich.edu
2322929Sktlim@umich.edu    fetchBlockedCycles
2332997Sstever@eecs.umich.edu        .name(name() + ".BlockedCycles")
2342997Sstever@eecs.umich.edu        .desc("Number of cycles fetch has spent blocked")
2352929Sktlim@umich.edu        .prereq(fetchBlockedCycles);
2368802Sgblack@eecs.umich.edu
2372997Sstever@eecs.umich.edu    fetchedCacheLines
2382929Sktlim@umich.edu        .name(name() + ".CacheLines")
2392997Sstever@eecs.umich.edu        .desc("Number of cache lines fetched")
2402997Sstever@eecs.umich.edu        .prereq(fetchedCacheLines);
2418802Sgblack@eecs.umich.edu
2422929Sktlim@umich.edu    fetchMiscStallCycles
2432997Sstever@eecs.umich.edu        .name(name() + ".MiscStallCycles")
2442997Sstever@eecs.umich.edu        .desc("Number of cycles fetch has spent waiting on interrupts, or "
2452997Sstever@eecs.umich.edu              "bad addresses, or out of MSHRs")
2462997Sstever@eecs.umich.edu        .prereq(fetchMiscStallCycles);
2475773Snate@binkert.org
2485773Snate@binkert.org    fetchIcacheSquashes
2492997Sstever@eecs.umich.edu        .name(name() + ".IcacheSquashes")
2502997Sstever@eecs.umich.edu        .desc("Number of outstanding Icache misses that were squashed")
2516007Ssteve.reinhardt@amd.com        .prereq(fetchIcacheSquashes);
2526007Ssteve.reinhardt@amd.com
2532997Sstever@eecs.umich.edu    fetchNisnDist
2542929Sktlim@umich.edu        .init(/* base value */ 0,
2552997Sstever@eecs.umich.edu              /* last value */ fetchWidth,
2568120Sgblack@eecs.umich.edu              /* bucket size */ 1)
2572997Sstever@eecs.umich.edu        .name(name() + ".rateDist")
2582997Sstever@eecs.umich.edu        .desc("Number of instructions fetched each cycle (Total)")
2592997Sstever@eecs.umich.edu        .flags(Stats::pdf);
2602997Sstever@eecs.umich.edu
2612997Sstever@eecs.umich.edu    idleRate
2622929Sktlim@umich.edu        .name(name() + ".idleRate")
2632997Sstever@eecs.umich.edu        .desc("Percent of cycles fetch was idle")
2642929Sktlim@umich.edu        .prereq(idleRate);
2652929Sktlim@umich.edu    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
2663005Sstever@eecs.umich.edu
2673005Sstever@eecs.umich.edu    branchRate
2688802Sgblack@eecs.umich.edu        .name(name() + ".branchRate")
2698802Sgblack@eecs.umich.edu        .desc("Number of branch fetches per cycle")
2708802Sgblack@eecs.umich.edu        .flags(Stats::total);
2718802Sgblack@eecs.umich.edu    branchRate = fetchedBranches / cpu->numCycles;
2728802Sgblack@eecs.umich.edu
2738802Sgblack@eecs.umich.edu    fetchRate
2748802Sgblack@eecs.umich.edu        .name(name() + ".rate")
2758802Sgblack@eecs.umich.edu        .desc("Number of inst fetches per cycle")
2768802Sgblack@eecs.umich.edu        .flags(Stats::total);
2778802Sgblack@eecs.umich.edu    fetchRate = fetchedInsts / cpu->numCycles;
2788802Sgblack@eecs.umich.edu
2798802Sgblack@eecs.umich.edu    branchPred.regStats();
2808802Sgblack@eecs.umich.edu}
2818802Sgblack@eecs.umich.edu
2828802Sgblack@eecs.umich.edutemplate<class Impl>
2838802Sgblack@eecs.umich.eduvoid
2848802Sgblack@eecs.umich.eduDefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
2858802Sgblack@eecs.umich.edu{
2868802Sgblack@eecs.umich.edu    timeBuffer = time_buffer;
2878802Sgblack@eecs.umich.edu
2888802Sgblack@eecs.umich.edu    // Create wires to get information from proper places in time buffer.
2898802Sgblack@eecs.umich.edu    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
2903691Shsul@eecs.umich.edu    fromRename = timeBuffer->getWire(-renameToFetchDelay);
2918802Sgblack@eecs.umich.edu    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
2928802Sgblack@eecs.umich.edu    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
2938802Sgblack@eecs.umich.edu}
2943005Sstever@eecs.umich.edu
2958492Snilay@cs.wisc.edutemplate<class Impl>
2966928SBrad.Beckmann@amd.comvoid
2976928SBrad.Beckmann@amd.comDefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
2986928SBrad.Beckmann@amd.com{
2996928SBrad.Beckmann@amd.com    activeThreads = at_ptr;
3006166Ssteve.reinhardt@amd.com}
3012929Sktlim@umich.edu
3022929Sktlim@umich.edutemplate<class Impl>
3033005Sstever@eecs.umich.eduvoid
3048802Sgblack@eecs.umich.eduDefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
3052997Sstever@eecs.umich.edu{
3066293Ssteve.reinhardt@amd.com    fetchQueue = fq_ptr;
3076293Ssteve.reinhardt@amd.com
3082929Sktlim@umich.edu    // Create wire to write information to proper place in fetch queue.
309    toDecode = fetchQueue->getWire(0);
310}
311
312template<class Impl>
313void
314DefaultFetch<Impl>::initStage()
315{
316    // Setup PC and nextPC with initial state.
317    for (int tid = 0; tid < numThreads; tid++) {
318        PC[tid] = cpu->readPC(tid);
319        nextPC[tid] = cpu->readNextPC(tid);
320        microPC[tid] = cpu->readMicroPC(tid);
321    }
322
323    for (int tid=0; tid < numThreads; tid++) {
324
325        fetchStatus[tid] = Running;
326
327        priorityList.push_back(tid);
328
329        memReq[tid] = NULL;
330
331        stalls[tid].decode = false;
332        stalls[tid].rename = false;
333        stalls[tid].iew = false;
334        stalls[tid].commit = false;
335    }
336
337    // Schedule fetch to get the correct PC from the CPU
338    // scheduleFetchStartupEvent(1);
339
340    // Fetch needs to start fetching instructions at the very beginning,
341    // so it must start up in active state.
342    switchToActive();
343}
344
345template<class Impl>
346void
347DefaultFetch<Impl>::setIcache()
348{
349    // Size of cache block.
350    cacheBlkSize = icachePort->peerBlockSize();
351
352    // Create mask to get rid of offset bits.
353    cacheBlkMask = (cacheBlkSize - 1);
354
355    for (int tid=0; tid < numThreads; tid++) {
356        // Create space to store a cache line.
357        cacheData[tid] = new uint8_t[cacheBlkSize];
358        cacheDataPC[tid] = 0;
359        cacheDataValid[tid] = false;
360    }
361}
362
363template<class Impl>
364void
365DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
366{
367    unsigned tid = pkt->req->threadId();
368
369    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
370
371    assert(!pkt->wasNacked());
372
373    // Only change the status if it's still waiting on the icache access
374    // to return.
375    if (fetchStatus[tid] != IcacheWaitResponse ||
376        pkt->req != memReq[tid] ||
377        isSwitchedOut()) {
378        ++fetchIcacheSquashes;
379        delete pkt->req;
380        delete pkt;
381        return;
382    }
383
384    memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
385    cacheDataValid[tid] = true;
386
387    if (!drainPending) {
388        // Wake up the CPU (if it went to sleep and was waiting on
389        // this completion event).
390        cpu->wakeCPU();
391
392        DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
393                tid);
394
395        switchToActive();
396    }
397
398    // Only switch to IcacheAccessComplete if we're not stalled as well.
399    if (checkStall(tid)) {
400        fetchStatus[tid] = Blocked;
401    } else {
402        fetchStatus[tid] = IcacheAccessComplete;
403    }
404
405    // Reset the mem req to NULL.
406    delete pkt->req;
407    delete pkt;
408    memReq[tid] = NULL;
409}
410
411template <class Impl>
412bool
413DefaultFetch<Impl>::drain()
414{
415    // Fetch is ready to drain at any time.
416    cpu->signalDrained();
417    drainPending = true;
418    return true;
419}
420
421template <class Impl>
422void
423DefaultFetch<Impl>::resume()
424{
425    drainPending = false;
426}
427
428template <class Impl>
429void
430DefaultFetch<Impl>::switchOut()
431{
432    switchedOut = true;
433    // Branch predictor needs to have its state cleared.
434    branchPred.switchOut();
435}
436
437template <class Impl>
438void
439DefaultFetch<Impl>::takeOverFrom()
440{
441    // Reset all state
442    for (int i = 0; i < Impl::MaxThreads; ++i) {
443        stalls[i].decode = 0;
444        stalls[i].rename = 0;
445        stalls[i].iew = 0;
446        stalls[i].commit = 0;
447        PC[i] = cpu->readPC(i);
448        nextPC[i] = cpu->readNextPC(i);
449        microPC[i] = cpu->readMicroPC(i);
450        fetchStatus[i] = Running;
451    }
452    numInst = 0;
453    wroteToTimeBuffer = false;
454    _status = Inactive;
455    switchedOut = false;
456    interruptPending = false;
457    branchPred.takeOverFrom();
458}
459
460template <class Impl>
461void
462DefaultFetch<Impl>::wakeFromQuiesce()
463{
464    DPRINTF(Fetch, "Waking up from quiesce\n");
465    // Hopefully this is safe
466    // @todo: Allow other threads to wake from quiesce.
467    fetchStatus[0] = Running;
468}
469
470template <class Impl>
471inline void
472DefaultFetch<Impl>::switchToActive()
473{
474    if (_status == Inactive) {
475        DPRINTF(Activity, "Activating stage.\n");
476
477        cpu->activateStage(O3CPU::FetchIdx);
478
479        _status = Active;
480    }
481}
482
483template <class Impl>
484inline void
485DefaultFetch<Impl>::switchToInactive()
486{
487    if (_status == Active) {
488        DPRINTF(Activity, "Deactivating stage.\n");
489
490        cpu->deactivateStage(O3CPU::FetchIdx);
491
492        _status = Inactive;
493    }
494}
495
496template <class Impl>
497bool
498DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
499                                          Addr &next_NPC, Addr &next_MicroPC)
500{
501    // Do branch prediction check here.
502    // A bit of a misnomer...next_PC is actually the current PC until
503    // this function updates it.
504    bool predict_taken;
505
506    if (!inst->isControl()) {
507        if (inst->isMicroop() && !inst->isLastMicroop()) {
508            next_MicroPC++;
509        } else {
510            next_PC  = next_NPC;
511            next_NPC = next_NPC + instSize;
512            next_MicroPC = 0;
513        }
514        inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
515        inst->setPredTaken(false);
516        return false;
517    }
518
519    //Assume for now that all control flow is to a different macroop which
520    //would reset the micro pc to 0.
521    next_MicroPC = 0;
522
523    int tid = inst->threadNumber;
524    Addr pred_PC = next_PC;
525    predict_taken = branchPred.predict(inst, pred_PC, tid);
526
527    if (predict_taken) {
528        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %#x.\n",
529                tid, inst->seqNum, pred_PC);
530    } else {
531        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
532                tid, inst->seqNum);
533    }
534
535#if ISA_HAS_DELAY_SLOT
536    next_PC = next_NPC;
537    if (predict_taken)
538        next_NPC = pred_PC;
539    else
540        next_NPC += instSize;
541#else
542    if (predict_taken)
543        next_PC = pred_PC;
544    else
545        next_PC += instSize;
546    next_NPC = next_PC + instSize;
547#endif
548
549    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %#x and then %#x.\n",
550            tid, inst->seqNum, next_PC, next_NPC);
551    inst->setPredTarg(next_PC, next_NPC, next_MicroPC);
552    inst->setPredTaken(predict_taken);
553
554    ++fetchedBranches;
555
556    if (predict_taken) {
557        ++predictedBranches;
558    }
559
560    return predict_taken;
561}
562
563template <class Impl>
564bool
565DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
566{
567    Fault fault = NoFault;
568
569    //AlphaDep
570    if (cacheBlocked) {
571        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
572                tid);
573        return false;
574    } else if (isSwitchedOut()) {
575        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
576                tid);
577        return false;
578    } else if (interruptPending && !(fetch_PC & 0x3)) {
579        // Hold off fetch from getting new instructions when:
580        // Cache is blocked, or
581        // while an interrupt is pending and we're not in PAL mode, or
582        // fetch is switched out.
583        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
584                tid);
585        return false;
586    }
587
588    // Align the fetch PC so it's at the start of a cache block.
589    Addr block_PC = icacheBlockAlignPC(fetch_PC);
590
591    // If we've already got the block, no need to try to fetch it again.
592    if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
593        return true;
594    }
595
596    // Setup the memReq to do a read of the first instruction's address.
597    // Set the appropriate read size and flags as well.
598    // Build request here.
599    RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
600                                     fetch_PC, cpu->thread[tid]->contextId(),
601                                     tid);
602
603    memReq[tid] = mem_req;
604
605    // Translate the instruction request.
606    fault = cpu->itb->translateAtomic(mem_req, cpu->thread[tid]->getTC(),
607                                      BaseTLB::Execute);
608
609    // In the case of faults, the fetch stage may need to stall and wait
610    // for the ITB miss to be handled.
611
612    // If translation was successful, attempt to read the first
613    // instruction.
614    if (fault == NoFault) {
615#if 0
616        if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
617            memReq[tid]->isUncacheable()) {
618            DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
619                    "misspeculating path)!",
620                    memReq[tid]->paddr);
621            ret_fault = TheISA::genMachineCheckFault();
622            return false;
623        }
624#endif
625
626        // Build packet here.
627        PacketPtr data_pkt = new Packet(mem_req,
628                                        MemCmd::ReadReq, Packet::Broadcast);
629        data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
630
631        cacheDataPC[tid] = block_PC;
632        cacheDataValid[tid] = false;
633
634        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
635
636        fetchedCacheLines++;
637
638        // Now do the timing access to see whether or not the instruction
639        // exists within the cache.
640        if (!icachePort->sendTiming(data_pkt)) {
641            assert(retryPkt == NULL);
642            assert(retryTid == -1);
643            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
644            fetchStatus[tid] = IcacheWaitRetry;
645            retryPkt = data_pkt;
646            retryTid = tid;
647            cacheBlocked = true;
648            return false;
649        }
650
651        DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
652
653        lastIcacheStall[tid] = curTick;
654
655        DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
656                "response.\n", tid);
657
658        fetchStatus[tid] = IcacheWaitResponse;
659    } else {
660        delete mem_req;
661        memReq[tid] = NULL;
662    }
663
664    ret_fault = fault;
665    return true;
666}
667
668template <class Impl>
669inline void
670DefaultFetch<Impl>::doSquash(const Addr &new_PC,
671        const Addr &new_NPC, const Addr &new_microPC, unsigned tid)
672{
673    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
674            tid, new_PC, new_NPC);
675
676    PC[tid] = new_PC;
677    nextPC[tid] = new_NPC;
678    microPC[tid] = new_microPC;
679
680    // Clear the icache miss if it's outstanding.
681    if (fetchStatus[tid] == IcacheWaitResponse) {
682        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
683                tid);
684        memReq[tid] = NULL;
685    }
686
687    // Get rid of the retrying packet if it was from this thread.
688    if (retryTid == tid) {
689        assert(cacheBlocked);
690        if (retryPkt) {
691            delete retryPkt->req;
692            delete retryPkt;
693        }
694        retryPkt = NULL;
695        retryTid = -1;
696    }
697
698    fetchStatus[tid] = Squashing;
699
700    ++fetchSquashCycles;
701}
702
703template<class Impl>
704void
705DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
706                                     const Addr &new_MicroPC,
707                                     const InstSeqNum &seq_num, unsigned tid)
708{
709    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
710
711    doSquash(new_PC, new_NPC, new_MicroPC, tid);
712
713    // Tell the CPU to remove any instructions that are in flight between
714    // fetch and decode.
715    cpu->removeInstsUntil(seq_num, tid);
716}
717
718template<class Impl>
719bool
720DefaultFetch<Impl>::checkStall(unsigned tid) const
721{
722    bool ret_val = false;
723
724    if (cpu->contextSwitch) {
725        DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
726        ret_val = true;
727    } else if (stalls[tid].decode) {
728        DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
729        ret_val = true;
730    } else if (stalls[tid].rename) {
731        DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
732        ret_val = true;
733    } else if (stalls[tid].iew) {
734        DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
735        ret_val = true;
736    } else if (stalls[tid].commit) {
737        DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
738        ret_val = true;
739    }
740
741    return ret_val;
742}
743
744template<class Impl>
745typename DefaultFetch<Impl>::FetchStatus
746DefaultFetch<Impl>::updateFetchStatus()
747{
748    //Check Running
749    std::list<unsigned>::iterator threads = activeThreads->begin();
750    std::list<unsigned>::iterator end = activeThreads->end();
751
752    while (threads != end) {
753        unsigned tid = *threads++;
754
755        if (fetchStatus[tid] == Running ||
756            fetchStatus[tid] == Squashing ||
757            fetchStatus[tid] == IcacheAccessComplete) {
758
759            if (_status == Inactive) {
760                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
761
762                if (fetchStatus[tid] == IcacheAccessComplete) {
763                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
764                            "completion\n",tid);
765                }
766
767                cpu->activateStage(O3CPU::FetchIdx);
768            }
769
770            return Active;
771        }
772    }
773
774    // Stage is switching from active to inactive, notify CPU of it.
775    if (_status == Active) {
776        DPRINTF(Activity, "Deactivating stage.\n");
777
778        cpu->deactivateStage(O3CPU::FetchIdx);
779    }
780
781    return Inactive;
782}
783
784template <class Impl>
785void
786DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
787                           const Addr &new_MicroPC,
788                           const InstSeqNum &seq_num, unsigned tid)
789{
790    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
791
792    doSquash(new_PC, new_NPC, new_MicroPC, tid);
793
794    // Tell the CPU to remove any instructions that are not in the ROB.
795    cpu->removeInstsNotInROB(tid);
796}
797
798template <class Impl>
799void
800DefaultFetch<Impl>::tick()
801{
802    std::list<unsigned>::iterator threads = activeThreads->begin();
803    std::list<unsigned>::iterator end = activeThreads->end();
804    bool status_change = false;
805
806    wroteToTimeBuffer = false;
807
808    while (threads != end) {
809        unsigned tid = *threads++;
810
811        // Check the signals for each thread to determine the proper status
812        // for each thread.
813        bool updated_status = checkSignalsAndUpdate(tid);
814        status_change =  status_change || updated_status;
815    }
816
817    DPRINTF(Fetch, "Running stage.\n");
818
819    // Reset the number of the instruction we're fetching.
820    numInst = 0;
821
822#if FULL_SYSTEM
823    if (fromCommit->commitInfo[0].interruptPending) {
824        interruptPending = true;
825    }
826
827    if (fromCommit->commitInfo[0].clearInterrupt) {
828        interruptPending = false;
829    }
830#endif
831
832    for (threadFetched = 0; threadFetched < numFetchingThreads;
833         threadFetched++) {
834        // Fetch each of the actively fetching threads.
835        fetch(status_change);
836    }
837
838    // Record number of instructions fetched this cycle for distribution.
839    fetchNisnDist.sample(numInst);
840
841    if (status_change) {
842        // Change the fetch stage status if there was a status change.
843        _status = updateFetchStatus();
844    }
845
846    // If there was activity this cycle, inform the CPU of it.
847    if (wroteToTimeBuffer || cpu->contextSwitch) {
848        DPRINTF(Activity, "Activity this cycle.\n");
849
850        cpu->activityThisCycle();
851    }
852}
853
854template <class Impl>
855bool
856DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
857{
858    // Update the per thread stall statuses.
859    if (fromDecode->decodeBlock[tid]) {
860        stalls[tid].decode = true;
861    }
862
863    if (fromDecode->decodeUnblock[tid]) {
864        assert(stalls[tid].decode);
865        assert(!fromDecode->decodeBlock[tid]);
866        stalls[tid].decode = false;
867    }
868
869    if (fromRename->renameBlock[tid]) {
870        stalls[tid].rename = true;
871    }
872
873    if (fromRename->renameUnblock[tid]) {
874        assert(stalls[tid].rename);
875        assert(!fromRename->renameBlock[tid]);
876        stalls[tid].rename = false;
877    }
878
879    if (fromIEW->iewBlock[tid]) {
880        stalls[tid].iew = true;
881    }
882
883    if (fromIEW->iewUnblock[tid]) {
884        assert(stalls[tid].iew);
885        assert(!fromIEW->iewBlock[tid]);
886        stalls[tid].iew = false;
887    }
888
889    if (fromCommit->commitBlock[tid]) {
890        stalls[tid].commit = true;
891    }
892
893    if (fromCommit->commitUnblock[tid]) {
894        assert(stalls[tid].commit);
895        assert(!fromCommit->commitBlock[tid]);
896        stalls[tid].commit = false;
897    }
898
899    // Check squash signals from commit.
900    if (fromCommit->commitInfo[tid].squash) {
901
902        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
903                "from commit.\n",tid);
904        // In any case, squash.
905        squash(fromCommit->commitInfo[tid].nextPC,
906               fromCommit->commitInfo[tid].nextNPC,
907               fromCommit->commitInfo[tid].nextMicroPC,
908               fromCommit->commitInfo[tid].doneSeqNum,
909               tid);
910
911        // Also check if there's a mispredict that happened.
912        if (fromCommit->commitInfo[tid].branchMispredict) {
913            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
914                              fromCommit->commitInfo[tid].nextPC,
915                              fromCommit->commitInfo[tid].branchTaken,
916                              tid);
917        } else {
918            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
919                              tid);
920        }
921
922        return true;
923    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
924        // Update the branch predictor if it wasn't a squashed instruction
925        // that was broadcasted.
926        branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
927    }
928
929    // Check ROB squash signals from commit.
930    if (fromCommit->commitInfo[tid].robSquashing) {
931        DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
932
933        // Continue to squash.
934        fetchStatus[tid] = Squashing;
935
936        return true;
937    }
938
939    // Check squash signals from decode.
940    if (fromDecode->decodeInfo[tid].squash) {
941        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
942                "from decode.\n",tid);
943
944        // Update the branch predictor.
945        if (fromDecode->decodeInfo[tid].branchMispredict) {
946            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
947                              fromDecode->decodeInfo[tid].nextPC,
948                              fromDecode->decodeInfo[tid].branchTaken,
949                              tid);
950        } else {
951            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
952                              tid);
953        }
954
955        if (fetchStatus[tid] != Squashing) {
956
957            DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
958                    fromDecode->decodeInfo[tid].nextPC,
959                    fromDecode->decodeInfo[tid].nextNPC);
960            // Squash unless we're already squashing
961            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
962                             fromDecode->decodeInfo[tid].nextNPC,
963                             fromDecode->decodeInfo[tid].nextMicroPC,
964                             fromDecode->decodeInfo[tid].doneSeqNum,
965                             tid);
966
967            return true;
968        }
969    }
970
971    if (checkStall(tid) &&
972        fetchStatus[tid] != IcacheWaitResponse &&
973        fetchStatus[tid] != IcacheWaitRetry) {
974        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
975
976        fetchStatus[tid] = Blocked;
977
978        return true;
979    }
980
981    if (fetchStatus[tid] == Blocked ||
982        fetchStatus[tid] == Squashing) {
983        // Switch status to running if fetch isn't being told to block or
984        // squash this cycle.
985        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
986                tid);
987
988        fetchStatus[tid] = Running;
989
990        return true;
991    }
992
993    // If we've reached this point, we have not gotten any signals that
994    // cause fetch to change its status.  Fetch remains the same as before.
995    return false;
996}
997
998template<class Impl>
999void
1000DefaultFetch<Impl>::fetch(bool &status_change)
1001{
1002    //////////////////////////////////////////
1003    // Start actual fetch
1004    //////////////////////////////////////////
1005    int tid = getFetchingThread(fetchPolicy);
1006
1007    if (tid == -1 || drainPending) {
1008        DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1009
1010        // Breaks looping condition in tick()
1011        threadFetched = numFetchingThreads;
1012        return;
1013    }
1014
1015    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1016
1017    // The current PC.
1018    Addr fetch_PC = PC[tid];
1019    Addr fetch_NPC = nextPC[tid];
1020    Addr fetch_MicroPC = microPC[tid];
1021
1022    // Fault code for memory access.
1023    Fault fault = NoFault;
1024
1025    // If returning from the delay of a cache miss, then update the status
1026    // to running, otherwise do the cache access.  Possibly move this up
1027    // to tick() function.
1028    if (fetchStatus[tid] == IcacheAccessComplete) {
1029        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1030                tid);
1031
1032        fetchStatus[tid] = Running;
1033        status_change = true;
1034    } else if (fetchStatus[tid] == Running) {
1035        DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1036                "instruction, starting at PC %08p.\n",
1037                tid, fetch_PC);
1038
1039        bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1040        if (!fetch_success) {
1041            if (cacheBlocked) {
1042                ++icacheStallCycles;
1043            } else {
1044                ++fetchMiscStallCycles;
1045            }
1046            return;
1047        }
1048    } else {
1049        if (fetchStatus[tid] == Idle) {
1050            ++fetchIdleCycles;
1051            DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1052        } else if (fetchStatus[tid] == Blocked) {
1053            ++fetchBlockedCycles;
1054            DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1055        } else if (fetchStatus[tid] == Squashing) {
1056            ++fetchSquashCycles;
1057            DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1058        } else if (fetchStatus[tid] == IcacheWaitResponse) {
1059            ++icacheStallCycles;
1060            DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1061        }
1062
1063        // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1064        // fetch should do nothing.
1065        return;
1066    }
1067
1068    ++fetchCycles;
1069
1070    // If we had a stall due to an icache miss, then return.
1071    if (fetchStatus[tid] == IcacheWaitResponse) {
1072        ++icacheStallCycles;
1073        status_change = true;
1074        return;
1075    }
1076
1077    Addr next_PC = fetch_PC;
1078    Addr next_NPC = fetch_NPC;
1079    Addr next_MicroPC = fetch_MicroPC;
1080
1081    InstSeqNum inst_seq;
1082    MachInst inst;
1083    ExtMachInst ext_inst;
1084    // @todo: Fix this hack.
1085    unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1086
1087    StaticInstPtr staticInst = NULL;
1088    StaticInstPtr macroop = NULL;
1089
1090    if (fault == NoFault) {
1091        // If the read of the first instruction was successful, then grab the
1092        // instructions from the rest of the cache line and put them into the
1093        // queue heading to decode.
1094
1095        DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1096                "decode.\n",tid);
1097
1098        // Need to keep track of whether or not a predicted branch
1099        // ended this fetch block.
1100        bool predicted_branch = false;
1101
1102        while (offset < cacheBlkSize &&
1103               numInst < fetchWidth &&
1104               !predicted_branch) {
1105
1106            // If we're branching after this instruction, quite fetching
1107            // from the same block then.
1108            predicted_branch =
1109                (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1110            if (predicted_branch) {
1111                DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1112                        fetch_PC, fetch_NPC);
1113            }
1114
1115            // Make sure this is a valid index.
1116            assert(offset <= cacheBlkSize - instSize);
1117
1118            if (!macroop) {
1119                // Get the instruction from the array of the cache line.
1120                inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1121                            (&cacheData[tid][offset]));
1122
1123                predecoder.setTC(cpu->thread[tid]->getTC());
1124                predecoder.moreBytes(fetch_PC, fetch_PC, inst);
1125
1126                ext_inst = predecoder.getExtMachInst();
1127                staticInst = StaticInstPtr(ext_inst, fetch_PC);
1128                if (staticInst->isMacroop())
1129                    macroop = staticInst;
1130            }
1131            do {
1132                if (macroop) {
1133                    staticInst = macroop->fetchMicroop(fetch_MicroPC);
1134                    if (staticInst->isLastMicroop())
1135                        macroop = NULL;
1136                }
1137
1138                // Get a sequence number.
1139                inst_seq = cpu->getAndIncrementInstSeq();
1140
1141                // Create a new DynInst from the instruction fetched.
1142                DynInstPtr instruction = new DynInst(staticInst,
1143                                                     fetch_PC, fetch_NPC, fetch_MicroPC,
1144                                                     next_PC, next_NPC, next_MicroPC,
1145                                                     inst_seq, cpu);
1146                instruction->setTid(tid);
1147
1148                instruction->setASID(tid);
1149
1150                instruction->setThreadState(cpu->thread[tid]);
1151
1152                DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1153                        "[sn:%lli]\n",
1154                        tid, instruction->readPC(), inst_seq);
1155
1156                //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1157
1158                DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1159                        tid, instruction->staticInst->disassemble(fetch_PC));
1160
1161#if TRACING_ON
1162                instruction->traceData =
1163                    cpu->getTracer()->getInstRecord(curTick, cpu->tcBase(tid),
1164                            instruction->staticInst, instruction->readPC());
1165#else
1166                instruction->traceData = NULL;
1167#endif
1168
1169                ///FIXME This needs to be more robust in dealing with delay slots
1170                predicted_branch |=
1171                    lookupAndUpdateNextPC(instruction, next_PC, next_NPC, next_MicroPC);
1172
1173                // Add instruction to the CPU's list of instructions.
1174                instruction->setInstListIt(cpu->addInst(instruction));
1175
1176                // Write the instruction to the first slot in the queue
1177                // that heads to decode.
1178                toDecode->insts[numInst] = instruction;
1179
1180                toDecode->size++;
1181
1182                // Increment stat of fetched instructions.
1183                ++fetchedInsts;
1184
1185                // Move to the next instruction, unless we have a branch.
1186                fetch_PC = next_PC;
1187                fetch_NPC = next_NPC;
1188                fetch_MicroPC = next_MicroPC;
1189
1190                if (instruction->isQuiesce()) {
1191                    DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1192                            curTick);
1193                    fetchStatus[tid] = QuiescePending;
1194                    ++numInst;
1195                    status_change = true;
1196                    break;
1197                }
1198
1199                ++numInst;
1200            } while (staticInst->isMicroop() &&
1201                     !staticInst->isLastMicroop() &&
1202                     numInst < fetchWidth);
1203            offset += instSize;
1204        }
1205
1206        if (predicted_branch) {
1207            DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1208                    "instruction encountered.\n", tid);
1209        } else if (numInst >= fetchWidth) {
1210            DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1211                    "for this cycle.\n", tid);
1212        } else if (offset >= cacheBlkSize) {
1213            DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1214                    "block.\n", tid);
1215        }
1216    }
1217
1218    if (numInst > 0) {
1219        wroteToTimeBuffer = true;
1220    }
1221
1222    // Now that fetching is completed, update the PC to signify what the next
1223    // cycle will be.
1224    if (fault == NoFault) {
1225        PC[tid] = next_PC;
1226        nextPC[tid] = next_NPC;
1227        microPC[tid] = next_MicroPC;
1228        DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1229    } else {
1230        // We shouldn't be in an icache miss and also have a fault (an ITB
1231        // miss)
1232        if (fetchStatus[tid] == IcacheWaitResponse) {
1233            panic("Fetch should have exited prior to this!");
1234        }
1235
1236        // Send the fault to commit.  This thread will not do anything
1237        // until commit handles the fault.  The only other way it can
1238        // wake up is if a squash comes along and changes the PC.
1239        assert(numInst < fetchWidth);
1240        // Get a sequence number.
1241        inst_seq = cpu->getAndIncrementInstSeq();
1242        // We will use a nop in order to carry the fault.
1243        ext_inst = TheISA::NoopMachInst;
1244
1245        // Create a new DynInst from the dummy nop.
1246        DynInstPtr instruction = new DynInst(ext_inst,
1247                                             fetch_PC, fetch_NPC, fetch_MicroPC,
1248                                             next_PC, next_NPC, next_MicroPC,
1249                                             inst_seq, cpu);
1250        instruction->setPredTarg(next_NPC, next_NPC + instSize, 0);
1251        instruction->setTid(tid);
1252
1253        instruction->setASID(tid);
1254
1255        instruction->setThreadState(cpu->thread[tid]);
1256
1257        instruction->traceData = NULL;
1258
1259        instruction->setInstListIt(cpu->addInst(instruction));
1260
1261        instruction->fault = fault;
1262
1263        toDecode->insts[numInst] = instruction;
1264        toDecode->size++;
1265
1266        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1267
1268        fetchStatus[tid] = TrapPending;
1269        status_change = true;
1270
1271        DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1272                tid, fault->name(), PC[tid]);
1273    }
1274}
1275
1276template<class Impl>
1277void
1278DefaultFetch<Impl>::recvRetry()
1279{
1280    if (retryPkt != NULL) {
1281        assert(cacheBlocked);
1282        assert(retryTid != -1);
1283        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1284
1285        if (icachePort->sendTiming(retryPkt)) {
1286            fetchStatus[retryTid] = IcacheWaitResponse;
1287            retryPkt = NULL;
1288            retryTid = -1;
1289            cacheBlocked = false;
1290        }
1291    } else {
1292        assert(retryTid == -1);
1293        // Access has been squashed since it was sent out.  Just clear
1294        // the cache being blocked.
1295        cacheBlocked = false;
1296    }
1297}
1298
1299///////////////////////////////////////
1300//                                   //
1301//  SMT FETCH POLICY MAINTAINED HERE //
1302//                                   //
1303///////////////////////////////////////
1304template<class Impl>
1305int
1306DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1307{
1308    if (numThreads > 1) {
1309        switch (fetch_priority) {
1310
1311          case SingleThread:
1312            return 0;
1313
1314          case RoundRobin:
1315            return roundRobin();
1316
1317          case IQ:
1318            return iqCount();
1319
1320          case LSQ:
1321            return lsqCount();
1322
1323          case Branch:
1324            return branchCount();
1325
1326          default:
1327            return -1;
1328        }
1329    } else {
1330        std::list<unsigned>::iterator thread = activeThreads->begin();
1331        if (thread == activeThreads->end()) {
1332            return -1;
1333        }
1334
1335        int tid = *thread;
1336
1337        if (fetchStatus[tid] == Running ||
1338            fetchStatus[tid] == IcacheAccessComplete ||
1339            fetchStatus[tid] == Idle) {
1340            return tid;
1341        } else {
1342            return -1;
1343        }
1344    }
1345
1346}
1347
1348
1349template<class Impl>
1350int
1351DefaultFetch<Impl>::roundRobin()
1352{
1353    std::list<unsigned>::iterator pri_iter = priorityList.begin();
1354    std::list<unsigned>::iterator end      = priorityList.end();
1355
1356    int high_pri;
1357
1358    while (pri_iter != end) {
1359        high_pri = *pri_iter;
1360
1361        assert(high_pri <= numThreads);
1362
1363        if (fetchStatus[high_pri] == Running ||
1364            fetchStatus[high_pri] == IcacheAccessComplete ||
1365            fetchStatus[high_pri] == Idle) {
1366
1367            priorityList.erase(pri_iter);
1368            priorityList.push_back(high_pri);
1369
1370            return high_pri;
1371        }
1372
1373        pri_iter++;
1374    }
1375
1376    return -1;
1377}
1378
1379template<class Impl>
1380int
1381DefaultFetch<Impl>::iqCount()
1382{
1383    std::priority_queue<unsigned> PQ;
1384
1385    std::list<unsigned>::iterator threads = activeThreads->begin();
1386    std::list<unsigned>::iterator end = activeThreads->end();
1387
1388    while (threads != end) {
1389        unsigned tid = *threads++;
1390
1391        PQ.push(fromIEW->iewInfo[tid].iqCount);
1392    }
1393
1394    while (!PQ.empty()) {
1395
1396        unsigned high_pri = PQ.top();
1397
1398        if (fetchStatus[high_pri] == Running ||
1399            fetchStatus[high_pri] == IcacheAccessComplete ||
1400            fetchStatus[high_pri] == Idle)
1401            return high_pri;
1402        else
1403            PQ.pop();
1404
1405    }
1406
1407    return -1;
1408}
1409
1410template<class Impl>
1411int
1412DefaultFetch<Impl>::lsqCount()
1413{
1414    std::priority_queue<unsigned> PQ;
1415
1416    std::list<unsigned>::iterator threads = activeThreads->begin();
1417    std::list<unsigned>::iterator end = activeThreads->end();
1418
1419    while (threads != end) {
1420        unsigned tid = *threads++;
1421
1422        PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1423    }
1424
1425    while (!PQ.empty()) {
1426
1427        unsigned high_pri = PQ.top();
1428
1429        if (fetchStatus[high_pri] == Running ||
1430            fetchStatus[high_pri] == IcacheAccessComplete ||
1431            fetchStatus[high_pri] == Idle)
1432            return high_pri;
1433        else
1434            PQ.pop();
1435
1436    }
1437
1438    return -1;
1439}
1440
1441template<class Impl>
1442int
1443DefaultFetch<Impl>::branchCount()
1444{
1445    std::list<unsigned>::iterator thread = activeThreads->begin();
1446    assert(thread != activeThreads->end());
1447    unsigned tid = *thread;
1448
1449    panic("Branch Count Fetch policy unimplemented\n");
1450    return 0 * tid;
1451}
1452