2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "config/use_checker.hh"
34 #include "arch/isa_traits.hh"
35 #include "arch/utility.hh"
36 #include "cpu/checker/cpu.hh"
37 #include "cpu/exetrace.hh"
38 #include "cpu/o3/fetch.hh"
39 #include "mem/packet.hh"
40 #include "mem/request.hh"
41 #include "sim/byteswap.hh"
42 #include "sim/host.hh"
43 #include "sim/core.hh"
46 #include "arch/tlb.hh"
47 #include "arch/vtophys.hh"
48 #include "sim/system.hh"
55 DefaultFetch<Impl>::IcachePort::setPeer(Port *port)
64 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
66 panic("DefaultFetch doesn't expect recvAtomic callback!");
72 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
74 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
80 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
82 if (status == RangeChange) {
83 if (!snoopRangeSent) {
84 snoopRangeSent = true;
85 sendStatusChange(Port::RangeChange);
90 panic("DefaultFetch doesn't expect recvStatusChange callback!");
95 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
97 DPRINTF(Fetch, "Received timing\n");
98 if (pkt->isResponse()) {
99 fetch->processCacheCompletion(pkt);
101 //else Snooped a coherence request, just return
107 DefaultFetch<Impl>::IcachePort::recvRetry()
113 DefaultFetch<Impl>::DefaultFetch(Params *params)
114 : branchPred(params),
116 decodeToFetchDelay(params->decodeToFetchDelay),
117 renameToFetchDelay(params->renameToFetchDelay),
118 iewToFetchDelay(params->iewToFetchDelay),
119 commitToFetchDelay(params->commitToFetchDelay),
120 fetchWidth(params->fetchWidth),
124 numThreads(params->numberOfThreads),
125 numFetchingThreads(params->smtNumFetchingThreads),
126 interruptPending(false),
130 if (numThreads > Impl::MaxThreads)
131 fatal("numThreads is not a valid value\n");
133 // Set fetch stage's status to inactive.
136 std::string policy = params->smtFetchPolicy;
138 // Convert string to lowercase
139 std::transform(policy.begin(), policy.end(), policy.begin(),
140 (int(*)(int)) tolower);
142 // Figure out fetch policy
143 if (policy == "singlethread") {
144 fetchPolicy = SingleThread;
146 panic("Invalid Fetch Policy for a SMT workload.");
147 } else if (policy == "roundrobin") {
148 fetchPolicy = RoundRobin;
149 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
150 } else if (policy == "branch") {
151 fetchPolicy = Branch;
152 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
153 } else if (policy == "iqcount") {
155 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
156 } else if (policy == "lsqcount") {
158 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
160 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
161 " RoundRobin,LSQcount,IQcount}\n");
164 // Get the size of an instruction.
165 instSize = sizeof(TheISA::MachInst);
168 template <class Impl>
170 DefaultFetch<Impl>::name() const
172 return cpu->name() + ".fetch";
175 template <class Impl>
177 DefaultFetch<Impl>::regStats()
180 .name(name() + ".icacheStallCycles")
181 .desc("Number of cycles fetch is stalled on an Icache miss")
182 .prereq(icacheStallCycles);
185 .name(name() + ".Insts")
186 .desc("Number of instructions fetch has processed")
187 .prereq(fetchedInsts);
190 .name(name() + ".Branches")
191 .desc("Number of branches that fetch encountered")
192 .prereq(fetchedBranches);
195 .name(name() + ".predictedBranches")
196 .desc("Number of branches that fetch has predicted taken")
197 .prereq(predictedBranches);
200 .name(name() + ".Cycles")
201 .desc("Number of cycles fetch has run and was not squashing or"
203 .prereq(fetchCycles);
206 .name(name() + ".SquashCycles")
207 .desc("Number of cycles fetch has spent squashing")
208 .prereq(fetchSquashCycles);
211 .name(name() + ".IdleCycles")
212 .desc("Number of cycles fetch was idle")
213 .prereq(fetchIdleCycles);
216 .name(name() + ".BlockedCycles")
217 .desc("Number of cycles fetch has spent blocked")
218 .prereq(fetchBlockedCycles);
221 .name(name() + ".CacheLines")
222 .desc("Number of cache lines fetched")
223 .prereq(fetchedCacheLines);
226 .name(name() + ".MiscStallCycles")
227 .desc("Number of cycles fetch has spent waiting on interrupts, or "
228 "bad addresses, or out of MSHRs")
229 .prereq(fetchMiscStallCycles);
232 .name(name() + ".IcacheSquashes")
233 .desc("Number of outstanding Icache misses that were squashed")
234 .prereq(fetchIcacheSquashes);
237 .init(/* base value */ 0,
238 /* last value */ fetchWidth,
240 .name(name() + ".rateDist")
241 .desc("Number of instructions fetched each cycle (Total)")
245 .name(name() + ".idleRate")
246 .desc("Percent of cycles fetch was idle")
248 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
251 .name(name() + ".branchRate")
252 .desc("Number of branch fetches per cycle")
253 .flags(Stats::total);
254 branchRate = fetchedBranches / cpu->numCycles;
257 .name(name() + ".rate")
258 .desc("Number of inst fetches per cycle")
259 .flags(Stats::total);
260 fetchRate = fetchedInsts / cpu->numCycles;
262 branchPred.regStats();
267 DefaultFetch<Impl>::setCPU(O3CPU *cpu_ptr)
270 DPRINTF(Fetch, "Setting the CPU pointer.\n");
272 // Name is finally available, so create the port.
273 icachePort = new IcachePort(this);
275 icachePort->snoopRangeSent = false;
279 cpu->checker->setIcachePort(icachePort);
283 // Schedule fetch to get the correct PC from the CPU
284 // scheduleFetchStartupEvent(1);
286 // Fetch needs to start fetching instructions at the very beginning,
287 // so it must start up in active state.
293 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
295 timeBuffer = time_buffer;
297 // Create wires to get information from proper places in time buffer.
298 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
299 fromRename = timeBuffer->getWire(-renameToFetchDelay);
300 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
301 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
306 DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
308 activeThreads = at_ptr;
313 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
317 // Create wire to write information to proper place in fetch queue.
318 toDecode = fetchQueue->getWire(0);
323 DefaultFetch<Impl>::initStage()
325 // Setup PC and nextPC with initial state.
326 for (int tid = 0; tid < numThreads; tid++) {
327 PC[tid] = cpu->readPC(tid);
328 nextPC[tid] = cpu->readNextPC(tid);
329 nextNPC[tid] = cpu->readNextNPC(tid);
332 for (int tid=0; tid < numThreads; tid++) {
334 fetchStatus[tid] = Running;
336 priorityList.push_back(tid);
340 stalls[tid].decode = false;
341 stalls[tid].rename = false;
342 stalls[tid].iew = false;
343 stalls[tid].commit = false;
349 DefaultFetch<Impl>::setIcache()
351 // Size of cache block.
352 cacheBlkSize = icachePort->peerBlockSize();
354 // Create mask to get rid of offset bits.
355 cacheBlkMask = (cacheBlkSize - 1);
357 for (int tid=0; tid < numThreads; tid++) {
358 // Create space to store a cache line.
359 cacheData[tid] = new uint8_t[cacheBlkSize];
360 cacheDataPC[tid] = 0;
361 cacheDataValid[tid] = false;
367 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
369 unsigned tid = pkt->req->getThreadNum();
371 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
373 // Only change the status if it's still waiting on the icache access
375 if (fetchStatus[tid] != IcacheWaitResponse ||
376 pkt->req != memReq[tid] ||
378 ++fetchIcacheSquashes;
384 memcpy(cacheData[tid], pkt->getPtr<uint8_t *>(), cacheBlkSize);
385 cacheDataValid[tid] = true;
388 // Wake up the CPU (if it went to sleep and was waiting on
389 // this completion event).
392 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
398 // Only switch to IcacheAccessComplete if we're not stalled as well.
399 if (checkStall(tid)) {
400 fetchStatus[tid] = Blocked;
402 fetchStatus[tid] = IcacheAccessComplete;
405 // Reset the mem req to NULL.
411 template <class Impl>
413 DefaultFetch<Impl>::drain()
415 // Fetch is ready to drain at any time.
416 cpu->signalDrained();
421 template <class Impl>
423 DefaultFetch<Impl>::resume()
425 drainPending = false;
428 template <class Impl>
430 DefaultFetch<Impl>::switchOut()
433 // Branch predictor needs to have its state cleared.
434 branchPred.switchOut();
437 template <class Impl>
439 DefaultFetch<Impl>::takeOverFrom()
442 for (int i = 0; i < Impl::MaxThreads; ++i) {
443 stalls[i].decode = 0;
444 stalls[i].rename = 0;
446 stalls[i].commit = 0;
447 PC[i] = cpu->readPC(i);
448 nextPC[i] = cpu->readNextPC(i);
449 #if ISA_HAS_DELAY_SLOT
450 nextNPC[i] = cpu->readNextNPC(i);
452 nextNPC[i] = nextPC[i] + sizeof(TheISA::MachInst);
454 fetchStatus[i] = Running;
457 wroteToTimeBuffer = false;
460 interruptPending = false;
461 branchPred.takeOverFrom();
464 template <class Impl>
466 DefaultFetch<Impl>::wakeFromQuiesce()
468 DPRINTF(Fetch, "Waking up from quiesce\n");
469 // Hopefully this is safe
470 // @todo: Allow other threads to wake from quiesce.
471 fetchStatus[0] = Running;
474 template <class Impl>
476 DefaultFetch<Impl>::switchToActive()
478 if (_status == Inactive) {
479 DPRINTF(Activity, "Activating stage.\n");
481 cpu->activateStage(O3CPU::FetchIdx);
487 template <class Impl>
489 DefaultFetch<Impl>::switchToInactive()
491 if (_status == Active) {
492 DPRINTF(Activity, "Deactivating stage.\n");
494 cpu->deactivateStage(O3CPU::FetchIdx);
500 template <class Impl>
502 DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
505 // Do branch prediction check here.
506 // A bit of a misnomer...next_PC is actually the current PC until
507 // this function updates it.
510 if (!inst->isControl()) {
512 next_NPC = next_NPC + instSize;
513 inst->setPredTarg(next_PC, next_NPC);
514 inst->setPredTaken(false);
518 int tid = inst->threadNumber;
519 Addr pred_PC = next_PC;
520 predict_taken = branchPred.predict(inst, pred_PC, tid);
522 /* if (predict_taken) {
523 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be taken to %#x.\n",
526 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be not taken.\n", tid);
529 #if ISA_HAS_DELAY_SLOT
534 next_NPC += instSize;
540 next_NPC = next_PC + instSize;
542 /* DPRINTF(Fetch, "[tid:%i]: Branch predicted to go to %#x and then %#x.\n",
543 tid, next_PC, next_NPC);*/
544 inst->setPredTarg(next_PC, next_NPC);
545 inst->setPredTaken(predict_taken);
553 return predict_taken;
556 template <class Impl>
558 DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
560 Fault fault = NoFault;
564 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
567 } else if (isSwitchedOut()) {
568 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
571 } else if (interruptPending && !(fetch_PC & 0x3)) {
572 // Hold off fetch from getting new instructions when:
573 // Cache is blocked, or
574 // while an interrupt is pending and we're not in PAL mode, or
575 // fetch is switched out.
576 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
581 // Align the fetch PC so it's at the start of a cache block.
582 Addr block_PC = icacheBlockAlignPC(fetch_PC);
584 // If we've already got the block, no need to try to fetch it again.
585 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
589 // Setup the memReq to do a read of the first instruction's address.
590 // Set the appropriate read size and flags as well.
591 // Build request here.
592 RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
593 fetch_PC, cpu->readCpuId(), tid);
595 memReq[tid] = mem_req;
597 // Translate the instruction request.
598 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
600 // In the case of faults, the fetch stage may need to stall and wait
601 // for the ITB miss to be handled.
603 // If translation was successful, attempt to read the first
605 if (fault == NoFault) {
607 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
608 memReq[tid]->isUncacheable()) {
609 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
610 "misspeculating path)!",
612 ret_fault = TheISA::genMachineCheckFault();
617 // Build packet here.
618 PacketPtr data_pkt = new Packet(mem_req,
619 MemCmd::ReadReq, Packet::Broadcast);
620 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
622 cacheDataPC[tid] = block_PC;
623 cacheDataValid[tid] = false;
625 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
629 // Now do the timing access to see whether or not the instruction
630 // exists within the cache.
631 if (!icachePort->sendTiming(data_pkt)) {
632 if (data_pkt->result == Packet::BadAddress) {
633 fault = TheISA::genMachineCheckFault();
636 warn("Bad address!\n");
638 assert(retryPkt == NULL);
639 assert(retryTid == -1);
640 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
641 fetchStatus[tid] = IcacheWaitRetry;
648 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
650 lastIcacheStall[tid] = curTick;
652 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
655 fetchStatus[tid] = IcacheWaitResponse;
665 template <class Impl>
667 DefaultFetch<Impl>::doSquash(const Addr &new_PC,
668 const Addr &new_NPC, unsigned tid)
670 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
671 tid, new_PC, new_NPC);
674 nextPC[tid] = new_NPC;
675 nextNPC[tid] = new_NPC + instSize;
677 // Clear the icache miss if it's outstanding.
678 if (fetchStatus[tid] == IcacheWaitResponse) {
679 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
684 // Get rid of the retrying packet if it was from this thread.
685 if (retryTid == tid) {
686 assert(cacheBlocked);
688 delete retryPkt->req;
695 fetchStatus[tid] = Squashing;
702 DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
703 const InstSeqNum &seq_num,
706 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
708 doSquash(new_PC, new_NPC, tid);
710 // Tell the CPU to remove any instructions that are in flight between
712 cpu->removeInstsUntil(seq_num, tid);
717 DefaultFetch<Impl>::checkStall(unsigned tid) const
719 bool ret_val = false;
721 if (cpu->contextSwitch) {
722 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
724 } else if (stalls[tid].decode) {
725 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
727 } else if (stalls[tid].rename) {
728 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
730 } else if (stalls[tid].iew) {
731 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
733 } else if (stalls[tid].commit) {
734 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
742 typename DefaultFetch<Impl>::FetchStatus
743 DefaultFetch<Impl>::updateFetchStatus()
746 std::list<unsigned>::iterator threads = activeThreads->begin();
747 std::list<unsigned>::iterator end = activeThreads->end();
749 while (threads != end) {
750 unsigned tid = *threads++;
752 if (fetchStatus[tid] == Running ||
753 fetchStatus[tid] == Squashing ||
754 fetchStatus[tid] == IcacheAccessComplete) {
756 if (_status == Inactive) {
757 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
759 if (fetchStatus[tid] == IcacheAccessComplete) {
760 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
764 cpu->activateStage(O3CPU::FetchIdx);
771 // Stage is switching from active to inactive, notify CPU of it.
772 if (_status == Active) {
773 DPRINTF(Activity, "Deactivating stage.\n");
775 cpu->deactivateStage(O3CPU::FetchIdx);
781 template <class Impl>
783 DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
784 const InstSeqNum &seq_num,
785 bool squash_delay_slot, unsigned tid)
787 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
789 doSquash(new_PC, new_NPC, tid);
791 #if ISA_HAS_DELAY_SLOT
792 // Tell the CPU to remove any instructions that are not in the ROB.
793 cpu->removeInstsNotInROB(tid, squash_delay_slot, seq_num);
795 // Tell the CPU to remove any instructions that are not in the ROB.
796 cpu->removeInstsNotInROB(tid, true, 0);
800 template <class Impl>
802 DefaultFetch<Impl>::tick()
804 std::list<unsigned>::iterator threads = activeThreads->begin();
805 std::list<unsigned>::iterator end = activeThreads->end();
806 bool status_change = false;
808 wroteToTimeBuffer = false;
810 while (threads != end) {
811 unsigned tid = *threads++;
813 // Check the signals for each thread to determine the proper status
815 bool updated_status = checkSignalsAndUpdate(tid);
816 status_change = status_change || updated_status;
819 DPRINTF(Fetch, "Running stage.\n");
821 // Reset the number of the instruction we're fetching.
825 if (fromCommit->commitInfo[0].interruptPending) {
826 interruptPending = true;
829 if (fromCommit->commitInfo[0].clearInterrupt) {
830 interruptPending = false;
834 for (threadFetched = 0; threadFetched < numFetchingThreads;
836 // Fetch each of the actively fetching threads.
837 fetch(status_change);
840 // Record number of instructions fetched this cycle for distribution.
841 fetchNisnDist.sample(numInst);
844 // Change the fetch stage status if there was a status change.
845 _status = updateFetchStatus();
848 // If there was activity this cycle, inform the CPU of it.
849 if (wroteToTimeBuffer || cpu->contextSwitch) {
850 DPRINTF(Activity, "Activity this cycle.\n");
852 cpu->activityThisCycle();
856 template <class Impl>
858 DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
860 // Update the per thread stall statuses.
861 if (fromDecode->decodeBlock[tid]) {
862 stalls[tid].decode = true;
865 if (fromDecode->decodeUnblock[tid]) {
866 assert(stalls[tid].decode);
867 assert(!fromDecode->decodeBlock[tid]);
868 stalls[tid].decode = false;
871 if (fromRename->renameBlock[tid]) {
872 stalls[tid].rename = true;
875 if (fromRename->renameUnblock[tid]) {
876 assert(stalls[tid].rename);
877 assert(!fromRename->renameBlock[tid]);
878 stalls[tid].rename = false;
881 if (fromIEW->iewBlock[tid]) {
882 stalls[tid].iew = true;
885 if (fromIEW->iewUnblock[tid]) {
886 assert(stalls[tid].iew);
887 assert(!fromIEW->iewBlock[tid]);
888 stalls[tid].iew = false;
891 if (fromCommit->commitBlock[tid]) {
892 stalls[tid].commit = true;
895 if (fromCommit->commitUnblock[tid]) {
896 assert(stalls[tid].commit);
897 assert(!fromCommit->commitBlock[tid]);
898 stalls[tid].commit = false;
901 // Check squash signals from commit.
902 if (fromCommit->commitInfo[tid].squash) {
904 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
905 "from commit.\n",tid);
907 #if ISA_HAS_DELAY_SLOT
908 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
910 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].doneSeqNum;
912 // In any case, squash.
913 squash(fromCommit->commitInfo[tid].nextPC,
914 fromCommit->commitInfo[tid].nextNPC,
916 fromCommit->commitInfo[tid].squashDelaySlot,
919 // Also check if there's a mispredict that happened.
920 if (fromCommit->commitInfo[tid].branchMispredict) {
921 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
922 fromCommit->commitInfo[tid].nextPC,
923 fromCommit->commitInfo[tid].branchTaken,
926 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
931 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
932 // Update the branch predictor if it wasn't a squashed instruction
933 // that was broadcasted.
934 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
937 // Check ROB squash signals from commit.
938 if (fromCommit->commitInfo[tid].robSquashing) {
939 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
941 // Continue to squash.
942 fetchStatus[tid] = Squashing;
947 // Check squash signals from decode.
948 if (fromDecode->decodeInfo[tid].squash) {
949 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
950 "from decode.\n",tid);
952 // Update the branch predictor.
953 if (fromDecode->decodeInfo[tid].branchMispredict) {
954 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
955 fromDecode->decodeInfo[tid].nextPC,
956 fromDecode->decodeInfo[tid].branchTaken,
959 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
963 if (fetchStatus[tid] != Squashing) {
965 #if ISA_HAS_DELAY_SLOT
966 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].bdelayDoneSeqNum;
968 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].doneSeqNum;
970 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
971 fromDecode->decodeInfo[tid].nextPC,
972 fromDecode->decodeInfo[tid].nextNPC);
973 // Squash unless we're already squashing
974 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
975 fromDecode->decodeInfo[tid].nextNPC,
983 if (checkStall(tid) &&
984 fetchStatus[tid] != IcacheWaitResponse &&
985 fetchStatus[tid] != IcacheWaitRetry) {
986 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
988 fetchStatus[tid] = Blocked;
993 if (fetchStatus[tid] == Blocked ||
994 fetchStatus[tid] == Squashing) {
995 // Switch status to running if fetch isn't being told to block or
996 // squash this cycle.
997 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
1000 fetchStatus[tid] = Running;
1005 // If we've reached this point, we have not gotten any signals that
1006 // cause fetch to change its status. Fetch remains the same as before.
1010 template<class Impl>
1012 DefaultFetch<Impl>::fetch(bool &status_change)
1014 //////////////////////////////////////////
1015 // Start actual fetch
1016 //////////////////////////////////////////
1017 int tid = getFetchingThread(fetchPolicy);
1019 if (tid == -1 || drainPending) {
1020 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1022 // Breaks looping condition in tick()
1023 threadFetched = numFetchingThreads;
1027 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1030 Addr &fetch_PC = PC[tid];
1032 Addr &fetch_NPC = nextPC[tid];
1034 // Fault code for memory access.
1035 Fault fault = NoFault;
1037 // If returning from the delay of a cache miss, then update the status
1038 // to running, otherwise do the cache access. Possibly move this up
1039 // to tick() function.
1040 if (fetchStatus[tid] == IcacheAccessComplete) {
1041 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1044 fetchStatus[tid] = Running;
1045 status_change = true;
1046 } else if (fetchStatus[tid] == Running) {
1047 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1048 "instruction, starting at PC %08p.\n",
1051 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1052 if (!fetch_success) {
1054 ++icacheStallCycles;
1056 ++fetchMiscStallCycles;
1061 if (fetchStatus[tid] == Idle) {
1063 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1064 } else if (fetchStatus[tid] == Blocked) {
1065 ++fetchBlockedCycles;
1066 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1067 } else if (fetchStatus[tid] == Squashing) {
1068 ++fetchSquashCycles;
1069 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1070 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1071 ++icacheStallCycles;
1072 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1075 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1076 // fetch should do nothing.
1082 // If we had a stall due to an icache miss, then return.
1083 if (fetchStatus[tid] == IcacheWaitResponse) {
1084 ++icacheStallCycles;
1085 status_change = true;
1089 Addr next_PC = fetch_PC;
1090 Addr next_NPC = fetch_NPC;
1092 InstSeqNum inst_seq;
1094 ExtMachInst ext_inst;
1095 // @todo: Fix this hack.
1096 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1098 if (fault == NoFault) {
1099 // If the read of the first instruction was successful, then grab the
1100 // instructions from the rest of the cache line and put them into the
1101 // queue heading to decode.
1103 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1106 // Need to keep track of whether or not a predicted branch
1107 // ended this fetch block.
1108 bool predicted_branch = false;
1111 offset < cacheBlkSize &&
1112 numInst < fetchWidth &&
1116 // If we're branching after this instruction, quite fetching
1117 // from the same block then.
1119 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1120 if (predicted_branch) {
1121 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1122 fetch_PC, fetch_NPC);
1126 // Get a sequence number.
1127 inst_seq = cpu->getAndIncrementInstSeq();
1129 // Make sure this is a valid index.
1130 assert(offset <= cacheBlkSize - instSize);
1132 // Get the instruction from the array of the cache line.
1133 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1134 (&cacheData[tid][offset]));
1136 predecoder.setTC(cpu->thread[tid]->getTC());
1137 predecoder.moreBytes(fetch_PC, 0, inst);
1139 ext_inst = predecoder.getExtMachInst();
1141 // Create a new DynInst from the instruction fetched.
1142 DynInstPtr instruction = new DynInst(ext_inst,
1143 fetch_PC, fetch_NPC,
1146 instruction->setTid(tid);
1148 instruction->setASID(tid);
1150 instruction->setThreadState(cpu->thread[tid]);
1152 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1154 tid, instruction->readPC(), inst_seq);
1156 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1158 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1159 tid, instruction->staticInst->disassemble(fetch_PC));
1161 instruction->traceData =
1162 Trace::getInstRecord(curTick, cpu->tcBase(tid),
1163 instruction->staticInst,
1164 instruction->readPC());
1166 ///FIXME This needs to be more robust in dealing with delay slots
1167 #if !ISA_HAS_DELAY_SLOT
1168 // predicted_branch |=
1170 lookupAndUpdateNextPC(instruction, next_PC, next_NPC);
1171 predicted_branch |= (next_PC != fetch_NPC);
1173 // Add instruction to the CPU's list of instructions.
1174 instruction->setInstListIt(cpu->addInst(instruction));
1176 // Write the instruction to the first slot in the queue
1177 // that heads to decode.
1178 toDecode->insts[numInst] = instruction;
1182 // Increment stat of fetched instructions.
1185 // Move to the next instruction, unless we have a branch.
1187 fetch_NPC = next_NPC;
1189 if (instruction->isQuiesce()) {
1190 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1192 fetchStatus[tid] = QuiescePending;
1194 status_change = true;
1201 if (offset >= cacheBlkSize) {
1202 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1204 } else if (numInst >= fetchWidth) {
1205 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1206 "for this cycle.\n", tid);
1207 } else if (predicted_branch) {
1208 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1209 "instruction encountered.\n", tid);
1214 wroteToTimeBuffer = true;
1217 // Now that fetching is completed, update the PC to signify what the next
1219 if (fault == NoFault) {
1221 nextPC[tid] = next_NPC;
1222 nextNPC[tid] = next_NPC + instSize;
1223 #if ISA_HAS_DELAY_SLOT
1224 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]);
1226 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1229 // We shouldn't be in an icache miss and also have a fault (an ITB
1231 if (fetchStatus[tid] == IcacheWaitResponse) {
1232 panic("Fetch should have exited prior to this!");
1235 // Send the fault to commit. This thread will not do anything
1236 // until commit handles the fault. The only other way it can
1237 // 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;
1245 // Create a new DynInst from the dummy nop.
1246 DynInstPtr instruction = new DynInst(ext_inst,
1247 fetch_PC, fetch_NPC,
1250 instruction->setPredTarg(next_PC, next_NPC);
1251 instruction->setTid(tid);
1253 instruction->setASID(tid);
1255 instruction->setThreadState(cpu->thread[tid]);
1257 instruction->traceData = NULL;
1259 instruction->setInstListIt(cpu->addInst(instruction));
1261 instruction->fault = fault;
1263 toDecode->insts[numInst] = instruction;
1266 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1268 fetchStatus[tid] = TrapPending;
1269 status_change = true;
1270 #else // !FULL_SYSTEM
1271 fetchStatus[tid] = TrapPending;
1272 status_change = true;
1274 #endif // FULL_SYSTEM
1275 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1276 tid, fault->name(), PC[tid]);
1280 template<class Impl>
1282 DefaultFetch<Impl>::recvRetry()
1284 if (retryPkt != NULL) {
1285 assert(cacheBlocked);
1286 assert(retryTid != -1);
1287 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1289 if (icachePort->sendTiming(retryPkt)) {
1290 fetchStatus[retryTid] = IcacheWaitResponse;
1293 cacheBlocked = false;
1296 assert(retryTid == -1);
1297 // Access has been squashed since it was sent out. Just clear
1298 // the cache being blocked.
1299 cacheBlocked = false;
1303 ///////////////////////////////////////
1305 // SMT FETCH POLICY MAINTAINED HERE //
1307 ///////////////////////////////////////
1308 template<class Impl>
1310 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1312 if (numThreads > 1) {
1313 switch (fetch_priority) {
1319 return roundRobin();
1328 return branchCount();
1334 std::list<unsigned>::iterator thread = activeThreads->begin();
1335 assert(thread != activeThreads->end());
1338 if (fetchStatus[tid] == Running ||
1339 fetchStatus[tid] == IcacheAccessComplete ||
1340 fetchStatus[tid] == Idle) {
1350 template<class Impl>
1352 DefaultFetch<Impl>::roundRobin()
1354 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1355 std::list<unsigned>::iterator end = priorityList.end();
1359 while (pri_iter != end) {
1360 high_pri = *pri_iter;
1362 assert(high_pri <= numThreads);
1364 if (fetchStatus[high_pri] == Running ||
1365 fetchStatus[high_pri] == IcacheAccessComplete ||
1366 fetchStatus[high_pri] == Idle) {
1368 priorityList.erase(pri_iter);
1369 priorityList.push_back(high_pri);
1380 template<class Impl>
1382 DefaultFetch<Impl>::iqCount()
1384 std::priority_queue<unsigned> PQ;
1386 std::list<unsigned>::iterator threads = activeThreads->begin();
1387 std::list<unsigned>::iterator end = activeThreads->end();
1389 while (threads != end) {
1390 unsigned tid = *threads++;
1392 PQ.push(fromIEW->iewInfo[tid].iqCount);
1395 while (!PQ.empty()) {
1397 unsigned high_pri = PQ.top();
1399 if (fetchStatus[high_pri] == Running ||
1400 fetchStatus[high_pri] == IcacheAccessComplete ||
1401 fetchStatus[high_pri] == Idle)
1411 template<class Impl>
1413 DefaultFetch<Impl>::lsqCount()
1415 std::priority_queue<unsigned> PQ;
1417 std::list<unsigned>::iterator threads = activeThreads->begin();
1418 std::list<unsigned>::iterator end = activeThreads->end();
1420 while (threads != end) {
1421 unsigned tid = *threads++;
1423 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1426 while (!PQ.empty()) {
1428 unsigned high_pri = PQ.top();
1430 if (fetchStatus[high_pri] == Running ||
1431 fetchStatus[high_pri] == IcacheAccessComplete ||
1432 fetchStatus[high_pri] == Idle)
1442 template<class Impl>
1444 DefaultFetch<Impl>::branchCount()
1446 std::list<unsigned>::iterator thread = activeThreads->begin();
1447 assert(thread != activeThreads->end());
1448 unsigned tid = *thread;
1450 panic("Branch Count Fetch policy unimplemented\n");