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 "base/remote_gdb.hh"
49 #include "sim/system.hh"
56 DefaultFetch<Impl>::IcachePort::recvAtomic(PacketPtr pkt)
58 panic("DefaultFetch doesn't expect recvAtomic callback!");
64 DefaultFetch<Impl>::IcachePort::recvFunctional(PacketPtr pkt)
66 warn("Default fetch doesn't update it's state from a functional call.");
71 DefaultFetch<Impl>::IcachePort::recvStatusChange(Status status)
73 if (status == RangeChange)
76 panic("DefaultFetch doesn't expect recvStatusChange callback!");
81 DefaultFetch<Impl>::IcachePort::recvTiming(PacketPtr pkt)
83 if (pkt->isResponse()) {
84 fetch->processCacheCompletion(pkt);
86 //else Snooped a coherence request, just return
92 DefaultFetch<Impl>::IcachePort::recvRetry()
98 DefaultFetch<Impl>::DefaultFetch(Params *params)
100 decodeToFetchDelay(params->decodeToFetchDelay),
101 renameToFetchDelay(params->renameToFetchDelay),
102 iewToFetchDelay(params->iewToFetchDelay),
103 commitToFetchDelay(params->commitToFetchDelay),
104 fetchWidth(params->fetchWidth),
108 numThreads(params->numberOfThreads),
109 numFetchingThreads(params->smtNumFetchingThreads),
110 interruptPending(false),
114 if (numThreads > Impl::MaxThreads)
115 fatal("numThreads is not a valid value\n");
117 // Set fetch stage's status to inactive.
120 std::string policy = params->smtFetchPolicy;
122 // Convert string to lowercase
123 std::transform(policy.begin(), policy.end(), policy.begin(),
124 (int(*)(int)) tolower);
126 // Figure out fetch policy
127 if (policy == "singlethread") {
128 fetchPolicy = SingleThread;
130 panic("Invalid Fetch Policy for a SMT workload.");
131 } else if (policy == "roundrobin") {
132 fetchPolicy = RoundRobin;
133 DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
134 } else if (policy == "branch") {
135 fetchPolicy = Branch;
136 DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
137 } else if (policy == "iqcount") {
139 DPRINTF(Fetch, "Fetch policy set to IQ count\n");
140 } else if (policy == "lsqcount") {
142 DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
144 fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
145 " RoundRobin,LSQcount,IQcount}\n");
148 // Size of cache block.
151 // Create mask to get rid of offset bits.
152 cacheBlkMask = (cacheBlkSize - 1);
154 for (int tid=0; tid < numThreads; tid++) {
156 fetchStatus[tid] = Running;
158 priorityList.push_back(tid);
162 // Create space to store a cache line.
163 cacheData[tid] = new uint8_t[cacheBlkSize];
164 cacheDataPC[tid] = 0;
165 cacheDataValid[tid] = false;
167 delaySlotInfo[tid].branchSeqNum = -1;
168 delaySlotInfo[tid].numInsts = 0;
169 delaySlotInfo[tid].targetAddr = 0;
170 delaySlotInfo[tid].targetReady = false;
172 stalls[tid].decode = false;
173 stalls[tid].rename = false;
174 stalls[tid].iew = false;
175 stalls[tid].commit = false;
178 // Get the size of an instruction.
179 instSize = sizeof(TheISA::MachInst);
182 template <class Impl>
184 DefaultFetch<Impl>::name() const
186 return cpu->name() + ".fetch";
189 template <class Impl>
191 DefaultFetch<Impl>::regStats()
194 .name(name() + ".icacheStallCycles")
195 .desc("Number of cycles fetch is stalled on an Icache miss")
196 .prereq(icacheStallCycles);
199 .name(name() + ".Insts")
200 .desc("Number of instructions fetch has processed")
201 .prereq(fetchedInsts);
204 .name(name() + ".Branches")
205 .desc("Number of branches that fetch encountered")
206 .prereq(fetchedBranches);
209 .name(name() + ".predictedBranches")
210 .desc("Number of branches that fetch has predicted taken")
211 .prereq(predictedBranches);
214 .name(name() + ".Cycles")
215 .desc("Number of cycles fetch has run and was not squashing or"
217 .prereq(fetchCycles);
220 .name(name() + ".SquashCycles")
221 .desc("Number of cycles fetch has spent squashing")
222 .prereq(fetchSquashCycles);
225 .name(name() + ".IdleCycles")
226 .desc("Number of cycles fetch was idle")
227 .prereq(fetchIdleCycles);
230 .name(name() + ".BlockedCycles")
231 .desc("Number of cycles fetch has spent blocked")
232 .prereq(fetchBlockedCycles);
235 .name(name() + ".CacheLines")
236 .desc("Number of cache lines fetched")
237 .prereq(fetchedCacheLines);
240 .name(name() + ".MiscStallCycles")
241 .desc("Number of cycles fetch has spent waiting on interrupts, or "
242 "bad addresses, or out of MSHRs")
243 .prereq(fetchMiscStallCycles);
246 .name(name() + ".IcacheSquashes")
247 .desc("Number of outstanding Icache misses that were squashed")
248 .prereq(fetchIcacheSquashes);
251 .init(/* base value */ 0,
252 /* last value */ fetchWidth,
254 .name(name() + ".rateDist")
255 .desc("Number of instructions fetched each cycle (Total)")
259 .name(name() + ".idleRate")
260 .desc("Percent of cycles fetch was idle")
262 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
265 .name(name() + ".branchRate")
266 .desc("Number of branch fetches per cycle")
267 .flags(Stats::total);
268 branchRate = fetchedBranches / cpu->numCycles;
271 .name(name() + ".rate")
272 .desc("Number of inst fetches per cycle")
273 .flags(Stats::total);
274 fetchRate = fetchedInsts / cpu->numCycles;
276 branchPred.regStats();
281 DefaultFetch<Impl>::setCPU(O3CPU *cpu_ptr)
283 DPRINTF(Fetch, "Setting the CPU pointer.\n");
286 // Name is finally available, so create the port.
287 icachePort = new IcachePort(this);
291 cpu->checker->setIcachePort(icachePort);
295 // Schedule fetch to get the correct PC from the CPU
296 // scheduleFetchStartupEvent(1);
298 // Fetch needs to start fetching instructions at the very beginning,
299 // so it must start up in active state.
305 DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
307 DPRINTF(Fetch, "Setting the time buffer pointer.\n");
308 timeBuffer = time_buffer;
310 // Create wires to get information from proper places in time buffer.
311 fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
312 fromRename = timeBuffer->getWire(-renameToFetchDelay);
313 fromIEW = timeBuffer->getWire(-iewToFetchDelay);
314 fromCommit = timeBuffer->getWire(-commitToFetchDelay);
319 DefaultFetch<Impl>::setActiveThreads(std::list<unsigned> *at_ptr)
321 DPRINTF(Fetch, "Setting active threads list pointer.\n");
322 activeThreads = at_ptr;
327 DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *fq_ptr)
329 DPRINTF(Fetch, "Setting the fetch queue pointer.\n");
332 // Create wire to write information to proper place in fetch queue.
333 toDecode = fetchQueue->getWire(0);
338 DefaultFetch<Impl>::initStage()
340 // Setup PC and nextPC with initial state.
341 for (int tid = 0; tid < numThreads; tid++) {
342 PC[tid] = cpu->readPC(tid);
343 nextPC[tid] = cpu->readNextPC(tid);
344 #if ISA_HAS_DELAY_SLOT
345 nextNPC[tid] = cpu->readNextNPC(tid);
352 DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
354 unsigned tid = pkt->req->getThreadNum();
356 DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n",tid);
358 // Only change the status if it's still waiting on the icache access
360 if (fetchStatus[tid] != IcacheWaitResponse ||
361 pkt->req != memReq[tid] ||
363 ++fetchIcacheSquashes;
369 memcpy(cacheData[tid], pkt->getPtr<uint8_t *>(), cacheBlkSize);
370 cacheDataValid[tid] = true;
373 // Wake up the CPU (if it went to sleep and was waiting on
374 // this completion event).
377 DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
383 // Only switch to IcacheAccessComplete if we're not stalled as well.
384 if (checkStall(tid)) {
385 fetchStatus[tid] = Blocked;
387 fetchStatus[tid] = IcacheAccessComplete;
390 // Reset the mem req to NULL.
396 template <class Impl>
398 DefaultFetch<Impl>::drain()
400 // Fetch is ready to drain at any time.
401 cpu->signalDrained();
406 template <class Impl>
408 DefaultFetch<Impl>::resume()
410 drainPending = false;
413 template <class Impl>
415 DefaultFetch<Impl>::switchOut()
418 // Branch predictor needs to have its state cleared.
419 branchPred.switchOut();
422 template <class Impl>
424 DefaultFetch<Impl>::takeOverFrom()
427 for (int i = 0; i < Impl::MaxThreads; ++i) {
428 stalls[i].decode = 0;
429 stalls[i].rename = 0;
431 stalls[i].commit = 0;
432 PC[i] = cpu->readPC(i);
433 nextPC[i] = cpu->readNextPC(i);
434 #if ISA_HAS_DELAY_SLOT
435 nextNPC[i] = cpu->readNextNPC(i);
436 delaySlotInfo[i].branchSeqNum = -1;
437 delaySlotInfo[i].numInsts = 0;
438 delaySlotInfo[i].targetAddr = 0;
439 delaySlotInfo[i].targetReady = false;
441 fetchStatus[i] = Running;
444 wroteToTimeBuffer = false;
447 interruptPending = false;
448 branchPred.takeOverFrom();
451 template <class Impl>
453 DefaultFetch<Impl>::wakeFromQuiesce()
455 DPRINTF(Fetch, "Waking up from quiesce\n");
456 // Hopefully this is safe
457 // @todo: Allow other threads to wake from quiesce.
458 fetchStatus[0] = Running;
461 template <class Impl>
463 DefaultFetch<Impl>::switchToActive()
465 if (_status == Inactive) {
466 DPRINTF(Activity, "Activating stage.\n");
468 cpu->activateStage(O3CPU::FetchIdx);
474 template <class Impl>
476 DefaultFetch<Impl>::switchToInactive()
478 if (_status == Active) {
479 DPRINTF(Activity, "Deactivating stage.\n");
481 cpu->deactivateStage(O3CPU::FetchIdx);
487 template <class Impl>
489 DefaultFetch<Impl>::lookupAndUpdateNextPC(DynInstPtr &inst, Addr &next_PC,
492 // Do branch prediction check here.
493 // A bit of a misnomer...next_PC is actually the current PC until
494 // this function updates it.
497 if (!inst->isControl()) {
498 #if ISA_HAS_DELAY_SLOT
499 Addr cur_PC = next_PC;
500 next_PC = cur_PC + instSize; //next_NPC;
501 next_NPC = cur_PC + (2 * instSize);//next_NPC + instSize;
502 inst->setPredTarg(next_NPC);
504 next_PC = next_PC + instSize;
505 inst->setPredTarg(next_PC);
510 int tid = inst->threadNumber;
511 #if ISA_HAS_DELAY_SLOT
512 Addr pred_PC = next_PC;
513 predict_taken = branchPred.predict(inst, pred_PC, tid);
516 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be true.\n", tid);
518 DPRINTF(Fetch, "[tid:%i]: Branch predicted to be false.\n", tid);
525 // Update delay slot info
526 ++delaySlotInfo[tid].numInsts;
527 delaySlotInfo[tid].targetAddr = pred_PC;
528 DPRINTF(Fetch, "[tid:%i]: %i delay slot inst(s) to process.\n", tid,
529 delaySlotInfo[tid].numInsts);
530 } else { // !predict_taken
531 if (inst->isCondDelaySlot()) {
533 // The delay slot is skipped here if there is on
537 // No need to declare a delay slot here since
538 // there is no for the pred. target to jump
541 next_NPC = next_NPC + instSize;
544 predict_taken = branchPred.predict(inst, next_PC, tid);
553 return predict_taken;
556 template <class Impl>
558 DefaultFetch<Impl>::fetchCacheLine(Addr fetch_PC, Fault &ret_fault, unsigned tid)
560 Fault fault = NoFault;
563 // Flag to say whether or not address is physical addr.
564 unsigned flags = cpu->inPalMode(fetch_PC) ? PHYSICAL : 0;
567 #endif // FULL_SYSTEM
569 if (cacheBlocked || isSwitchedOut() || (interruptPending && flags == 0)) {
570 // Hold off fetch from getting new instructions when:
571 // Cache is blocked, or
572 // while an interrupt is pending and we're not in PAL mode, or
573 // fetch is switched out.
577 // Align the fetch PC so it's at the start of a cache block.
578 fetch_PC = icacheBlockAlignPC(fetch_PC);
580 // If we've already got the block, no need to try to fetch it again.
581 if (cacheDataValid[tid] && fetch_PC == cacheDataPC[tid]) {
585 // Setup the memReq to do a read of the first instruction's address.
586 // Set the appropriate read size and flags as well.
587 // Build request here.
588 RequestPtr mem_req = new Request(tid, fetch_PC, cacheBlkSize, flags,
589 fetch_PC, cpu->readCpuId(), tid);
591 memReq[tid] = mem_req;
593 // Translate the instruction request.
594 fault = cpu->translateInstReq(mem_req, cpu->thread[tid]);
596 // In the case of faults, the fetch stage may need to stall and wait
597 // for the ITB miss to be handled.
599 // If translation was successful, attempt to read the first
601 if (fault == NoFault) {
603 if (cpu->system->memctrl->badaddr(memReq[tid]->paddr) ||
604 memReq[tid]->isUncacheable()) {
605 DPRINTF(Fetch, "Fetch: Bad address %#x (hopefully on a "
606 "misspeculating path)!",
608 ret_fault = TheISA::genMachineCheckFault();
613 // Build packet here.
614 PacketPtr data_pkt = new Packet(mem_req,
615 Packet::ReadReq, Packet::Broadcast);
616 data_pkt->dataDynamicArray(new uint8_t[cacheBlkSize]);
618 cacheDataPC[tid] = fetch_PC;
619 cacheDataValid[tid] = false;
621 DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
625 // Now do the timing access to see whether or not the instruction
626 // exists within the cache.
627 if (!icachePort->sendTiming(data_pkt)) {
628 if (data_pkt->result == Packet::BadAddress) {
629 fault = TheISA::genMachineCheckFault();
633 assert(retryPkt == NULL);
634 assert(retryTid == -1);
635 DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
636 fetchStatus[tid] = IcacheWaitRetry;
643 DPRINTF(Fetch, "[tid:%i]: Doing cache access.\n", tid);
645 lastIcacheStall[tid] = curTick;
647 DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
650 fetchStatus[tid] = IcacheWaitResponse;
660 template <class Impl>
662 DefaultFetch<Impl>::doSquash(const Addr &new_PC, unsigned tid)
664 DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %#x.\n",
668 nextPC[tid] = new_PC + instSize;
669 nextNPC[tid] = new_PC + (2 * instSize);
671 // Clear the icache miss if it's outstanding.
672 if (fetchStatus[tid] == IcacheWaitResponse) {
673 DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
678 // Get rid of the retrying packet if it was from this thread.
679 if (retryTid == tid) {
680 assert(cacheBlocked);
681 cacheBlocked = false;
683 delete retryPkt->req;
688 fetchStatus[tid] = Squashing;
695 DefaultFetch<Impl>::squashFromDecode(const Addr &new_PC,
696 const InstSeqNum &seq_num,
699 DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n",tid);
701 doSquash(new_PC, tid);
703 #if ISA_HAS_DELAY_SLOT
704 if (seq_num <= delaySlotInfo[tid].branchSeqNum) {
705 delaySlotInfo[tid].numInsts = 0;
706 delaySlotInfo[tid].targetAddr = 0;
707 delaySlotInfo[tid].targetReady = false;
711 // Tell the CPU to remove any instructions that are in flight between
713 cpu->removeInstsUntil(seq_num, tid);
718 DefaultFetch<Impl>::checkStall(unsigned tid) const
720 bool ret_val = false;
722 if (cpu->contextSwitch) {
723 DPRINTF(Fetch,"[tid:%i]: Stalling for a context switch.\n",tid);
725 } else if (stalls[tid].decode) {
726 DPRINTF(Fetch,"[tid:%i]: Stall from Decode stage detected.\n",tid);
728 } else if (stalls[tid].rename) {
729 DPRINTF(Fetch,"[tid:%i]: Stall from Rename stage detected.\n",tid);
731 } else if (stalls[tid].iew) {
732 DPRINTF(Fetch,"[tid:%i]: Stall from IEW stage detected.\n",tid);
734 } else if (stalls[tid].commit) {
735 DPRINTF(Fetch,"[tid:%i]: Stall from Commit stage detected.\n",tid);
743 typename DefaultFetch<Impl>::FetchStatus
744 DefaultFetch<Impl>::updateFetchStatus()
747 std::list<unsigned>::iterator threads = (*activeThreads).begin();
749 while (threads != (*activeThreads).end()) {
751 unsigned tid = *threads++;
753 if (fetchStatus[tid] == Running ||
754 fetchStatus[tid] == Squashing ||
755 fetchStatus[tid] == IcacheAccessComplete) {
757 if (_status == Inactive) {
758 DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
760 if (fetchStatus[tid] == IcacheAccessComplete) {
761 DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
765 cpu->activateStage(O3CPU::FetchIdx);
772 // Stage is switching from active to inactive, notify CPU of it.
773 if (_status == Active) {
774 DPRINTF(Activity, "Deactivating stage.\n");
776 cpu->deactivateStage(O3CPU::FetchIdx);
782 template <class Impl>
784 DefaultFetch<Impl>::squash(const Addr &new_PC, 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, tid);
791 #if ISA_HAS_DELAY_SLOT
792 if (seq_num <= delaySlotInfo[tid].branchSeqNum) {
793 delaySlotInfo[tid].numInsts = 0;
794 delaySlotInfo[tid].targetAddr = 0;
795 delaySlotInfo[tid].targetReady = false;
798 // Tell the CPU to remove any instructions that are not in the ROB.
799 cpu->removeInstsNotInROB(tid, squash_delay_slot, seq_num);
801 // Tell the CPU to remove any instructions that are not in the ROB.
802 cpu->removeInstsNotInROB(tid, true, 0);
806 template <class Impl>
808 DefaultFetch<Impl>::tick()
810 std::list<unsigned>::iterator threads = (*activeThreads).begin();
811 bool status_change = false;
813 wroteToTimeBuffer = false;
815 while (threads != (*activeThreads).end()) {
816 unsigned tid = *threads++;
818 // Check the signals for each thread to determine the proper status
820 bool updated_status = checkSignalsAndUpdate(tid);
821 status_change = status_change || updated_status;
824 DPRINTF(Fetch, "Running stage.\n");
826 // Reset the number of the instruction we're fetching.
830 if (fromCommit->commitInfo[0].interruptPending) {
831 interruptPending = true;
834 if (fromCommit->commitInfo[0].clearInterrupt) {
835 interruptPending = false;
839 for (threadFetched = 0; threadFetched < numFetchingThreads;
841 // Fetch each of the actively fetching threads.
842 fetch(status_change);
845 // Record number of instructions fetched this cycle for distribution.
846 fetchNisnDist.sample(numInst);
849 // Change the fetch stage status if there was a status change.
850 _status = updateFetchStatus();
853 // If there was activity this cycle, inform the CPU of it.
854 if (wroteToTimeBuffer || cpu->contextSwitch) {
855 DPRINTF(Activity, "Activity this cycle.\n");
857 cpu->activityThisCycle();
861 template <class Impl>
863 DefaultFetch<Impl>::checkSignalsAndUpdate(unsigned tid)
865 // Update the per thread stall statuses.
866 if (fromDecode->decodeBlock[tid]) {
867 stalls[tid].decode = true;
870 if (fromDecode->decodeUnblock[tid]) {
871 assert(stalls[tid].decode);
872 assert(!fromDecode->decodeBlock[tid]);
873 stalls[tid].decode = false;
876 if (fromRename->renameBlock[tid]) {
877 stalls[tid].rename = true;
880 if (fromRename->renameUnblock[tid]) {
881 assert(stalls[tid].rename);
882 assert(!fromRename->renameBlock[tid]);
883 stalls[tid].rename = false;
886 if (fromIEW->iewBlock[tid]) {
887 stalls[tid].iew = true;
890 if (fromIEW->iewUnblock[tid]) {
891 assert(stalls[tid].iew);
892 assert(!fromIEW->iewBlock[tid]);
893 stalls[tid].iew = false;
896 if (fromCommit->commitBlock[tid]) {
897 stalls[tid].commit = true;
900 if (fromCommit->commitUnblock[tid]) {
901 assert(stalls[tid].commit);
902 assert(!fromCommit->commitBlock[tid]);
903 stalls[tid].commit = false;
906 // Check squash signals from commit.
907 if (fromCommit->commitInfo[tid].squash) {
909 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
910 "from commit.\n",tid);
912 #if ISA_HAS_DELAY_SLOT
913 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].bdelayDoneSeqNum;
915 InstSeqNum doneSeqNum = fromCommit->commitInfo[tid].doneSeqNum;
917 // In any case, squash.
918 squash(fromCommit->commitInfo[tid].nextPC,
920 fromCommit->commitInfo[tid].squashDelaySlot,
923 // Also check if there's a mispredict that happened.
924 if (fromCommit->commitInfo[tid].branchMispredict) {
925 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
926 fromCommit->commitInfo[tid].nextPC,
927 fromCommit->commitInfo[tid].branchTaken,
930 branchPred.squash(fromCommit->commitInfo[tid].doneSeqNum,
935 } else if (fromCommit->commitInfo[tid].doneSeqNum) {
936 // Update the branch predictor if it wasn't a squashed instruction
937 // that was broadcasted.
938 branchPred.update(fromCommit->commitInfo[tid].doneSeqNum, tid);
941 // Check ROB squash signals from commit.
942 if (fromCommit->commitInfo[tid].robSquashing) {
943 DPRINTF(Fetch, "[tid:%u]: ROB is still squashing.\n", tid);
945 // Continue to squash.
946 fetchStatus[tid] = Squashing;
951 // Check squash signals from decode.
952 if (fromDecode->decodeInfo[tid].squash) {
953 DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
954 "from decode.\n",tid);
956 // Update the branch predictor.
957 if (fromDecode->decodeInfo[tid].branchMispredict) {
958 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
959 fromDecode->decodeInfo[tid].nextPC,
960 fromDecode->decodeInfo[tid].branchTaken,
963 branchPred.squash(fromDecode->decodeInfo[tid].doneSeqNum,
967 if (fetchStatus[tid] != Squashing) {
969 #if ISA_HAS_DELAY_SLOT
970 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].bdelayDoneSeqNum;
972 InstSeqNum doneSeqNum = fromDecode->decodeInfo[tid].doneSeqNum;
974 // Squash unless we're already squashing
975 squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
983 if (checkStall(tid) && fetchStatus[tid] != IcacheWaitResponse) {
984 DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
986 fetchStatus[tid] = Blocked;
991 if (fetchStatus[tid] == Blocked ||
992 fetchStatus[tid] == Squashing) {
993 // Switch status to running if fetch isn't being told to block or
994 // squash this cycle.
995 DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
998 fetchStatus[tid] = Running;
1003 // If we've reached this point, we have not gotten any signals that
1004 // cause fetch to change its status. Fetch remains the same as before.
1008 template<class Impl>
1010 DefaultFetch<Impl>::fetch(bool &status_change)
1012 //////////////////////////////////////////
1013 // Start actual fetch
1014 //////////////////////////////////////////
1015 int tid = getFetchingThread(fetchPolicy);
1017 if (tid == -1 || drainPending) {
1018 DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
1020 // Breaks looping condition in tick()
1021 threadFetched = numFetchingThreads;
1025 DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
1028 Addr &fetch_PC = PC[tid];
1030 // Fault code for memory access.
1031 Fault fault = NoFault;
1033 // If returning from the delay of a cache miss, then update the status
1034 // to running, otherwise do the cache access. Possibly move this up
1035 // to tick() function.
1036 if (fetchStatus[tid] == IcacheAccessComplete) {
1037 DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n",
1040 fetchStatus[tid] = Running;
1041 status_change = true;
1042 } else if (fetchStatus[tid] == Running) {
1043 DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
1044 "instruction, starting at PC %08p.\n",
1047 bool fetch_success = fetchCacheLine(fetch_PC, fault, tid);
1048 if (!fetch_success) {
1050 ++icacheStallCycles;
1052 ++fetchMiscStallCycles;
1057 if (fetchStatus[tid] == Idle) {
1059 } else if (fetchStatus[tid] == Blocked) {
1060 ++fetchBlockedCycles;
1061 } else if (fetchStatus[tid] == Squashing) {
1062 ++fetchSquashCycles;
1063 } else if (fetchStatus[tid] == IcacheWaitResponse) {
1064 ++icacheStallCycles;
1067 // Status is Idle, Squashing, Blocked, or IcacheWaitResponse, so
1068 // fetch should do nothing.
1074 // If we had a stall due to an icache miss, then return.
1075 if (fetchStatus[tid] == IcacheWaitResponse) {
1076 ++icacheStallCycles;
1077 status_change = true;
1081 Addr next_PC = fetch_PC;
1082 Addr next_NPC = next_PC + instSize;
1083 InstSeqNum inst_seq;
1085 ExtMachInst ext_inst;
1086 // @todo: Fix this hack.
1087 unsigned offset = (fetch_PC & cacheBlkMask) & ~3;
1089 if (fault == NoFault) {
1090 // If the read of the first instruction was successful, then grab the
1091 // instructions from the rest of the cache line and put them into the
1092 // queue heading to decode.
1094 DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
1097 // Need to keep track of whether or not a predicted branch
1098 // ended this fetch block.
1099 bool predicted_branch = false;
1101 // Need to keep track of whether or not a delay slot
1102 // instruction has been fetched
1105 offset < cacheBlkSize &&
1106 numInst < fetchWidth &&
1107 (!predicted_branch || delaySlotInfo[tid].numInsts > 0);
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());
1126 // Create a new DynInst from the instruction fetched.
1127 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1130 instruction->setTid(tid);
1132 instruction->setASID(tid);
1134 instruction->setThreadState(cpu->thread[tid]);
1136 DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x created "
1138 tid, instruction->readPC(), inst_seq);
1140 DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n",
1141 tid, instruction->staticInst->disassemble(fetch_PC));
1143 instruction->traceData =
1144 Trace::getInstRecord(curTick, cpu->tcBase(tid),
1145 instruction->staticInst,
1146 instruction->readPC());
1148 predicted_branch = lookupAndUpdateNextPC(instruction, next_PC,
1151 // Add instruction to the CPU's list of instructions.
1152 instruction->setInstListIt(cpu->addInst(instruction));
1154 // Write the instruction to the first slot in the queue
1155 // that heads to decode.
1156 toDecode->insts[numInst] = instruction;
1160 // Increment stat of fetched instructions.
1163 // Move to the next instruction, unless we have a branch.
1166 if (instruction->isQuiesce()) {
1167 // warn("%lli: Quiesce instruction encountered, halting fetch!",
1169 fetchStatus[tid] = QuiescePending;
1171 status_change = true;
1177 #if ISA_HAS_DELAY_SLOT
1178 if (predicted_branch) {
1179 delaySlotInfo[tid].branchSeqNum = inst_seq;
1181 DPRINTF(Fetch, "[tid:%i]: Delay slot branch set to [sn:%i]\n",
1184 } else if (delaySlotInfo[tid].numInsts > 0) {
1185 --delaySlotInfo[tid].numInsts;
1187 // It's OK to set PC to target of branch
1188 if (delaySlotInfo[tid].numInsts == 0) {
1189 delaySlotInfo[tid].targetReady = true;
1191 // Break the looping condition
1192 predicted_branch = true;
1195 DPRINTF(Fetch, "[tid:%i]: %i delay slot inst(s) left to"
1196 " process.\n", tid, delaySlotInfo[tid].numInsts);
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 && delaySlotInfo[tid].numInsts <= 0) {
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) {
1220 #if ISA_HAS_DELAY_SLOT
1221 if (delaySlotInfo[tid].targetReady &&
1222 delaySlotInfo[tid].numInsts == 0) {
1224 PC[tid] = delaySlotInfo[tid].targetAddr; //next_PC
1225 nextPC[tid] = next_PC + instSize; //next_NPC
1226 nextNPC[tid] = next_PC + (2 * instSize);
1228 delaySlotInfo[tid].targetReady = false;
1231 nextPC[tid] = next_NPC;
1232 nextNPC[tid] = next_NPC + instSize;
1235 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]);
1237 DPRINTF(Fetch, "[tid:%i]: Setting PC to %08p.\n",tid, next_PC);
1239 nextPC[tid] = next_PC + instSize;
1242 // We shouldn't be in an icache miss and also have a fault (an ITB
1244 if (fetchStatus[tid] == IcacheWaitResponse) {
1245 panic("Fetch should have exited prior to this!");
1248 // Send the fault to commit. This thread will not do anything
1249 // until commit handles the fault. The only other way it can
1250 // wake up is if a squash comes along and changes the PC.
1252 assert(numInst != fetchWidth);
1253 // Get a sequence number.
1254 inst_seq = cpu->getAndIncrementInstSeq();
1255 // We will use a nop in order to carry the fault.
1256 ext_inst = TheISA::NoopMachInst;
1258 // Create a new DynInst from the dummy nop.
1259 DynInstPtr instruction = new DynInst(ext_inst, fetch_PC,
1262 instruction->setPredTarg(next_PC + instSize);
1263 instruction->setTid(tid);
1265 instruction->setASID(tid);
1267 instruction->setThreadState(cpu->thread[tid]);
1269 instruction->traceData = NULL;
1271 instruction->setInstListIt(cpu->addInst(instruction));
1273 instruction->fault = fault;
1275 toDecode->insts[numInst] = instruction;
1278 DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n",tid);
1280 fetchStatus[tid] = TrapPending;
1281 status_change = true;
1283 // warn("%lli fault (%d) detected @ PC %08p", curTick, fault, PC[tid]);
1284 #else // !FULL_SYSTEM
1285 warn("cycle %lli: fault (%s) detected @ PC %08p", curTick, fault->name(), PC[tid]);
1286 #endif // FULL_SYSTEM
1290 template<class Impl>
1292 DefaultFetch<Impl>::recvRetry()
1294 if (retryPkt != NULL) {
1295 assert(cacheBlocked);
1296 assert(retryTid != -1);
1297 assert(fetchStatus[retryTid] == IcacheWaitRetry);
1299 if (icachePort->sendTiming(retryPkt)) {
1300 fetchStatus[retryTid] = IcacheWaitResponse;
1303 cacheBlocked = false;
1306 assert(retryTid == -1);
1307 // Access has been squashed since it was sent out. Just clear
1308 // the cache being blocked.
1309 cacheBlocked = false;
1313 ///////////////////////////////////////
1315 // SMT FETCH POLICY MAINTAINED HERE //
1317 ///////////////////////////////////////
1318 template<class Impl>
1320 DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
1322 if (numThreads > 1) {
1323 switch (fetch_priority) {
1329 return roundRobin();
1338 return branchCount();
1344 int tid = *((*activeThreads).begin());
1346 if (fetchStatus[tid] == Running ||
1347 fetchStatus[tid] == IcacheAccessComplete ||
1348 fetchStatus[tid] == Idle) {
1358 template<class Impl>
1360 DefaultFetch<Impl>::roundRobin()
1362 std::list<unsigned>::iterator pri_iter = priorityList.begin();
1363 std::list<unsigned>::iterator end = priorityList.end();
1367 while (pri_iter != end) {
1368 high_pri = *pri_iter;
1370 assert(high_pri <= numThreads);
1372 if (fetchStatus[high_pri] == Running ||
1373 fetchStatus[high_pri] == IcacheAccessComplete ||
1374 fetchStatus[high_pri] == Idle) {
1376 priorityList.erase(pri_iter);
1377 priorityList.push_back(high_pri);
1388 template<class Impl>
1390 DefaultFetch<Impl>::iqCount()
1392 std::priority_queue<unsigned> PQ;
1394 std::list<unsigned>::iterator threads = (*activeThreads).begin();
1396 while (threads != (*activeThreads).end()) {
1397 unsigned tid = *threads++;
1399 PQ.push(fromIEW->iewInfo[tid].iqCount);
1402 while (!PQ.empty()) {
1404 unsigned high_pri = PQ.top();
1406 if (fetchStatus[high_pri] == Running ||
1407 fetchStatus[high_pri] == IcacheAccessComplete ||
1408 fetchStatus[high_pri] == Idle)
1418 template<class Impl>
1420 DefaultFetch<Impl>::lsqCount()
1422 std::priority_queue<unsigned> PQ;
1425 std::list<unsigned>::iterator threads = (*activeThreads).begin();
1427 while (threads != (*activeThreads).end()) {
1428 unsigned tid = *threads++;
1430 PQ.push(fromIEW->iewInfo[tid].ldstqCount);
1433 while (!PQ.empty()) {
1435 unsigned high_pri = PQ.top();
1437 if (fetchStatus[high_pri] == Running ||
1438 fetchStatus[high_pri] == IcacheAccessComplete ||
1439 fetchStatus[high_pri] == Idle)
1449 template<class Impl>
1451 DefaultFetch<Impl>::branchCount()
1453 std::list<unsigned>::iterator threads = (*activeThreads).begin();
1454 panic("Branch Count Fetch policy unimplemented\n");