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/root.hh"
46 #include "arch/tlb.hh"
47 #include "arch/vtophys.hh"
48 #include "sim/system.hh"
55 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
57 panic("DefaultFetch doesn't expect recvAtomic callback!");
63 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
65 DPRINTF(Fetch, "DefaultFetch doesn't update its state from a "
71 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
73 if (status == RangeChange) {
74 if (!snoopRangeSent) {
75 snoopRangeSent = true;
76 sendStatusChange(Port::RangeChange);
81 panic("DefaultFetch doesn't expect recvStatusChange callback!");
86 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
88 DPRINTF(Fetch, "Received timing\n");
89 if (pkt->isResponse()) {
90 fetch->processCacheCompletion(pkt);
92 //else Snooped a coherence request, just return
98 DefaultFetch<Impl>::IcachePort::recvRetry()
104 DefaultFetch<Impl>::DefaultFetch(Params *params)
105 : branchPred(params),
106 decodeToFetchDelay(params->decodeToFetchDelay),
107 renameToFetchDelay(params->renameToFetchDelay),
108 iewToFetchDelay(params->iewToFetchDelay),
109 commitToFetchDelay(params->commitToFetchDelay),
110 fetchWidth(params->fetchWidth),
114 numThreads(params->numberOfThreads),
115 numFetchingThreads(params->smtNumFetchingThreads),
116 interruptPending(false),
120 if (numThreads > Impl::MaxThreads)
121 fatal("numThreads is not a valid value\n");
123 // Set fetch stage's status to inactive.
126 std::string policy = params->smtFetchPolicy;
128 // Convert string to lowercase
129 std::transform(policy.begin(), policy.end(), policy.begin(),
130 (int(*)(int)) tolower);
132 // Figure out fetch policy
133 if (policy == "singlethread") {
134 fetchPolicy = SingleThread;
136 panic("Invalid Fetch Policy for a SMT workload.");
137 } else if (policy == "roundrobin") {
138 fetchPolicy = RoundRobin;
139 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
140 } else if (policy == "branch") {
141 fetchPolicy = Branch;
142 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
143 } else if (policy == "iqcount") {
145 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
146 } else if (policy == "lsqcount") {
148 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
150 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
151 " RoundRobin,LSQcount,IQcount}\n");
154 // Get the size of an instruction.
155 instSize = sizeof(TheISA::MachInst);
158 template <class Impl>
160 DefaultFetch<Impl>::name() const
162 return cpu->name() + ".fetch";
165 template <class Impl>
167 DefaultFetch<Impl>::regStats()
170 .name(name() + ".icacheStallCycles")
171 .desc("Number of cycles fetch is stalled on an Icache miss")
172 .prereq(icacheStallCycles);
175 .name(name() + ".Insts")
176 .desc("Number of instructions fetch has processed")
177 .prereq(fetchedInsts);
180 .name(name() + ".Branches")
181 .desc("Number of branches that fetch encountered")
182 .prereq(fetchedBranches);
185 .name(name() + ".predictedBranches")
186 .desc("Number of branches that fetch has predicted taken")
187 .prereq(predictedBranches);
190 .name(name() + ".Cycles")
191 .desc("Number of cycles fetch has run and was not squashing or"
193 .prereq(fetchCycles);
196 .name(name() + ".SquashCycles")
197 .desc("Number of cycles fetch has spent squashing")
198 .prereq(fetchSquashCycles);
201 .name(name() + ".IdleCycles")
202 .desc("Number of cycles fetch was idle")
203 .prereq(fetchIdleCycles);
206 .name(name() + ".BlockedCycles")
207 .desc("Number of cycles fetch has spent blocked")
208 .prereq(fetchBlockedCycles);
211 .name(name() + ".CacheLines")
212 .desc("Number of cache lines fetched")
213 .prereq(fetchedCacheLines);
216 .name(name() + ".MiscStallCycles")
217 .desc("Number of cycles fetch has spent waiting on interrupts, or "
218 "bad addresses, or out of MSHRs")
219 .prereq(fetchMiscStallCycles);
222 .name(name() + ".IcacheSquashes")
223 .desc("Number of outstanding Icache misses that were squashed")
224 .prereq(fetchIcacheSquashes);
227 .init(/* base value */ 0,
228 /* last value */ fetchWidth,
230 .name(name() + ".rateDist")
231 .desc("Number of instructions fetched each cycle (Total)")
235 .name(name() + ".idleRate")
236 .desc("Percent of cycles fetch was idle")
238 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
241 .name(name() + ".branchRate")
242 .desc("Number of branch fetches per cycle")
243 .flags(Stats::total);
244 branchRate = fetchedBranches / cpu->numCycles;
247 .name(name() + ".rate")
248 .desc("Number of inst fetches per cycle")
249 .flags(Stats::total);
250 fetchRate = fetchedInsts / cpu->numCycles;
252 branchPred.regStats();
257 DefaultFetch<Impl>::setCPU(O3CPU *cpu_ptr)
259 DPRINTF(Fetch, "Setting the CPU pointer.\n");
262 // Name is finally available, so create the port.
263 icachePort = new IcachePort(this);
265 icachePort->snoopRangeSent = false;
269 cpu->checker->setIcachePort(icachePort);
273 // Schedule fetch to get the correct PC from the CPU
274 // scheduleFetchStartupEvent(1);
276 // Fetch needs to start fetching instructions at the very beginning,
277 // so it must start up in active state.
283 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
285 DPRINTF(Fetch, "Setting the time buffer pointer.\n");
286 timeBuffer = time_buffer;
288 // Create wires to get information from proper places in time buffer.
289 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
290 fromRename = timeBuffer->getWire(-renameToFetchDelay);
291 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
292 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
297 DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
299 DPRINTF(Fetch, "Setting active threads list pointer.\n");
300 activeThreads = at_ptr;
305 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
307 DPRINTF(Fetch, "Setting the fetch queue pointer.\n");
310 // Create wire to write information to proper place in fetch queue.
311 toDecode = fetchQueue->getWire(0);
316 DefaultFetch<Impl>::initStage()
318 // Setup PC and nextPC with initial state.
319 for (int tid = 0; tid < numThreads; tid++) {
320 PC[tid] = cpu->readPC(tid);
321 nextPC[tid] = cpu->readNextPC(tid);
322 nextNPC[tid] = cpu->readNextNPC(tid);
325 // Size of cache block.
326 cacheBlkSize = icachePort->peerBlockSize();
328 // Create mask to get rid of offset bits.
329 cacheBlkMask = (cacheBlkSize - 1);
331 for (int tid=0; tid < numThreads; tid++) {
333 fetchStatus[tid] = Running;
335 priorityList.push_back(tid);
339 // Create space to store a cache line.
340 cacheData[tid] = new uint8_t[cacheBlkSize];
341 cacheDataPC[tid] = 0;
342 cacheDataValid[tid] = false;
344 stalls[tid].decode = false;
345 stalls[tid].rename = false;
346 stalls[tid].iew = false;
347 stalls[tid].commit = false;
353 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
355 unsigned tid = pkt->req->getThreadNum();
357 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
359 // Only change the status if it's still waiting on the icache access
361 if (fetchStatus[tid] != IcacheWaitResponse ||
362 pkt->req != memReq[tid] ||
364 ++fetchIcacheSquashes;
370 memcpy(cacheData[tid], pkt->getPtr<uint8_t *>(), cacheBlkSize);
371 cacheDataValid[tid] = true;
374 // Wake up the CPU (if it went to sleep and was waiting on
375 // this completion event).
378 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
384 // Only switch to IcacheAccessComplete if we're not stalled as well.
385 if (checkStall(tid)) {
386 fetchStatus[tid] = Blocked;
388 fetchStatus[tid] = IcacheAccessComplete;
391 // Reset the mem req to NULL.
397 template <class Impl>
399 DefaultFetch<Impl>::drain()
401 // Fetch is ready to drain at any time.
402 cpu->signalDrained();
407 template <class Impl>
409 DefaultFetch<Impl>::resume()
411 drainPending = false;
414 template <class Impl>
416 DefaultFetch<Impl>::switchOut()
419 // Branch predictor needs to have its state cleared.
420 branchPred.switchOut();
423 template <class Impl>
425 DefaultFetch<Impl>::takeOverFrom()
428 for (int i = 0; i < Impl::MaxThreads; ++i) {
429 stalls[i].decode = 0;
430 stalls[i].rename = 0;
432 stalls[i].commit = 0;
433 PC[i] = cpu->readPC(i);
434 nextPC[i] = cpu->readNextPC(i);
435 #if ISA_HAS_DELAY_SLOT
436 nextNPC[i] = cpu->readNextNPC(i);
438 nextNPC[i] = nextPC[i] + sizeof(TheISA::MachInst);
440 fetchStatus[i] = Running;
443 wroteToTimeBuffer = false;
446 interruptPending = false;
447 branchPred.takeOverFrom();
450 template <class Impl>
452 DefaultFetch<Impl>::wakeFromQuiesce()
454 DPRINTF(Fetch, "Waking up from quiesce\n");
455 // Hopefully this is safe
456 // @todo: Allow other threads to wake from quiesce.
457 fetchStatus[0] = Running;
460 template <class Impl>
462 DefaultFetch<Impl>::switchToActive()
464 if (_status == Inactive) {
465 DPRINTF(Activity, "Activating stage.\n");
467 cpu->activateStage(O3CPU::FetchIdx);
473 template <class Impl>
475 DefaultFetch<Impl>::switchToInactive()
477 if (_status == Active) {
478 DPRINTF(Activity, "Deactivating stage.\n");
480 cpu->deactivateStage(O3CPU::FetchIdx);
486 template <class Impl>
488 DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
491 // Do branch prediction check here.
492 // A bit of a misnomer...next_PC is actually the current PC until
493 // this function updates it.
496 if (!inst->isControl()) {
498 next_NPC = next_NPC + instSize;
499 inst->setPredTarg(next_PC, next_NPC);
500 inst->setPredTaken(false);
504 int tid = inst->threadNumber;
505 Addr pred_PC = next_PC;
506 predict_taken = branchPred.predict(inst, pred_PC, tid);
508 /* if (predict_taken) {
509 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be taken to %#x.\n",
512 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be not taken.\n", tid);
515 #if ISA_HAS_DELAY_SLOT
520 next_NPC += instSize;
526 next_NPC = next_PC + instSize;
528 /* DPRINTF(Fetch, "[tid:%i]: Branch predicted to go to %#x and then %#x.\n",
529 tid, next_PC, next_NPC);*/
530 inst->setPredTarg(next_PC, next_NPC);
531 inst->setPredTaken(predict_taken);
539 return predict_taken;
542 template <class Impl>
544 DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
546 Fault fault = NoFault;
550 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
553 } else if (isSwitchedOut()) {
554 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, switched out\n",
557 } else if (interruptPending && !(fetch_PC & 0x3)) {
558 // Hold off fetch from getting new instructions when:
559 // Cache is blocked, or
560 // while an interrupt is pending and we're not in PAL mode, or
561 // fetch is switched out.
562 DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
567 // Align the fetch PC so it's at the start of a cache block.
568 Addr block_PC = icacheBlockAlignPC(fetch_PC);
570 // If we've already got the block, no need to try to fetch it again.
571 if (cacheDataValid[tid] && block_PC == cacheDataPC[tid]) {
575 // Setup the memReq to do a read of the first instruction's address.
576 // Set the appropriate read size and flags as well.
577 // Build request here.
578 RequestPtr mem_req = new Request(tid, block_PC, cacheBlkSize, 0,
579 fetch_PC, cpu->readCpuId(), tid);
581 memReq[tid] = mem_req;
583 // Translate the instruction request.
584 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
586 // In the case of faults, the fetch stage may need to stall and wait
587 // for the ITB miss to be handled.
589 // If translation was successful, attempt to read the first
591 if (fault == NoFault) {
593 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
594 memReq[tid]->isUncacheable()) {
595 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
596 "misspeculating path)!",
598 ret_fault = TheISA::genMachineCheckFault();
603 // Build packet here.
604 PacketPtr data_pkt = new Packet(mem_req,
605 MemCmd::ReadReq, Packet::Broadcast);
606 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
608 cacheDataPC[tid] = block_PC;
609 cacheDataValid[tid] = false;
611 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
615 // Now do the timing access to see whether or not the instruction
616 // exists within the cache.
617 if (!icachePort->sendTiming(data_pkt)) {
618 if (data_pkt->result == Packet::BadAddress) {
619 fault = TheISA::genMachineCheckFault();
623 assert(retryPkt == NULL);
624 assert(retryTid == -1);
625 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
626 fetchStatus[tid] = IcacheWaitRetry;
633 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
635 lastIcacheStall[tid] = curTick;
637 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
640 fetchStatus[tid] = IcacheWaitResponse;
650 template <class Impl>
652 DefaultFetch<Impl>::doSquash(const Addr &new_PC,
653 const Addr &new_NPC, unsigned tid)
655 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x, NPC to: %#x.\n",
656 tid, new_PC, new_NPC);
659 nextPC[tid] = new_NPC;
660 nextNPC[tid] = new_NPC + instSize;
662 // Clear the icache miss if it's outstanding.
663 if (fetchStatus[tid] == IcacheWaitResponse) {
664 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
669 // Get rid of the retrying packet if it was from this thread.
670 if (retryTid == tid) {
671 assert(cacheBlocked);
672 cacheBlocked = false;
674 delete retryPkt->req;
679 fetchStatus[tid] = Squashing;
686 DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC, const Addr &new_NPC,
687 const InstSeqNum &seq_num,
690 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
692 doSquash(new_PC, new_NPC, tid);
694 // Tell the CPU to remove any instructions that are in flight between
696 cpu->removeInstsUntil(seq_num, tid);
701 DefaultFetch<Impl>::checkStall(unsigned tid) const
703 bool ret_val = false;
705 if (cpu->contextSwitch) {
706 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
708 } else if (stalls[tid].decode) {
709 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
711 } else if (stalls[tid].rename) {
712 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
714 } else if (stalls[tid].iew) {
715 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
717 } else if (stalls[tid].commit) {
718 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
726 typename DefaultFetch<Impl>::FetchStatus
727 DefaultFetch<Impl>::updateFetchStatus()
730 std::list<unsigned>::iterator threads = activeThreads->begin();
731 std::list<unsigned>::iterator end = activeThreads->end();
733 while (threads != end) {
734 unsigned tid = *threads++;
736 if (fetchStatus[tid] == Running ||
737 fetchStatus[tid] == Squashing ||
738 fetchStatus[tid] == IcacheAccessComplete) {
740 if (_status == Inactive) {
741 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
743 if (fetchStatus[tid] == IcacheAccessComplete) {
744 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
748 cpu->activateStage(O3CPU::FetchIdx);
755 // Stage is switching from active to inactive, notify CPU of it.
756 if (_status == Active) {
757 DPRINTF(Activity, "Deactivating stage.\n");
759 cpu->deactivateStage(O3CPU::FetchIdx);
765 template <class Impl>
767 DefaultFetch<Impl>::squash(const Addr &new_PC, const Addr &new_NPC,
768 const InstSeqNum &seq_num,
769 bool squash_delay_slot, unsigned tid)
771 DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n",tid);
773 doSquash(new_PC, new_NPC, tid);
775 #if ISA_HAS_DELAY_SLOT
776 // Tell the CPU to remove any instructions that are not in the ROB.
777 cpu->removeInstsNotInROB(tid, squash_delay_slot, seq_num);
779 // Tell the CPU to remove any instructions that are not in the ROB.
780 cpu->removeInstsNotInROB(tid, true, 0);
784 template <class Impl>
786 DefaultFetch<Impl>::tick()
788 std::list<unsigned>::iterator threads = activeThreads->begin();
789 std::list<unsigned>::iterator end = activeThreads->end();
790 bool status_change = false;
792 wroteToTimeBuffer = false;
794 while (threads != end) {
795 unsigned tid = *threads++;
797 // Check the signals for each thread to determine the proper status
799 bool updated_status = checkSignalsAndUpdate(tid);
800 status_change = status_change || updated_status;
803 DPRINTF(Fetch, "Running stage.\n");
805 // Reset the number of the instruction we're fetching.
809 if (fromCommit->commitInfo[0].interruptPending) {
810 interruptPending = true;
813 if (fromCommit->commitInfo[0].clearInterrupt) {
814 interruptPending = false;
818 for (threadFetched = 0; threadFetched < numFetchingThreads;
820 // Fetch each of the actively fetching threads.
821 fetch(status_change);
824 // Record number of instructions fetched this cycle for distribution.
825 fetchNisnDist.sample(numInst);
828 // Change the fetch stage status if there was a status change.
829 _status = updateFetchStatus();
832 // If there was activity this cycle, inform the CPU of it.
833 if (wroteToTimeBuffer || cpu->contextSwitch) {
834 DPRINTF(Activity, "Activity this cycle.\n");
836 cpu->activityThisCycle();
840 template <class Impl>
842 DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
844 // Update the per thread stall statuses.
845 if (fromDecode->decodeBlock[tid]) {
846 stalls[tid].decode = true;
849 if (fromDecode->decodeUnblock[tid]) {
850 assert(stalls[tid].decode);
851 assert(!fromDecode->decodeBlock[tid]);
852 stalls[tid].decode = false;
855 if (fromRename->renameBlock[tid]) {
856 stalls[tid].rename = true;
859 if (fromRename->renameUnblock[tid]) {
860 assert(stalls[tid].rename);
861 assert(!fromRename->renameBlock[tid]);
862 stalls[tid].rename = false;
865 if (fromIEW->iewBlock[tid]) {
866 stalls[tid].iew = true;
869 if (fromIEW->iewUnblock[tid]) {
870 assert(stalls[tid].iew);
871 assert(!fromIEW->iewBlock[tid]);
872 stalls[tid].iew = false;
875 if (fromCommit->commitBlock[tid]) {
876 stalls[tid].commit = true;
879 if (fromCommit->commitUnblock[tid]) {
880 assert(stalls[tid].commit);
881 assert(!fromCommit->commitBlock[tid]);
882 stalls[tid].commit = false;
885 // Check squash signals from commit.
886 if (fromCommit->commitInfo[tid].squash) {
888 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
889 "from commit.\n",tid);
891 #if ISA_HAS_DELAY_SLOT
892 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
894 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].doneSeqNum;
896 // In any case, squash.
897 squash(fromCommit->commitInfo[tid].nextPC,
898 fromCommit->commitInfo[tid].nextNPC,
900 fromCommit->commitInfo[tid].squashDelaySlot,
903 // Also check if there's a mispredict that happened.
904 if (fromCommit->commitInfo[tid].branchMispredict) {
905 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
906 fromCommit->commitInfo[tid].nextPC,
907 fromCommit->commitInfo[tid].branchTaken,
910 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
915 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
916 // Update the branch predictor if it wasn't a squashed instruction
917 // that was broadcasted.
918 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
921 // Check ROB squash signals from commit.
922 if (fromCommit->commitInfo[tid].robSquashing) {
923 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
925 // Continue to squash.
926 fetchStatus[tid] = Squashing;
931 // Check squash signals from decode.
932 if (fromDecode->decodeInfo[tid].squash) {
933 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
934 "from decode.\n",tid);
936 // Update the branch predictor.
937 if (fromDecode->decodeInfo[tid].branchMispredict) {
938 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
939 fromDecode->decodeInfo[tid].nextPC,
940 fromDecode->decodeInfo[tid].branchTaken,
943 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
947 if (fetchStatus[tid] != Squashing) {
949 #if ISA_HAS_DELAY_SLOT
950 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].bdelayDoneSeqNum;
952 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].doneSeqNum;
954 DPRINTF(Fetch, "Squashing from decode with PC = %#x, NPC = %#x\n",
955 fromDecode->decodeInfo[tid].nextPC,
956 fromDecode->decodeInfo[tid].nextNPC);
957 // Squash unless we're already squashing
958 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
959 fromDecode->decodeInfo[tid].nextNPC,
967 if (checkStall(tid) &&
968 fetchStatus[tid] != IcacheWaitResponse &&
969 fetchStatus[tid] != IcacheWaitRetry) {
970 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
972 fetchStatus[tid] = Blocked;
977 if (fetchStatus[tid] == Blocked ||
978 fetchStatus[tid] == Squashing) {
979 // Switch status to running if fetch isn't being told to block or
980 // squash this cycle.
981 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
984 fetchStatus[tid] = Running;
989 // If we've reached this point, we have not gotten any signals that
990 // cause fetch to change its status. Fetch remains the same as before.
996 DefaultFetch<Impl>::fetch(bool &status_change)
998 //////////////////////////////////////////
999 // Start actual fetch
1000 //////////////////////////////////////////
1001 int tid = getFetchingThread(fetchPolicy);
1003 if (tid == -1 || drainPending) {
1004 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1006 // Breaks looping condition in tick()
1007 threadFetched = numFetchingThreads;
1011 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1014 Addr &fetch_PC = PC[tid];
1016 Addr &fetch_NPC = nextPC[tid];
1018 // Fault code for memory access.
1019 Fault fault = NoFault;
1021 // If returning from the delay of a cache miss, then update the status
1022 // to running, otherwise do the cache access. Possibly move this up
1023 // to tick() function.
1024 if (fetchStatus[tid] == IcacheAccessComplete) {
1025 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1028 fetchStatus[tid] = Running;
1029 status_change = true;
1030 } else if (fetchStatus[tid] == Running) {
1031 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1032 "instruction, starting at PC %08p.\n",
1035 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1036 if (!fetch_success) {
1038 ++icacheStallCycles;
1040 ++fetchMiscStallCycles;
1045 if (fetchStatus[tid] == Idle) {
1047 DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
1048 } else if (fetchStatus[tid] == Blocked) {
1049 ++fetchBlockedCycles;
1050 DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
1051 } else if (fetchStatus[tid] == Squashing) {
1052 ++fetchSquashCycles;
1053 DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
1054 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1055 ++icacheStallCycles;
1056 DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n", tid);
1059 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1060 // fetch should do nothing.
1066 // If we had a stall due to an icache miss, then return.
1067 if (fetchStatus[tid] == IcacheWaitResponse) {
1068 ++icacheStallCycles;
1069 status_change = true;
1073 Addr next_PC = fetch_PC;
1074 Addr next_NPC = fetch_NPC;
1076 InstSeqNum inst_seq;
1078 ExtMachInst ext_inst;
1079 // @todo: Fix this hack.
1080 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1082 if (fault == NoFault) {
1083 // If the read of the first instruction was successful, then grab the
1084 // instructions from the rest of the cache line and put them into the
1085 // queue heading to decode.
1087 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1090 // Need to keep track of whether or not a predicted branch
1091 // ended this fetch block.
1092 bool predicted_branch = false;
1095 offset < cacheBlkSize &&
1096 numInst < fetchWidth &&
1100 // If we're branching after this instruction, quite fetching
1101 // from the same block then.
1103 (fetch_PC + sizeof(TheISA::MachInst) != fetch_NPC);
1104 if (predicted_branch) {
1105 DPRINTF(Fetch, "Branch detected with PC = %#x, NPC = %#x\n",
1106 fetch_PC, fetch_NPC);
1110 // Get a sequence number.
1111 inst_seq = cpu->getAndIncrementInstSeq();
1113 // Make sure this is a valid index.
1114 assert(offset <= cacheBlkSize - instSize);
1116 // Get the instruction from the array of the cache line.
1117 inst = TheISA::gtoh(*reinterpret_cast<TheISA::MachInst *>
1118 (&cacheData[tid][offset]));
1120 #if THE_ISA == ALPHA_ISA
1121 ext_inst = TheISA::makeExtMI(inst, fetch_PC);
1122 #elif THE_ISA == SPARC_ISA
1123 ext_inst = TheISA::makeExtMI(inst, cpu->thread[tid]->getTC());
1124 #elif THE_ISA == MIPS_ISA
1125 ext_inst = TheISA::makeExtMI(inst, cpu->thread[tid]->getTC());
1128 // Create a new DynInst from the instruction fetched.
1129 DynInstPtr instruction = new DynInst(ext_inst,
1130 fetch_PC, fetch_NPC,
1133 instruction->setTid(tid);
1135 instruction->setASID(tid);
1137 instruction->setThreadState(cpu->thread[tid]);
1139 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1141 tid, instruction->readPC(), inst_seq);
1143 //DPRINTF(Fetch, "[tid:%i]: MachInst is %#x\n", tid, ext_inst);
1145 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1146 tid, instruction->staticInst->disassemble(fetch_PC));
1148 instruction->traceData =
1149 Trace::getInstRecord(curTick, cpu->tcBase(tid),
1150 instruction->staticInst,
1151 instruction->readPC());
1153 ///FIXME This needs to be more robust in dealing with delay slots
1154 #if !ISA_HAS_DELAY_SLOT
1157 lookupAndUpdateNextPC(instruction, next_PC, next_NPC);
1158 predicted_branch |= (next_PC != fetch_NPC);
1160 // Add instruction to the CPU's list of instructions.
1161 instruction->setInstListIt(cpu->addInst(instruction));
1163 // Write the instruction to the first slot in the queue
1164 // that heads to decode.
1165 toDecode->insts[numInst] = instruction;
1169 // Increment stat of fetched instructions.
1172 // Move to the next instruction, unless we have a branch.
1174 fetch_NPC = next_NPC;
1176 if (instruction->isQuiesce()) {
1177 DPRINTF(Fetch, "Quiesce instruction encountered, halting fetch!",
1179 fetchStatus[tid] = QuiescePending;
1181 status_change = true;
1188 if (offset >= cacheBlkSize) {
1189 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of cache "
1191 } else if (numInst >= fetchWidth) {
1192 DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
1193 "for this cycle.\n", tid);
1194 } else if (predicted_branch) {
1195 DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
1196 "instruction encountered.\n", tid);
1201 wroteToTimeBuffer = true;
1204 // Now that fetching is completed, update the PC to signify what the next
1206 if (fault == NoFault) {
1208 nextPC[tid] = next_NPC;
1209 nextNPC[tid] = next_NPC + instSize;
1210 #if ISA_HAS_DELAY_SLOT
1211 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]);
1213 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, next_PC);
1216 // We shouldn't be in an icache miss and also have a fault (an ITB
1218 if (fetchStatus[tid] == IcacheWaitResponse) {
1219 panic("Fetch should have exited prior to this!");
1222 // Send the fault to commit. This thread will not do anything
1223 // until commit handles the fault. The only other way it can
1224 // wake up is if a squash comes along and changes the PC.
1226 assert(numInst != fetchWidth);
1227 // Get a sequence number.
1228 inst_seq = cpu->getAndIncrementInstSeq();
1229 // We will use a nop in order to carry the fault.
1230 ext_inst = TheISA::NoopMachInst;
1232 // Create a new DynInst from the dummy nop.
1233 DynInstPtr instruction = new DynInst(ext_inst,
1234 fetch_PC, fetch_NPC,
1237 instruction->setPredTarg(next_PC, next_NPC);
1238 instruction->setTid(tid);
1240 instruction->setASID(tid);
1242 instruction->setThreadState(cpu->thread[tid]);
1244 instruction->traceData = NULL;
1246 instruction->setInstListIt(cpu->addInst(instruction));
1248 instruction->fault = fault;
1250 toDecode->insts[numInst] = instruction;
1253 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1255 fetchStatus[tid] = TrapPending;
1256 status_change = true;
1257 #else // !FULL_SYSTEM
1258 fetchStatus[tid] = TrapPending;
1259 status_change = true;
1261 #endif // FULL_SYSTEM
1262 DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %08p",
1263 tid, fault->name(), PC[tid]);
1267 template<class Impl>
1269 DefaultFetch<Impl>::recvRetry()
1271 if (retryPkt != NULL) {
1272 assert(cacheBlocked);
1273 assert(retryTid != -1);
1274 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1276 if (icachePort->sendTiming(retryPkt)) {
1277 fetchStatus[retryTid] = IcacheWaitResponse;
1280 cacheBlocked = false;
1283 assert(retryTid == -1);
1284 // Access has been squashed since it was sent out. Just clear
1285 // the cache being blocked.
1286 cacheBlocked = false;
1290 ///////////////////////////////////////
1292 // SMT FETCH POLICY MAINTAINED HERE //
1294 ///////////////////////////////////////
1295 template<class Impl>
1297 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1299 if (numThreads > 1) {
1300 switch (fetch_priority) {
1306 return roundRobin();
1315 return branchCount();
1321 std::list<unsigned>::iterator thread = activeThreads->begin();
1322 assert(thread != activeThreads->end());
1325 if (fetchStatus[tid] == Running ||
1326 fetchStatus[tid] == IcacheAccessComplete ||
1327 fetchStatus[tid] == Idle) {
1337 template<class Impl>
1339 DefaultFetch<Impl>::roundRobin()
1341 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1342 std::list<unsigned>::iterator end = priorityList.end();
1346 while (pri_iter != end) {
1347 high_pri = *pri_iter;
1349 assert(high_pri <= numThreads);
1351 if (fetchStatus[high_pri] == Running ||
1352 fetchStatus[high_pri] == IcacheAccessComplete ||
1353 fetchStatus[high_pri] == Idle) {
1355 priorityList.erase(pri_iter);
1356 priorityList.push_back(high_pri);
1367 template<class Impl>
1369 DefaultFetch<Impl>::iqCount()
1371 std::priority_queue<unsigned> PQ;
1373 std::list<unsigned>::iterator threads = activeThreads->begin();
1374 std::list<unsigned>::iterator end = activeThreads->end();
1376 while (threads != end) {
1377 unsigned tid = *threads++;
1379 PQ.push(fromIEW->iewInfo[tid].iqCount);
1382 while (!PQ.empty()) {
1384 unsigned high_pri = PQ.top();
1386 if (fetchStatus[high_pri] == Running ||
1387 fetchStatus[high_pri] == IcacheAccessComplete ||
1388 fetchStatus[high_pri] == Idle)
1398 template<class Impl>
1400 DefaultFetch<Impl>::lsqCount()
1402 std::priority_queue<unsigned> PQ;
1404 std::list<unsigned>::iterator threads = activeThreads->begin();
1405 std::list<unsigned>::iterator end = activeThreads->end();
1407 while (threads != end) {
1408 unsigned tid = *threads++;
1410 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1413 while (!PQ.empty()) {
1415 unsigned high_pri = PQ.top();
1417 if (fetchStatus[high_pri] == Running ||
1418 fetchStatus[high_pri] == IcacheAccessComplete ||
1419 fetchStatus[high_pri] == Idle)
1429 template<class Impl>
1431 DefaultFetch<Impl>::branchCount()
1433 std::list<unsigned>::iterator thread = activeThreads->begin();
1434 assert(thread != activeThreads->end());
1435 unsigned tid = *thread;
1437 panic("Branch Count Fetch policy unimplemented\n");