fetch_impl.hh revision 9444:ab47fe7f03f0
17584SAli.Saidi@arm.com/*
27584SAli.Saidi@arm.com * Copyright (c) 2010-2012 ARM Limited
37584SAli.Saidi@arm.com * All rights reserved.
47584SAli.Saidi@arm.com *
57584SAli.Saidi@arm.com * The license below extends only to copyright in the software and shall
67584SAli.Saidi@arm.com * not be construed as granting a license to any other intellectual
77584SAli.Saidi@arm.com * property including but not limited to intellectual property relating
87584SAli.Saidi@arm.com * to a hardware implementation of the functionality of the software
97584SAli.Saidi@arm.com * licensed hereunder.  You may use the software subject to the license
107584SAli.Saidi@arm.com * terms below provided that you ensure that this notice is replicated
117584SAli.Saidi@arm.com * unmodified and in its entirety in all distributions of the software,
127584SAli.Saidi@arm.com * modified or unmodified, in source code or in binary form.
137584SAli.Saidi@arm.com *
147584SAli.Saidi@arm.com * Copyright (c) 2004-2006 The Regents of The University of Michigan
157584SAli.Saidi@arm.com * All rights reserved.
167584SAli.Saidi@arm.com *
177584SAli.Saidi@arm.com * Redistribution and use in source and binary forms, with or without
187584SAli.Saidi@arm.com * modification, are permitted provided that the following conditions are
197584SAli.Saidi@arm.com * met: redistributions of source code must retain the above copyright
207584SAli.Saidi@arm.com * notice, this list of conditions and the following disclaimer;
217584SAli.Saidi@arm.com * redistributions in binary form must reproduce the above copyright
227584SAli.Saidi@arm.com * notice, this list of conditions and the following disclaimer in the
237584SAli.Saidi@arm.com * documentation and/or other materials provided with the distribution;
247584SAli.Saidi@arm.com * neither the name of the copyright holders nor the names of its
257584SAli.Saidi@arm.com * contributors may be used to endorse or promote products derived from
267584SAli.Saidi@arm.com * this software without specific prior written permission.
277584SAli.Saidi@arm.com *
287584SAli.Saidi@arm.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
297584SAli.Saidi@arm.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
307584SAli.Saidi@arm.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
317584SAli.Saidi@arm.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
327584SAli.Saidi@arm.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
337584SAli.Saidi@arm.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
347584SAli.Saidi@arm.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
357584SAli.Saidi@arm.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
367584SAli.Saidi@arm.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
377584SAli.Saidi@arm.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
387584SAli.Saidi@arm.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
397584SAli.Saidi@arm.com *
407584SAli.Saidi@arm.com * Authors: Kevin Lim
417584SAli.Saidi@arm.com *          Korey Sewell
427584SAli.Saidi@arm.com */
437584SAli.Saidi@arm.com
447587SAli.Saidi@arm.com#include <algorithm>
457584SAli.Saidi@arm.com#include <cstring>
467584SAli.Saidi@arm.com#include <list>
477584SAli.Saidi@arm.com#include <map>
487584SAli.Saidi@arm.com#include <queue>
497584SAli.Saidi@arm.com
507584SAli.Saidi@arm.com#include "arch/isa_traits.hh"
517584SAli.Saidi@arm.com#include "arch/tlb.hh"
527584SAli.Saidi@arm.com#include "arch/utility.hh"
537584SAli.Saidi@arm.com#include "arch/vtophys.hh"
547584SAli.Saidi@arm.com#include "base/types.hh"
557584SAli.Saidi@arm.com#include "config/the_isa.hh"
567584SAli.Saidi@arm.com#include "cpu/base.hh"
577584SAli.Saidi@arm.com//#include "cpu/checker/cpu.hh"
587584SAli.Saidi@arm.com#include "cpu/o3/fetch.hh"
597584SAli.Saidi@arm.com#include "cpu/exetrace.hh"
607584SAli.Saidi@arm.com#include "debug/Activity.hh"
617584SAli.Saidi@arm.com#include "debug/Drain.hh"
627584SAli.Saidi@arm.com#include "debug/Fetch.hh"
637584SAli.Saidi@arm.com#include "mem/packet.hh"
647584SAli.Saidi@arm.com#include "params/DerivO3CPU.hh"
657584SAli.Saidi@arm.com#include "sim/byteswap.hh"
667584SAli.Saidi@arm.com#include "sim/core.hh"
677584SAli.Saidi@arm.com#include "sim/eventq.hh"
687584SAli.Saidi@arm.com#include "sim/full_system.hh"
697584SAli.Saidi@arm.com#include "sim/system.hh"
707584SAli.Saidi@arm.com
717584SAli.Saidi@arm.comusing namespace std;
727584SAli.Saidi@arm.com
737584SAli.Saidi@arm.comtemplate<class Impl>
747584SAli.Saidi@arm.comDefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
757584SAli.Saidi@arm.com    : cpu(_cpu),
767584SAli.Saidi@arm.com      branchPred(params),
777584SAli.Saidi@arm.com      decodeToFetchDelay(params->decodeToFetchDelay),
787584SAli.Saidi@arm.com      renameToFetchDelay(params->renameToFetchDelay),
797584SAli.Saidi@arm.com      iewToFetchDelay(params->iewToFetchDelay),
807584SAli.Saidi@arm.com      commitToFetchDelay(params->commitToFetchDelay),
817584SAli.Saidi@arm.com      fetchWidth(params->fetchWidth),
827584SAli.Saidi@arm.com      retryPkt(NULL),
837584SAli.Saidi@arm.com      retryTid(InvalidThreadID),
847584SAli.Saidi@arm.com      numThreads(params->numThreads),
857584SAli.Saidi@arm.com      numFetchingThreads(params->smtNumFetchingThreads),
867584SAli.Saidi@arm.com      finishTranslationEvent(this)
877584SAli.Saidi@arm.com{
887584SAli.Saidi@arm.com    if (numThreads > Impl::MaxThreads)
897584SAli.Saidi@arm.com        fatal("numThreads (%d) is larger than compiled limit (%d),\n"
907584SAli.Saidi@arm.com              "\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
917584SAli.Saidi@arm.com              numThreads, static_cast<int>(Impl::MaxThreads));
927584SAli.Saidi@arm.com    if (fetchWidth > Impl::MaxWidth)
937584SAli.Saidi@arm.com        fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
947584SAli.Saidi@arm.com             "\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
957584SAli.Saidi@arm.com             fetchWidth, static_cast<int>(Impl::MaxWidth));
967584SAli.Saidi@arm.com
977584SAli.Saidi@arm.com    std::string policy = params->smtFetchPolicy;
987584SAli.Saidi@arm.com
997584SAli.Saidi@arm.com    // Convert string to lowercase
1007584SAli.Saidi@arm.com    std::transform(policy.begin(), policy.end(), policy.begin(),
1017584SAli.Saidi@arm.com                   (int(*)(int)) tolower);
1027584SAli.Saidi@arm.com
1037584SAli.Saidi@arm.com    // Figure out fetch policy
1047584SAli.Saidi@arm.com    if (policy == "singlethread") {
1057584SAli.Saidi@arm.com        fetchPolicy = SingleThread;
1067584SAli.Saidi@arm.com        if (numThreads > 1)
1077584SAli.Saidi@arm.com            panic("Invalid Fetch Policy for a SMT workload.");
1087584SAli.Saidi@arm.com    } else if (policy == "roundrobin") {
1097584SAli.Saidi@arm.com        fetchPolicy = RoundRobin;
1107584SAli.Saidi@arm.com        DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
1117584SAli.Saidi@arm.com    } else if (policy == "branch") {
1127584SAli.Saidi@arm.com        fetchPolicy = Branch;
1137584SAli.Saidi@arm.com        DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
1147584SAli.Saidi@arm.com    } else if (policy == "iqcount") {
1157584SAli.Saidi@arm.com        fetchPolicy = IQ;
1167584SAli.Saidi@arm.com        DPRINTF(Fetch, "Fetch policy set to IQ count\n");
1177587SAli.Saidi@arm.com    } else if (policy == "lsqcount") {
1187587SAli.Saidi@arm.com        fetchPolicy = LSQ;
1197587SAli.Saidi@arm.com        DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
1207584SAli.Saidi@arm.com    } else {
1217584SAli.Saidi@arm.com        fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
1227587SAli.Saidi@arm.com              " RoundRobin,LSQcount,IQcount}\n");
1237584SAli.Saidi@arm.com    }
1247584SAli.Saidi@arm.com
1257584SAli.Saidi@arm.com    // Get the size of an instruction.
1267584SAli.Saidi@arm.com    instSize = sizeof(TheISA::MachInst);
1277584SAli.Saidi@arm.com
1287584SAli.Saidi@arm.com    for (int i = 0; i < Impl::MaxThreads; i++) {
1297584SAli.Saidi@arm.com        cacheData[i] = NULL;
1307584SAli.Saidi@arm.com        decoder[i] = new TheISA::Decoder;
1317584SAli.Saidi@arm.com    }
1327584SAli.Saidi@arm.com}
1337584SAli.Saidi@arm.com
1347584SAli.Saidi@arm.comtemplate <class Impl>
1357584SAli.Saidi@arm.comstd::string
1367584SAli.Saidi@arm.comDefaultFetch<Impl>::name() const
1377584SAli.Saidi@arm.com{
1387584SAli.Saidi@arm.com    return cpu->name() + ".fetch";
1397584SAli.Saidi@arm.com}
1407584SAli.Saidi@arm.com
1417584SAli.Saidi@arm.comtemplate <class Impl>
1427584SAli.Saidi@arm.comvoid
1437584SAli.Saidi@arm.comDefaultFetch<Impl>::regStats()
1447584SAli.Saidi@arm.com{
1457584SAli.Saidi@arm.com    icacheStallCycles
1467584SAli.Saidi@arm.com        .name(name() + ".icacheStallCycles")
1477584SAli.Saidi@arm.com        .desc("Number of cycles fetch is stalled on an Icache miss")
1487584SAli.Saidi@arm.com        .prereq(icacheStallCycles);
1497584SAli.Saidi@arm.com
1507584SAli.Saidi@arm.com    fetchedInsts
1517584SAli.Saidi@arm.com        .name(name() + ".Insts")
1527584SAli.Saidi@arm.com        .desc("Number of instructions fetch has processed")
1537584SAli.Saidi@arm.com        .prereq(fetchedInsts);
1547584SAli.Saidi@arm.com
1557584SAli.Saidi@arm.com    fetchedBranches
1567584SAli.Saidi@arm.com        .name(name() + ".Branches")
1577584SAli.Saidi@arm.com        .desc("Number of branches that fetch encountered")
1587584SAli.Saidi@arm.com        .prereq(fetchedBranches);
1597584SAli.Saidi@arm.com
1607584SAli.Saidi@arm.com    predictedBranches
1617584SAli.Saidi@arm.com        .name(name() + ".predictedBranches")
1627584SAli.Saidi@arm.com        .desc("Number of branches that fetch has predicted taken")
1637584SAli.Saidi@arm.com        .prereq(predictedBranches);
1647584SAli.Saidi@arm.com
1657584SAli.Saidi@arm.com    fetchCycles
1667584SAli.Saidi@arm.com        .name(name() + ".Cycles")
1677584SAli.Saidi@arm.com        .desc("Number of cycles fetch has run and was not squashing or"
1687584SAli.Saidi@arm.com              " blocked")
1697584SAli.Saidi@arm.com        .prereq(fetchCycles);
1707584SAli.Saidi@arm.com
1717584SAli.Saidi@arm.com    fetchSquashCycles
1727584SAli.Saidi@arm.com        .name(name() + ".SquashCycles")
1737584SAli.Saidi@arm.com        .desc("Number of cycles fetch has spent squashing")
1747584SAli.Saidi@arm.com        .prereq(fetchSquashCycles);
1757584SAli.Saidi@arm.com
1767584SAli.Saidi@arm.com    fetchTlbCycles
1777584SAli.Saidi@arm.com        .name(name() + ".TlbCycles")
1787584SAli.Saidi@arm.com        .desc("Number of cycles fetch has spent waiting for tlb")
1797584SAli.Saidi@arm.com        .prereq(fetchTlbCycles);
1807584SAli.Saidi@arm.com
1817584SAli.Saidi@arm.com    fetchIdleCycles
1827584SAli.Saidi@arm.com        .name(name() + ".IdleCycles")
1837584SAli.Saidi@arm.com        .desc("Number of cycles fetch was idle")
1847584SAli.Saidi@arm.com        .prereq(fetchIdleCycles);
1857584SAli.Saidi@arm.com
1867584SAli.Saidi@arm.com    fetchBlockedCycles
1877584SAli.Saidi@arm.com        .name(name() + ".BlockedCycles")
1887584SAli.Saidi@arm.com        .desc("Number of cycles fetch has spent blocked")
1897584SAli.Saidi@arm.com        .prereq(fetchBlockedCycles);
1907584SAli.Saidi@arm.com
1917584SAli.Saidi@arm.com    fetchedCacheLines
1927584SAli.Saidi@arm.com        .name(name() + ".CacheLines")
1937584SAli.Saidi@arm.com        .desc("Number of cache lines fetched")
1947584SAli.Saidi@arm.com        .prereq(fetchedCacheLines);
1957584SAli.Saidi@arm.com
1967584SAli.Saidi@arm.com    fetchMiscStallCycles
1977584SAli.Saidi@arm.com        .name(name() + ".MiscStallCycles")
1987584SAli.Saidi@arm.com        .desc("Number of cycles fetch has spent waiting on interrupts, or "
1997584SAli.Saidi@arm.com              "bad addresses, or out of MSHRs")
2007584SAli.Saidi@arm.com        .prereq(fetchMiscStallCycles);
2017584SAli.Saidi@arm.com
2027584SAli.Saidi@arm.com    fetchPendingDrainCycles
2037584SAli.Saidi@arm.com        .name(name() + ".PendingDrainCycles")
2047584SAli.Saidi@arm.com        .desc("Number of cycles fetch has spent waiting on pipes to drain")
2057584SAli.Saidi@arm.com        .prereq(fetchPendingDrainCycles);
2067584SAli.Saidi@arm.com
2077584SAli.Saidi@arm.com    fetchNoActiveThreadStallCycles
2087584SAli.Saidi@arm.com        .name(name() + ".NoActiveThreadStallCycles")
2097584SAli.Saidi@arm.com        .desc("Number of stall cycles due to no active thread to fetch from")
2107584SAli.Saidi@arm.com        .prereq(fetchNoActiveThreadStallCycles);
2117584SAli.Saidi@arm.com
2127584SAli.Saidi@arm.com    fetchPendingTrapStallCycles
2137584SAli.Saidi@arm.com        .name(name() + ".PendingTrapStallCycles")
2147584SAli.Saidi@arm.com        .desc("Number of stall cycles due to pending traps")
2157584SAli.Saidi@arm.com        .prereq(fetchPendingTrapStallCycles);
2167584SAli.Saidi@arm.com
2177584SAli.Saidi@arm.com    fetchPendingQuiesceStallCycles
2187584SAli.Saidi@arm.com        .name(name() + ".PendingQuiesceStallCycles")
2197584SAli.Saidi@arm.com        .desc("Number of stall cycles due to pending quiesce instructions")
2207584SAli.Saidi@arm.com        .prereq(fetchPendingQuiesceStallCycles);
2217584SAli.Saidi@arm.com
2227584SAli.Saidi@arm.com    fetchIcacheWaitRetryStallCycles
2237584SAli.Saidi@arm.com        .name(name() + ".IcacheWaitRetryStallCycles")
2247584SAli.Saidi@arm.com        .desc("Number of stall cycles due to full MSHR")
2257584SAli.Saidi@arm.com        .prereq(fetchIcacheWaitRetryStallCycles);
2267584SAli.Saidi@arm.com
2277584SAli.Saidi@arm.com    fetchIcacheSquashes
2287584SAli.Saidi@arm.com        .name(name() + ".IcacheSquashes")
2297584SAli.Saidi@arm.com        .desc("Number of outstanding Icache misses that were squashed")
2307584SAli.Saidi@arm.com        .prereq(fetchIcacheSquashes);
2317584SAli.Saidi@arm.com
2327584SAli.Saidi@arm.com    fetchTlbSquashes
2337584SAli.Saidi@arm.com        .name(name() + ".ItlbSquashes")
2347584SAli.Saidi@arm.com        .desc("Number of outstanding ITLB misses that were squashed")
2357584SAli.Saidi@arm.com        .prereq(fetchTlbSquashes);
2367584SAli.Saidi@arm.com
2377584SAli.Saidi@arm.com    fetchNisnDist
2387584SAli.Saidi@arm.com        .init(/* base value */ 0,
2397584SAli.Saidi@arm.com              /* last value */ fetchWidth,
2407584SAli.Saidi@arm.com              /* bucket size */ 1)
2417584SAli.Saidi@arm.com        .name(name() + ".rateDist")
2427584SAli.Saidi@arm.com        .desc("Number of instructions fetched each cycle (Total)")
2437584SAli.Saidi@arm.com        .flags(Stats::pdf);
2447584SAli.Saidi@arm.com
2457584SAli.Saidi@arm.com    idleRate
2467584SAli.Saidi@arm.com        .name(name() + ".idleRate")
2477584SAli.Saidi@arm.com        .desc("Percent of cycles fetch was idle")
2487584SAli.Saidi@arm.com        .prereq(idleRate);
2497584SAli.Saidi@arm.com    idleRate = fetchIdleCycles * 100 / cpu->numCycles;
2507584SAli.Saidi@arm.com
2517584SAli.Saidi@arm.com    branchRate
2527584SAli.Saidi@arm.com        .name(name() + ".branchRate")
2537584SAli.Saidi@arm.com        .desc("Number of branch fetches per cycle")
2547584SAli.Saidi@arm.com        .flags(Stats::total);
2557584SAli.Saidi@arm.com    branchRate = fetchedBranches / cpu->numCycles;
2567584SAli.Saidi@arm.com
2577584SAli.Saidi@arm.com    fetchRate
2587584SAli.Saidi@arm.com        .name(name() + ".rate")
2597584SAli.Saidi@arm.com        .desc("Number of inst fetches per cycle")
2607584SAli.Saidi@arm.com        .flags(Stats::total);
2617584SAli.Saidi@arm.com    fetchRate = fetchedInsts / cpu->numCycles;
2627584SAli.Saidi@arm.com
2637584SAli.Saidi@arm.com    branchPred.regStats();
2647584SAli.Saidi@arm.com}
2657584SAli.Saidi@arm.com
2667584SAli.Saidi@arm.comtemplate<class Impl>
2677584SAli.Saidi@arm.comvoid
2687584SAli.Saidi@arm.comDefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
2697584SAli.Saidi@arm.com{
2707584SAli.Saidi@arm.com    timeBuffer = time_buffer;
2717584SAli.Saidi@arm.com
2727584SAli.Saidi@arm.com    // Create wires to get information from proper places in time buffer.
2737584SAli.Saidi@arm.com    fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
2747584SAli.Saidi@arm.com    fromRename = timeBuffer->getWire(-renameToFetchDelay);
2757584SAli.Saidi@arm.com    fromIEW = timeBuffer->getWire(-iewToFetchDelay);
2767584SAli.Saidi@arm.com    fromCommit = timeBuffer->getWire(-commitToFetchDelay);
2777733SAli.Saidi@ARM.com}
2787733SAli.Saidi@ARM.com
2797733SAli.Saidi@ARM.comtemplate<class Impl>
2807733SAli.Saidi@ARM.comvoid
2817733SAli.Saidi@ARM.comDefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
2827733SAli.Saidi@ARM.com{
2837733SAli.Saidi@ARM.com    activeThreads = at_ptr;
2847733SAli.Saidi@ARM.com}
2857733SAli.Saidi@ARM.com
2867733SAli.Saidi@ARM.comtemplate<class Impl>
2877733SAli.Saidi@ARM.comvoid
2887733SAli.Saidi@ARM.comDefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
2897733SAli.Saidi@ARM.com{
2907733SAli.Saidi@ARM.com    fetchQueue = fq_ptr;
2917733SAli.Saidi@ARM.com
2927733SAli.Saidi@ARM.com    // Create wire to write information to proper place in fetch queue.
2937733SAli.Saidi@ARM.com    toDecode = fetchQueue->getWire(0);
2947733SAli.Saidi@ARM.com}
2957584SAli.Saidi@arm.com
2967584SAli.Saidi@arm.comtemplate<class Impl>
2977584SAli.Saidi@arm.comvoid
2987584SAli.Saidi@arm.comDefaultFetch<Impl>::startupStage()
2997584SAli.Saidi@arm.com{
3007733SAli.Saidi@ARM.com    assert(priorityList.empty());
3017733SAli.Saidi@ARM.com    resetStage();
3027733SAli.Saidi@ARM.com
3037733SAli.Saidi@ARM.com    // Fetch needs to start fetching instructions at the very beginning,
3047733SAli.Saidi@ARM.com    // so it must start up in active state.
3057733SAli.Saidi@ARM.com    switchToActive();
3067733SAli.Saidi@ARM.com}
3077733SAli.Saidi@ARM.com
3087733SAli.Saidi@ARM.comtemplate<class Impl>
3097733SAli.Saidi@ARM.comvoid
3107733SAli.Saidi@ARM.comDefaultFetch<Impl>::resetStage()
3117733SAli.Saidi@ARM.com{
3127733SAli.Saidi@ARM.com    numInst = 0;
3137733SAli.Saidi@ARM.com    interruptPending = false;
3147733SAli.Saidi@ARM.com    cacheBlocked = false;
3157733SAli.Saidi@ARM.com
3167733SAli.Saidi@ARM.com    priorityList.clear();
3177733SAli.Saidi@ARM.com
3187733SAli.Saidi@ARM.com    // Setup PC and nextPC with initial state.
3197733SAli.Saidi@ARM.com    for (ThreadID tid = 0; tid < numThreads; tid++) {
3207733SAli.Saidi@ARM.com        fetchStatus[tid] = Running;
3217733SAli.Saidi@ARM.com        pc[tid] = cpu->pcState(tid);
3227584SAli.Saidi@arm.com        fetchOffset[tid] = 0;
3237584SAli.Saidi@arm.com        macroop[tid] = NULL;
3247584SAli.Saidi@arm.com
3257584SAli.Saidi@arm.com        delayedCommit[tid] = false;
3267584SAli.Saidi@arm.com        memReq[tid] = NULL;
3277584SAli.Saidi@arm.com
3287584SAli.Saidi@arm.com        stalls[tid].decode = false;
329        stalls[tid].rename = false;
330        stalls[tid].iew = false;
331        stalls[tid].commit = false;
332        stalls[tid].drain = false;
333
334        priorityList.push_back(tid);
335    }
336
337    wroteToTimeBuffer = false;
338    _status = Inactive;
339
340    // this CPU could still be unconnected if we are restoring from a
341    // checkpoint and this CPU is to be switched in, thus we can only
342    // do this here if the instruction port is actually connected, if
343    // not we have to do it as part of takeOverFrom.
344    if (cpu->getInstPort().isConnected())
345        setIcache();
346}
347
348template<class Impl>
349void
350DefaultFetch<Impl>::setIcache()
351{
352    assert(cpu->getInstPort().isConnected());
353
354    // Size of cache block.
355    cacheBlkSize = cpu->getInstPort().peerBlockSize();
356
357    // Create mask to get rid of offset bits.
358    cacheBlkMask = (cacheBlkSize - 1);
359
360    for (ThreadID tid = 0; tid < numThreads; tid++) {
361        // Create space to store a cache line.
362        if (!cacheData[tid])
363            cacheData[tid] = new uint8_t[cacheBlkSize];
364        cacheDataPC[tid] = 0;
365        cacheDataValid[tid] = false;
366    }
367}
368
369template<class Impl>
370void
371DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
372{
373    ThreadID tid = pkt->req->threadId();
374
375    DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
376    assert(!cpu->switchedOut());
377
378    // Only change the status if it's still waiting on the icache access
379    // to return.
380    if (fetchStatus[tid] != IcacheWaitResponse ||
381        pkt->req != memReq[tid]) {
382        ++fetchIcacheSquashes;
383        delete pkt->req;
384        delete pkt;
385        return;
386    }
387
388    memcpy(cacheData[tid], pkt->getPtr<uint8_t>(), cacheBlkSize);
389    cacheDataValid[tid] = true;
390
391    // Wake up the CPU (if it went to sleep and was waiting on
392    // this completion event).
393    cpu->wakeCPU();
394
395    DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
396            tid);
397
398    switchToActive();
399
400    // Only switch to IcacheAccessComplete if we're not stalled as well.
401    if (checkStall(tid)) {
402        fetchStatus[tid] = Blocked;
403    } else {
404        fetchStatus[tid] = IcacheAccessComplete;
405    }
406
407    // Reset the mem req to NULL.
408    delete pkt->req;
409    delete pkt;
410    memReq[tid] = NULL;
411}
412
413template <class Impl>
414void
415DefaultFetch<Impl>::drainResume()
416{
417    for (ThreadID i = 0; i < Impl::MaxThreads; ++i)
418        stalls[i].drain = false;
419}
420
421template <class Impl>
422void
423DefaultFetch<Impl>::drainSanityCheck() const
424{
425    assert(isDrained());
426    assert(retryPkt == NULL);
427    assert(retryTid == InvalidThreadID);
428    assert(cacheBlocked == false);
429    assert(interruptPending == false);
430
431    for (ThreadID i = 0; i < numThreads; ++i) {
432        assert(!memReq[i]);
433        assert(!stalls[i].decode);
434        assert(!stalls[i].rename);
435        assert(!stalls[i].iew);
436        assert(!stalls[i].commit);
437        assert(fetchStatus[i] == Idle || stalls[i].drain);
438    }
439
440    branchPred.drainSanityCheck();
441}
442
443template <class Impl>
444bool
445DefaultFetch<Impl>::isDrained() const
446{
447    /* Make sure that threads are either idle of that the commit stage
448     * has signaled that draining has completed by setting the drain
449     * stall flag. This effectively forces the pipeline to be disabled
450     * until the whole system is drained (simulation may continue to
451     * drain other components).
452     */
453    for (ThreadID i = 0; i < numThreads; ++i) {
454        if (!(fetchStatus[i] == Idle ||
455              (fetchStatus[i] == Blocked && stalls[i].drain)))
456            return false;
457    }
458
459    /* The pipeline might start up again in the middle of the drain
460     * cycle if the finish translation event is scheduled, so make
461     * sure that's not the case.
462     */
463    return !finishTranslationEvent.scheduled();
464}
465
466template <class Impl>
467void
468DefaultFetch<Impl>::takeOverFrom()
469{
470    assert(cpu->getInstPort().isConnected());
471    resetStage();
472
473    branchPred.takeOverFrom();
474}
475
476template <class Impl>
477void
478DefaultFetch<Impl>::drainStall(ThreadID tid)
479{
480    assert(cpu->isDraining());
481    assert(!stalls[tid].drain);
482    DPRINTF(Drain, "%i: Thread drained.\n", tid);
483    stalls[tid].drain = true;
484}
485
486template <class Impl>
487void
488DefaultFetch<Impl>::wakeFromQuiesce()
489{
490    DPRINTF(Fetch, "Waking up from quiesce\n");
491    // Hopefully this is safe
492    // @todo: Allow other threads to wake from quiesce.
493    fetchStatus[0] = Running;
494}
495
496template <class Impl>
497inline void
498DefaultFetch<Impl>::switchToActive()
499{
500    if (_status == Inactive) {
501        DPRINTF(Activity, "Activating stage.\n");
502
503        cpu->activateStage(O3CPU::FetchIdx);
504
505        _status = Active;
506    }
507}
508
509template <class Impl>
510inline void
511DefaultFetch<Impl>::switchToInactive()
512{
513    if (_status == Active) {
514        DPRINTF(Activity, "Deactivating stage.\n");
515
516        cpu->deactivateStage(O3CPU::FetchIdx);
517
518        _status = Inactive;
519    }
520}
521
522template <class Impl>
523bool
524DefaultFetch<Impl>::lookupAndUpdateNextPC(
525        DynInstPtr &inst, TheISA::PCState &nextPC)
526{
527    // Do branch prediction check here.
528    // A bit of a misnomer...next_PC is actually the current PC until
529    // this function updates it.
530    bool predict_taken;
531
532    if (!inst->isControl()) {
533        TheISA::advancePC(nextPC, inst->staticInst);
534        inst->setPredTarg(nextPC);
535        inst->setPredTaken(false);
536        return false;
537    }
538
539    ThreadID tid = inst->threadNumber;
540    predict_taken = branchPred.predict(inst, nextPC, tid);
541
542    if (predict_taken) {
543        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:  Branch predicted to be taken to %s.\n",
544                tid, inst->seqNum, nextPC);
545    } else {
546        DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
547                tid, inst->seqNum);
548    }
549
550    DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
551            tid, inst->seqNum, nextPC);
552    inst->setPredTarg(nextPC);
553    inst->setPredTaken(predict_taken);
554
555    ++fetchedBranches;
556
557    if (predict_taken) {
558        ++predictedBranches;
559    }
560
561    return predict_taken;
562}
563
564template <class Impl>
565bool
566DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
567{
568    Fault fault = NoFault;
569
570    assert(!cpu->switchedOut());
571
572    // @todo: not sure if these should block translation.
573    //AlphaDep
574    if (cacheBlocked) {
575        DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
576                tid);
577        return false;
578    } else if (checkInterrupt(pc) && !delayedCommit[tid]) {
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 address so it's at the start of a cache block.
589    Addr block_PC = icacheBlockAlignPC(vaddr);
590
591    DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
592            tid, block_PC, vaddr);
593
594    // Setup the memReq to do a read of the first instruction's address.
595    // Set the appropriate read size and flags as well.
596    // Build request here.
597    RequestPtr mem_req =
598        new Request(tid, block_PC, cacheBlkSize, Request::INST_FETCH,
599                    cpu->instMasterId(), pc, cpu->thread[tid]->contextId(), tid);
600
601    memReq[tid] = mem_req;
602
603    // Initiate translation of the icache block
604    fetchStatus[tid] = ItlbWait;
605    FetchTranslation *trans = new FetchTranslation(this);
606    cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
607                              trans, BaseTLB::Execute);
608    return true;
609}
610
611template <class Impl>
612void
613DefaultFetch<Impl>::finishTranslation(Fault fault, RequestPtr mem_req)
614{
615    ThreadID tid = mem_req->threadId();
616    Addr block_PC = mem_req->getVaddr();
617
618    assert(!cpu->switchedOut());
619
620    // Wake up CPU if it was idle
621    cpu->wakeCPU();
622
623    if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
624        mem_req->getVaddr() != memReq[tid]->getVaddr()) {
625        DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
626                tid);
627        ++fetchTlbSquashes;
628        delete mem_req;
629        return;
630    }
631
632
633    // If translation was successful, attempt to read the icache block.
634    if (fault == NoFault) {
635        // Check that we're not going off into random memory
636        // If we have, just wait around for commit to squash something and put
637        // us on the right track
638        if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
639            warn("Address %#x is outside of physical memory, stopping fetch\n",
640                    mem_req->getPaddr());
641            fetchStatus[tid] = NoGoodAddr;
642            delete mem_req;
643            memReq[tid] = NULL;
644            return;
645        }
646
647        // Build packet here.
648        PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
649        data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
650
651        cacheDataPC[tid] = block_PC;
652        cacheDataValid[tid] = false;
653        DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
654
655        fetchedCacheLines++;
656
657        // Access the cache.
658        if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
659            assert(retryPkt == NULL);
660            assert(retryTid == InvalidThreadID);
661            DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
662
663            fetchStatus[tid] = IcacheWaitRetry;
664            retryPkt = data_pkt;
665            retryTid = tid;
666            cacheBlocked = true;
667        } else {
668            DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
669            DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
670                    "response.\n", tid);
671
672            lastIcacheStall[tid] = curTick();
673            fetchStatus[tid] = IcacheWaitResponse;
674        }
675    } else {
676        if (!(numInst < fetchWidth)) {
677            assert(!finishTranslationEvent.scheduled());
678            finishTranslationEvent.setFault(fault);
679            finishTranslationEvent.setReq(mem_req);
680            cpu->schedule(finishTranslationEvent,
681                          cpu->clockEdge(Cycles(1)));
682            return;
683        }
684        DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
685                tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
686        // Translation faulted, icache request won't be sent.
687        delete mem_req;
688        memReq[tid] = NULL;
689
690        // Send the fault to commit.  This thread will not do anything
691        // until commit handles the fault.  The only other way it can
692        // wake up is if a squash comes along and changes the PC.
693        TheISA::PCState fetchPC = pc[tid];
694
695        DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
696        // We will use a nop in ordier to carry the fault.
697        DynInstPtr instruction = buildInst(tid,
698                decoder[tid]->decode(TheISA::NoopMachInst, fetchPC.instAddr()),
699                NULL, fetchPC, fetchPC, false);
700
701        instruction->setPredTarg(fetchPC);
702        instruction->fault = fault;
703        wroteToTimeBuffer = true;
704
705        DPRINTF(Activity, "Activity this cycle.\n");
706        cpu->activityThisCycle();
707
708        fetchStatus[tid] = TrapPending;
709
710        DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
711        DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
712                tid, fault->name(), pc[tid]);
713    }
714    _status = updateFetchStatus();
715}
716
717template <class Impl>
718inline void
719DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
720                             const DynInstPtr squashInst, ThreadID tid)
721{
722    DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
723            tid, newPC);
724
725    pc[tid] = newPC;
726    fetchOffset[tid] = 0;
727    if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
728        macroop[tid] = squashInst->macroop;
729    else
730        macroop[tid] = NULL;
731    decoder[tid]->reset();
732
733    // Clear the icache miss if it's outstanding.
734    if (fetchStatus[tid] == IcacheWaitResponse) {
735        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
736                tid);
737        memReq[tid] = NULL;
738    } else if (fetchStatus[tid] == ItlbWait) {
739        DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
740                tid);
741        memReq[tid] = NULL;
742    }
743
744    // Get rid of the retrying packet if it was from this thread.
745    if (retryTid == tid) {
746        assert(cacheBlocked);
747        if (retryPkt) {
748            delete retryPkt->req;
749            delete retryPkt;
750        }
751        retryPkt = NULL;
752        retryTid = InvalidThreadID;
753    }
754
755    fetchStatus[tid] = Squashing;
756
757    // microops are being squashed, it is not known wheather the
758    // youngest non-squashed microop was  marked delayed commit
759    // or not. Setting the flag to true ensures that the
760    // interrupts are not handled when they cannot be, though
761    // some opportunities to handle interrupts may be missed.
762    delayedCommit[tid] = true;
763
764    ++fetchSquashCycles;
765}
766
767template<class Impl>
768void
769DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
770                                     const DynInstPtr squashInst,
771                                     const InstSeqNum seq_num, ThreadID tid)
772{
773    DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
774
775    doSquash(newPC, squashInst, tid);
776
777    // Tell the CPU to remove any instructions that are in flight between
778    // fetch and decode.
779    cpu->removeInstsUntil(seq_num, tid);
780}
781
782template<class Impl>
783bool
784DefaultFetch<Impl>::checkStall(ThreadID tid) const
785{
786    bool ret_val = false;
787
788    if (cpu->contextSwitch) {
789        DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
790        ret_val = true;
791    } else if (stalls[tid].drain) {
792        assert(cpu->isDraining());
793        DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid);
794        ret_val = true;
795    } else if (stalls[tid].decode) {
796        DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
797        ret_val = true;
798    } else if (stalls[tid].rename) {
799        DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
800        ret_val = true;
801    } else if (stalls[tid].iew) {
802        DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
803        ret_val = true;
804    } else if (stalls[tid].commit) {
805        DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
806        ret_val = true;
807    }
808
809    return ret_val;
810}
811
812template<class Impl>
813typename DefaultFetch<Impl>::FetchStatus
814DefaultFetch<Impl>::updateFetchStatus()
815{
816    //Check Running
817    list<ThreadID>::iterator threads = activeThreads->begin();
818    list<ThreadID>::iterator end = activeThreads->end();
819
820    while (threads != end) {
821        ThreadID tid = *threads++;
822
823        if (fetchStatus[tid] == Running ||
824            fetchStatus[tid] == Squashing ||
825            fetchStatus[tid] == IcacheAccessComplete) {
826
827            if (_status == Inactive) {
828                DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
829
830                if (fetchStatus[tid] == IcacheAccessComplete) {
831                    DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
832                            "completion\n",tid);
833                }
834
835                cpu->activateStage(O3CPU::FetchIdx);
836            }
837
838            return Active;
839        }
840    }
841
842    // Stage is switching from active to inactive, notify CPU of it.
843    if (_status == Active) {
844        DPRINTF(Activity, "Deactivating stage.\n");
845
846        cpu->deactivateStage(O3CPU::FetchIdx);
847    }
848
849    return Inactive;
850}
851
852template <class Impl>
853void
854DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
855                           const InstSeqNum seq_num, DynInstPtr squashInst,
856                           ThreadID tid)
857{
858    DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
859
860    doSquash(newPC, squashInst, tid);
861
862    // Tell the CPU to remove any instructions that are not in the ROB.
863    cpu->removeInstsNotInROB(tid);
864}
865
866template <class Impl>
867void
868DefaultFetch<Impl>::tick()
869{
870    list<ThreadID>::iterator threads = activeThreads->begin();
871    list<ThreadID>::iterator end = activeThreads->end();
872    bool status_change = false;
873
874    wroteToTimeBuffer = false;
875
876    for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
877        issuePipelinedIfetch[i] = false;
878    }
879
880    while (threads != end) {
881        ThreadID tid = *threads++;
882
883        // Check the signals for each thread to determine the proper status
884        // for each thread.
885        bool updated_status = checkSignalsAndUpdate(tid);
886        status_change =  status_change || updated_status;
887    }
888
889    DPRINTF(Fetch, "Running stage.\n");
890
891    if (FullSystem) {
892        if (fromCommit->commitInfo[0].interruptPending) {
893            interruptPending = true;
894        }
895
896        if (fromCommit->commitInfo[0].clearInterrupt) {
897            interruptPending = false;
898        }
899    }
900
901    for (threadFetched = 0; threadFetched < numFetchingThreads;
902         threadFetched++) {
903        // Fetch each of the actively fetching threads.
904        fetch(status_change);
905    }
906
907    // Record number of instructions fetched this cycle for distribution.
908    fetchNisnDist.sample(numInst);
909
910    if (status_change) {
911        // Change the fetch stage status if there was a status change.
912        _status = updateFetchStatus();
913    }
914
915    // If there was activity this cycle, inform the CPU of it.
916    if (wroteToTimeBuffer || cpu->contextSwitch) {
917        DPRINTF(Activity, "Activity this cycle.\n");
918
919        cpu->activityThisCycle();
920    }
921
922    // Issue the next I-cache request if possible.
923    for (ThreadID i = 0; i < Impl::MaxThreads; ++i) {
924        if (issuePipelinedIfetch[i]) {
925            pipelineIcacheAccesses(i);
926        }
927    }
928
929    // Reset the number of the instruction we've fetched.
930    numInst = 0;
931}
932
933template <class Impl>
934bool
935DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
936{
937    // Update the per thread stall statuses.
938    if (fromDecode->decodeBlock[tid]) {
939        stalls[tid].decode = true;
940    }
941
942    if (fromDecode->decodeUnblock[tid]) {
943        assert(stalls[tid].decode);
944        assert(!fromDecode->decodeBlock[tid]);
945        stalls[tid].decode = false;
946    }
947
948    if (fromRename->renameBlock[tid]) {
949        stalls[tid].rename = true;
950    }
951
952    if (fromRename->renameUnblock[tid]) {
953        assert(stalls[tid].rename);
954        assert(!fromRename->renameBlock[tid]);
955        stalls[tid].rename = false;
956    }
957
958    if (fromIEW->iewBlock[tid]) {
959        stalls[tid].iew = true;
960    }
961
962    if (fromIEW->iewUnblock[tid]) {
963        assert(stalls[tid].iew);
964        assert(!fromIEW->iewBlock[tid]);
965        stalls[tid].iew = false;
966    }
967
968    if (fromCommit->commitBlock[tid]) {
969        stalls[tid].commit = true;
970    }
971
972    if (fromCommit->commitUnblock[tid]) {
973        assert(stalls[tid].commit);
974        assert(!fromCommit->commitBlock[tid]);
975        stalls[tid].commit = false;
976    }
977
978    // Check squash signals from commit.
979    if (fromCommit->commitInfo[tid].squash) {
980
981        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
982                "from commit.\n",tid);
983        // In any case, squash.
984        squash(fromCommit->commitInfo[tid].pc,
985               fromCommit->commitInfo[tid].doneSeqNum,
986               fromCommit->commitInfo[tid].squashInst, tid);
987
988        // If it was a branch mispredict on a control instruction, update the
989        // branch predictor with that instruction, otherwise just kill the
990        // invalid state we generated in after sequence number
991        if (fromCommit->commitInfo[tid].mispredictInst &&
992            fromCommit->commitInfo[tid].mispredictInst->isControl()) {
993            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
994                              fromCommit->commitInfo[tid].pc,
995                              fromCommit->commitInfo[tid].branchTaken,
996                              tid);
997        } else {
998            branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
999                              tid);
1000        }
1001
1002        return true;
1003    } else if (fromCommit->commitInfo[tid].doneSeqNum) {
1004        // Update the branch predictor if it wasn't a squashed instruction
1005        // that was broadcasted.
1006        branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
1007    }
1008
1009    // Check ROB squash signals from commit.
1010    if (fromCommit->commitInfo[tid].robSquashing) {
1011        DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
1012
1013        // Continue to squash.
1014        fetchStatus[tid] = Squashing;
1015
1016        return true;
1017    }
1018
1019    // Check squash signals from decode.
1020    if (fromDecode->decodeInfo[tid].squash) {
1021        DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
1022                "from decode.\n",tid);
1023
1024        // Update the branch predictor.
1025        if (fromDecode->decodeInfo[tid].branchMispredict) {
1026            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
1027                              fromDecode->decodeInfo[tid].nextPC,
1028                              fromDecode->decodeInfo[tid].branchTaken,
1029                              tid);
1030        } else {
1031            branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
1032                              tid);
1033        }
1034
1035        if (fetchStatus[tid] != Squashing) {
1036
1037            DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
1038                fromDecode->decodeInfo[tid].nextPC);
1039            // Squash unless we're already squashing
1040            squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
1041                             fromDecode->decodeInfo[tid].squashInst,
1042                             fromDecode->decodeInfo[tid].doneSeqNum,
1043                             tid);
1044
1045            return true;
1046        }
1047    }
1048
1049    if (checkStall(tid) &&
1050        fetchStatus[tid] != IcacheWaitResponse &&
1051        fetchStatus[tid] != IcacheWaitRetry) {
1052        DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
1053
1054        fetchStatus[tid] = Blocked;
1055
1056        return true;
1057    }
1058
1059    if (fetchStatus[tid] == Blocked ||
1060        fetchStatus[tid] == Squashing) {
1061        // Switch status to running if fetch isn't being told to block or
1062        // squash this cycle.
1063        DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1064                tid);
1065
1066        fetchStatus[tid] = Running;
1067
1068        return true;
1069    }
1070
1071    // If we've reached this point, we have not gotten any signals that
1072    // cause fetch to change its status.  Fetch remains the same as before.
1073    return false;
1074}
1075
1076template<class Impl>
1077typename Impl::DynInstPtr
1078DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
1079                              StaticInstPtr curMacroop, TheISA::PCState thisPC,
1080                              TheISA::PCState nextPC, bool trace)
1081{
1082    // Get a sequence number.
1083    InstSeqNum seq = cpu->getAndIncrementInstSeq();
1084
1085    // Create a new DynInst from the instruction fetched.
1086    DynInstPtr instruction =
1087        new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
1088    instruction->setTid(tid);
1089
1090    instruction->setASID(tid);
1091
1092    instruction->setThreadState(cpu->thread[tid]);
1093
1094    DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
1095            "[sn:%lli].\n", tid, thisPC.instAddr(),
1096            thisPC.microPC(), seq);
1097
1098    DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
1099            instruction->staticInst->
1100            disassemble(thisPC.instAddr()));
1101
1102#if TRACING_ON
1103    if (trace) {
1104        instruction->traceData =
1105            cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
1106                    instruction->staticInst, thisPC, curMacroop);
1107    }
1108#else
1109    instruction->traceData = NULL;
1110#endif
1111
1112    // Add instruction to the CPU's list of instructions.
1113    instruction->setInstListIt(cpu->addInst(instruction));
1114
1115    // Write the instruction to the first slot in the queue
1116    // that heads to decode.
1117    assert(numInst < fetchWidth);
1118    toDecode->insts[toDecode->size++] = instruction;
1119
1120    // Keep track of if we can take an interrupt at this boundary
1121    delayedCommit[tid] = instruction->isDelayedCommit();
1122
1123    return instruction;
1124}
1125
1126template<class Impl>
1127void
1128DefaultFetch<Impl>::fetch(bool &status_change)
1129{
1130    //////////////////////////////////////////
1131    // Start actual fetch
1132    //////////////////////////////////////////
1133    ThreadID tid = getFetchingThread(fetchPolicy);
1134
1135    assert(!cpu->switchedOut());
1136
1137    if (tid == InvalidThreadID) {
1138        // Breaks looping condition in tick()
1139        threadFetched = numFetchingThreads;
1140
1141        if (numThreads == 1) {  // @todo Per-thread stats
1142            profileStall(0);
1143        }
1144
1145        return;
1146    }
1147
1148    DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1149
1150    // The current PC.
1151    TheISA::PCState thisPC = pc[tid];
1152
1153    Addr pcOffset = fetchOffset[tid];
1154    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1155
1156    bool inRom = isRomMicroPC(thisPC.microPC());
1157
1158    // If returning from the delay of a cache miss, then update the status
1159    // to running, otherwise do the cache access.  Possibly move this up
1160    // to tick() function.
1161    if (fetchStatus[tid] == IcacheAccessComplete) {
1162        DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
1163
1164        fetchStatus[tid] = Running;
1165        status_change = true;
1166    } else if (fetchStatus[tid] == Running) {
1167        // Align the fetch PC so its at the start of a cache block.
1168        Addr block_PC = icacheBlockAlignPC(fetchAddr);
1169
1170        // If buffer is no longer valid or fetchAddr has moved to point
1171        // to the next cache block, AND we have no remaining ucode
1172        // from a macro-op, then start fetch from icache.
1173        if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])
1174            && !inRom && !macroop[tid]) {
1175            DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1176                    "instruction, starting at PC %s.\n", tid, thisPC);
1177
1178            fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1179
1180            if (fetchStatus[tid] == IcacheWaitResponse)
1181                ++icacheStallCycles;
1182            else if (fetchStatus[tid] == ItlbWait)
1183                ++fetchTlbCycles;
1184            else
1185                ++fetchMiscStallCycles;
1186            return;
1187        } else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) {
1188            // Stall CPU if an interrupt is posted and we're not issuing
1189            // an delayed commit micro-op currently (delayed commit instructions
1190            // are not interruptable by interrupts, only faults)
1191            ++fetchMiscStallCycles;
1192            DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
1193            return;
1194        }
1195    } else {
1196        if (fetchStatus[tid] == Idle) {
1197            ++fetchIdleCycles;
1198            DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1199        }
1200
1201        // Status is Idle, so fetch should do nothing.
1202        return;
1203    }
1204
1205    ++fetchCycles;
1206
1207    TheISA::PCState nextPC = thisPC;
1208
1209    StaticInstPtr staticInst = NULL;
1210    StaticInstPtr curMacroop = macroop[tid];
1211
1212    // If the read of the first instruction was successful, then grab the
1213    // instructions from the rest of the cache line and put them into the
1214    // queue heading to decode.
1215
1216    DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1217            "decode.\n", tid);
1218
1219    // Need to keep track of whether or not a predicted branch
1220    // ended this fetch block.
1221    bool predictedBranch = false;
1222
1223    TheISA::MachInst *cacheInsts =
1224        reinterpret_cast<TheISA::MachInst *>(cacheData[tid]);
1225
1226    const unsigned numInsts = cacheBlkSize / instSize;
1227    unsigned blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1228
1229    // Loop through instruction memory from the cache.
1230    // Keep issuing while fetchWidth is available and branch is not
1231    // predicted taken
1232    while (numInst < fetchWidth && !predictedBranch) {
1233
1234        // We need to process more memory if we aren't going to get a
1235        // StaticInst from the rom, the current macroop, or what's already
1236        // in the decoder.
1237        bool needMem = !inRom && !curMacroop &&
1238            !decoder[tid]->instReady();
1239        fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1240        Addr block_PC = icacheBlockAlignPC(fetchAddr);
1241
1242        if (needMem) {
1243            // If buffer is no longer valid or fetchAddr has moved to point
1244            // to the next cache block then start fetch from icache.
1245            if (!cacheDataValid[tid] || block_PC != cacheDataPC[tid])
1246                break;
1247
1248            if (blkOffset >= numInsts) {
1249                // We need to process more memory, but we've run out of the
1250                // current block.
1251                break;
1252            }
1253
1254            if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
1255                // Walk past any annulled delay slot instructions.
1256                Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
1257                while (fetchAddr != pcAddr && blkOffset < numInsts) {
1258                    blkOffset++;
1259                    fetchAddr += instSize;
1260                }
1261                if (blkOffset >= numInsts)
1262                    break;
1263            }
1264
1265            MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
1266            decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
1267
1268            if (decoder[tid]->needMoreBytes()) {
1269                blkOffset++;
1270                fetchAddr += instSize;
1271                pcOffset += instSize;
1272            }
1273        }
1274
1275        // Extract as many instructions and/or microops as we can from
1276        // the memory we've processed so far.
1277        do {
1278            if (!(curMacroop || inRom)) {
1279                if (decoder[tid]->instReady()) {
1280                    staticInst = decoder[tid]->decode(thisPC);
1281
1282                    // Increment stat of fetched instructions.
1283                    ++fetchedInsts;
1284
1285                    if (staticInst->isMacroop()) {
1286                        curMacroop = staticInst;
1287                    } else {
1288                        pcOffset = 0;
1289                    }
1290                } else {
1291                    // We need more bytes for this instruction so blkOffset and
1292                    // pcOffset will be updated
1293                    break;
1294                }
1295            }
1296            // Whether we're moving to a new macroop because we're at the
1297            // end of the current one, or the branch predictor incorrectly
1298            // thinks we are...
1299            bool newMacro = false;
1300            if (curMacroop || inRom) {
1301                if (inRom) {
1302                    staticInst = cpu->microcodeRom.fetchMicroop(
1303                            thisPC.microPC(), curMacroop);
1304                } else {
1305                    staticInst = curMacroop->fetchMicroop(thisPC.microPC());
1306                }
1307                newMacro |= staticInst->isLastMicroop();
1308            }
1309
1310            DynInstPtr instruction =
1311                buildInst(tid, staticInst, curMacroop,
1312                          thisPC, nextPC, true);
1313
1314            numInst++;
1315
1316#if TRACING_ON
1317            instruction->fetchTick = curTick();
1318#endif
1319
1320            nextPC = thisPC;
1321
1322            // If we're branching after this instruction, quite fetching
1323            // from the same block then.
1324            predictedBranch |= thisPC.branching();
1325            predictedBranch |=
1326                lookupAndUpdateNextPC(instruction, nextPC);
1327            if (predictedBranch) {
1328                DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
1329            }
1330
1331            newMacro |= thisPC.instAddr() != nextPC.instAddr();
1332
1333            // Move to the next instruction, unless we have a branch.
1334            thisPC = nextPC;
1335            inRom = isRomMicroPC(thisPC.microPC());
1336
1337            if (newMacro) {
1338                fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
1339                blkOffset = (fetchAddr - cacheDataPC[tid]) / instSize;
1340                pcOffset = 0;
1341                curMacroop = NULL;
1342            }
1343
1344            if (instruction->isQuiesce()) {
1345                DPRINTF(Fetch,
1346                        "Quiesce instruction encountered, halting fetch!");
1347                fetchStatus[tid] = QuiescePending;
1348                status_change = true;
1349                break;
1350            }
1351        } while ((curMacroop || decoder[tid]->instReady()) &&
1352                 numInst < fetchWidth);
1353    }
1354
1355    if (predictedBranch) {
1356        DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1357                "instruction encountered.\n", tid);
1358    } else if (numInst >= fetchWidth) {
1359        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1360                "for this cycle.\n", tid);
1361    } else if (blkOffset >= cacheBlkSize) {
1362        DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1363                "block.\n", tid);
1364    }
1365
1366    macroop[tid] = curMacroop;
1367    fetchOffset[tid] = pcOffset;
1368
1369    if (numInst > 0) {
1370        wroteToTimeBuffer = true;
1371    }
1372
1373    pc[tid] = thisPC;
1374
1375    // pipeline a fetch if we're crossing a cache boundary and not in
1376    // a state that would preclude fetching
1377    fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1378    Addr block_PC = icacheBlockAlignPC(fetchAddr);
1379    issuePipelinedIfetch[tid] = block_PC != cacheDataPC[tid] &&
1380        fetchStatus[tid] != IcacheWaitResponse &&
1381        fetchStatus[tid] != ItlbWait &&
1382        fetchStatus[tid] != IcacheWaitRetry &&
1383        fetchStatus[tid] != QuiescePending &&
1384        !curMacroop;
1385}
1386
1387template<class Impl>
1388void
1389DefaultFetch<Impl>::recvRetry()
1390{
1391    if (retryPkt != NULL) {
1392        assert(cacheBlocked);
1393        assert(retryTid != InvalidThreadID);
1394        assert(fetchStatus[retryTid] == IcacheWaitRetry);
1395
1396        if (cpu->getInstPort().sendTimingReq(retryPkt)) {
1397            fetchStatus[retryTid] = IcacheWaitResponse;
1398            retryPkt = NULL;
1399            retryTid = InvalidThreadID;
1400            cacheBlocked = false;
1401        }
1402    } else {
1403        assert(retryTid == InvalidThreadID);
1404        // Access has been squashed since it was sent out.  Just clear
1405        // the cache being blocked.
1406        cacheBlocked = false;
1407    }
1408}
1409
1410///////////////////////////////////////
1411//                                   //
1412//  SMT FETCH POLICY MAINTAINED HERE //
1413//                                   //
1414///////////////////////////////////////
1415template<class Impl>
1416ThreadID
1417DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1418{
1419    if (numThreads > 1) {
1420        switch (fetch_priority) {
1421
1422          case SingleThread:
1423            return 0;
1424
1425          case RoundRobin:
1426            return roundRobin();
1427
1428          case IQ:
1429            return iqCount();
1430
1431          case LSQ:
1432            return lsqCount();
1433
1434          case Branch:
1435            return branchCount();
1436
1437          default:
1438            return InvalidThreadID;
1439        }
1440    } else {
1441        list<ThreadID>::iterator thread = activeThreads->begin();
1442        if (thread == activeThreads->end()) {
1443            return InvalidThreadID;
1444        }
1445
1446        ThreadID tid = *thread;
1447
1448        if (fetchStatus[tid] == Running ||
1449            fetchStatus[tid] == IcacheAccessComplete ||
1450            fetchStatus[tid] == Idle) {
1451            return tid;
1452        } else {
1453            return InvalidThreadID;
1454        }
1455    }
1456}
1457
1458
1459template<class Impl>
1460ThreadID
1461DefaultFetch<Impl>::roundRobin()
1462{
1463    list<ThreadID>::iterator pri_iter = priorityList.begin();
1464    list<ThreadID>::iterator end      = priorityList.end();
1465
1466    ThreadID high_pri;
1467
1468    while (pri_iter != end) {
1469        high_pri = *pri_iter;
1470
1471        assert(high_pri <= numThreads);
1472
1473        if (fetchStatus[high_pri] == Running ||
1474            fetchStatus[high_pri] == IcacheAccessComplete ||
1475            fetchStatus[high_pri] == Idle) {
1476
1477            priorityList.erase(pri_iter);
1478            priorityList.push_back(high_pri);
1479
1480            return high_pri;
1481        }
1482
1483        pri_iter++;
1484    }
1485
1486    return InvalidThreadID;
1487}
1488
1489template<class Impl>
1490ThreadID
1491DefaultFetch<Impl>::iqCount()
1492{
1493    std::priority_queue<unsigned> PQ;
1494    std::map<unsigned, ThreadID> threadMap;
1495
1496    list<ThreadID>::iterator threads = activeThreads->begin();
1497    list<ThreadID>::iterator end = activeThreads->end();
1498
1499    while (threads != end) {
1500        ThreadID tid = *threads++;
1501        unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
1502
1503        PQ.push(iqCount);
1504        threadMap[iqCount] = tid;
1505    }
1506
1507    while (!PQ.empty()) {
1508        ThreadID high_pri = threadMap[PQ.top()];
1509
1510        if (fetchStatus[high_pri] == Running ||
1511            fetchStatus[high_pri] == IcacheAccessComplete ||
1512            fetchStatus[high_pri] == Idle)
1513            return high_pri;
1514        else
1515            PQ.pop();
1516
1517    }
1518
1519    return InvalidThreadID;
1520}
1521
1522template<class Impl>
1523ThreadID
1524DefaultFetch<Impl>::lsqCount()
1525{
1526    std::priority_queue<unsigned> PQ;
1527    std::map<unsigned, ThreadID> threadMap;
1528
1529    list<ThreadID>::iterator threads = activeThreads->begin();
1530    list<ThreadID>::iterator end = activeThreads->end();
1531
1532    while (threads != end) {
1533        ThreadID tid = *threads++;
1534        unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
1535
1536        PQ.push(ldstqCount);
1537        threadMap[ldstqCount] = tid;
1538    }
1539
1540    while (!PQ.empty()) {
1541        ThreadID high_pri = threadMap[PQ.top()];
1542
1543        if (fetchStatus[high_pri] == Running ||
1544            fetchStatus[high_pri] == IcacheAccessComplete ||
1545            fetchStatus[high_pri] == Idle)
1546            return high_pri;
1547        else
1548            PQ.pop();
1549    }
1550
1551    return InvalidThreadID;
1552}
1553
1554template<class Impl>
1555ThreadID
1556DefaultFetch<Impl>::branchCount()
1557{
1558#if 0
1559    list<ThreadID>::iterator thread = activeThreads->begin();
1560    assert(thread != activeThreads->end());
1561    ThreadID tid = *thread;
1562#endif
1563
1564    panic("Branch Count Fetch policy unimplemented\n");
1565    return InvalidThreadID;
1566}
1567
1568template<class Impl>
1569void
1570DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
1571{
1572    if (!issuePipelinedIfetch[tid]) {
1573        return;
1574    }
1575
1576    // The next PC to access.
1577    TheISA::PCState thisPC = pc[tid];
1578
1579    if (isRomMicroPC(thisPC.microPC())) {
1580        return;
1581    }
1582
1583    Addr pcOffset = fetchOffset[tid];
1584    Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
1585
1586    // Align the fetch PC so its at the start of a cache block.
1587    Addr block_PC = icacheBlockAlignPC(fetchAddr);
1588
1589    // Unless buffer already got the block, fetch it from icache.
1590    if (!(cacheDataValid[tid] && block_PC == cacheDataPC[tid])) {
1591        DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
1592                "starting at PC %s.\n", tid, thisPC);
1593
1594        fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
1595    }
1596}
1597
1598template<class Impl>
1599void
1600DefaultFetch<Impl>::profileStall(ThreadID tid) {
1601    DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1602
1603    // @todo Per-thread stats
1604
1605    if (stalls[tid].drain) {
1606        ++fetchPendingDrainCycles;
1607        DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
1608    } else if (activeThreads->empty()) {
1609        ++fetchNoActiveThreadStallCycles;
1610        DPRINTF(Fetch, "Fetch has no active thread!\n");
1611    } else if (fetchStatus[tid] == Blocked) {
1612        ++fetchBlockedCycles;
1613        DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1614    } else if (fetchStatus[tid] == Squashing) {
1615        ++fetchSquashCycles;
1616        DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1617    } else if (fetchStatus[tid] == IcacheWaitResponse) {
1618        ++icacheStallCycles;
1619        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
1620                tid);
1621    } else if (fetchStatus[tid] == ItlbWait) {
1622        ++fetchTlbCycles;
1623        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
1624                "finish!\n", tid);
1625    } else if (fetchStatus[tid] == TrapPending) {
1626        ++fetchPendingTrapStallCycles;
1627        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
1628                tid);
1629    } else if (fetchStatus[tid] == QuiescePending) {
1630        ++fetchPendingQuiesceStallCycles;
1631        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
1632                "instruction!\n", tid);
1633    } else if (fetchStatus[tid] == IcacheWaitRetry) {
1634        ++fetchIcacheWaitRetryStallCycles;
1635        DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
1636                tid);
1637    } else if (fetchStatus[tid] == NoGoodAddr) {
1638            DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
1639                    tid);
1640    } else {
1641        DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
1642             tid, fetchStatus[tid]);
1643    }
1644}
1645