2 * Copyright (c) 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.
31 #include "arch/faults.hh"
32 #include "arch/isa_traits.hh"
33 #include "base/statistics.hh"
34 #include "cpu/thread_context.hh"
35 #include "cpu/exetrace.hh"
36 #include "cpu/ozone/front_end.hh"
37 #include "mem/mem_interface.hh"
39 using namespace TheISA;
42 FrontEnd<Impl>::FrontEnd(Params *params)
44 icacheInterface(params->icacheInterface),
46 maxInstBufferSize(params->maxInstBufferSize),
47 width(params->frontEndWidth),
48 freeRegs(params->numPhysicalRegs),
49 numPhysRegs(params->numPhysicalRegs),
51 interruptPending(false)
58 // Size of cache block.
59 cacheBlkSize = icacheInterface ? icacheInterface->getBlockSize() : 64;
61 assert(isPowerOf2(cacheBlkSize));
63 // Create mask to get rid of offset bits.
64 cacheBlkMask = (cacheBlkSize - 1);
66 // Create space to store a cache line.
67 cacheData = new uint8_t[cacheBlkSize];
69 fetchCacheLineNextCycle = true;
71 cacheBlkValid = false;
74 // pTable = params->pTable;
81 FrontEnd<Impl>::name() const
83 return cpu->name() + ".frontend";
88 FrontEnd<Impl>::setCommBuffer(TimeBuffer<CommStruct> *_comm)
91 // @todo: Hardcoded for now. Allow this to be set by a latency.
92 fromCommit = comm->getWire(-1);
97 FrontEnd<Impl>::setTC(ThreadContext *tc_ptr)
102 template <class Impl>
104 FrontEnd<Impl>::regStats()
107 .name(name() + ".icacheStallCycles")
108 .desc("Number of cycles fetch is stalled on an Icache miss")
109 .prereq(icacheStallCycles);
112 .name(name() + ".fetchedInsts")
113 .desc("Number of instructions fetch has processed")
114 .prereq(fetchedInsts);
117 .name(name() + ".fetchedBranches")
118 .desc("Number of fetched branches")
119 .prereq(fetchedBranches);
122 .name(name() + ".predictedBranches")
123 .desc("Number of branches that fetch has predicted taken")
124 .prereq(predictedBranches);
127 .name(name() + ".fetchCycles")
128 .desc("Number of cycles fetch has run and was not squashing or"
130 .prereq(fetchCycles);
133 .name(name() + ".fetchIdleCycles")
134 .desc("Number of cycles fetch was idle")
135 .prereq(fetchIdleCycles);
138 .name(name() + ".fetchSquashCycles")
139 .desc("Number of cycles fetch has spent squashing")
140 .prereq(fetchSquashCycles);
143 .name(name() + ".fetchBlockedCycles")
144 .desc("Number of cycles fetch has spent blocked")
145 .prereq(fetchBlockedCycles);
148 .name(name() + ".fetchedCacheLines")
149 .desc("Number of cache lines fetched")
150 .prereq(fetchedCacheLines);
153 .name(name() + ".fetchIcacheSquashes")
154 .desc("Number of outstanding Icache misses that were squashed")
155 .prereq(fetchIcacheSquashes);
158 .init(/* base value */ 0,
159 /* last value */ width,
161 .name(name() + ".rateDist")
162 .desc("Number of instructions fetched each cycle (Total)")
166 .name(name() + ".idleRate")
167 .desc("Percent of cycles fetch was idle")
169 idleRate = fetchIdleCycles * 100 / cpu->numCycles;
172 .name(name() + ".branchRate")
173 .desc("Number of branch fetches per cycle")
174 .flags(Stats::total);
175 branchRate = fetchedBranches / cpu->numCycles;
178 .name(name() + ".rate")
179 .desc("Number of inst fetches per cycle")
180 .flags(Stats::total);
181 fetchRate = fetchedInsts / cpu->numCycles;
184 .name(name() + ".IFQ:count")
185 .desc("cumulative IFQ occupancy")
189 .name(name() + ".IFQ:fullCount")
190 .desc("cumulative IFQ full count")
195 .name(name() + ".IFQ:occupancy")
196 .desc("avg IFQ occupancy (inst's)")
198 IFQOccupancy = IFQCount / cpu->numCycles;
201 .name(name() + ".IFQ:latency")
202 .desc("avg IFQ occupant latency (cycle's)")
207 .name(name() + ".IFQ:fullRate")
208 .desc("fraction of time (cycles) IFQ was full")
209 .flags(Stats::total);
211 IFQFullRate = IFQFcount * Stats::constant(100) / cpu->numCycles;
214 .name(name() + ".DIS:count")
215 .desc("cumulative count of dispatched insts")
219 dispatchedSerializing
220 .name(name() + ".DIS:serializingInsts")
221 .desc("count of serializing insts dispatched")
225 dispatchedTempSerializing
226 .name(name() + ".DIS:tempSerializingInsts")
227 .desc("count of temporary serializing insts dispatched")
231 dispatchSerializeStallCycles
232 .name(name() + ".DIS:serializeStallCycles")
233 .desc("count of cycles dispatch stalled for serializing inst")
238 .name(name() + ".DIS:rate")
239 .desc("dispatched insts per cycle")
242 dispatchRate = dispatchCountStat / cpu->numCycles;
245 .name(name() + ".REG:int:full")
246 .desc("number of cycles where there were no INT registers")
250 .name(name() + ".REG:fp:full")
251 .desc("number of cycles where there were no FP registers")
253 IFQLatency = IFQOccupancy / dispatchRate;
255 branchPred.regStats();
258 template <class Impl>
260 FrontEnd<Impl>::tick()
265 // @todo: Maybe I want to just have direct communication...
266 if (fromCommit->doneSeqNum) {
267 branchPred.update(fromCommit->doneSeqNum, 0);
270 IFQCount += instBufferSize;
271 IFQFcount += instBufferSize == maxInstBufferSize;
274 if (status == IcacheMissComplete) {
275 cacheBlkValid = true;
279 status = SerializeBlocked;
281 status = RenameBlocked;
283 } else if (status == IcacheMissStall) {
284 DPRINTF(FE, "Still in Icache miss stall.\n");
289 if (status == RenameBlocked || status == SerializeBlocked ||
290 status == TrapPending || status == BEBlocked) {
291 // Will cause a one cycle bubble between changing state and
293 DPRINTF(FE, "In blocked status.\n");
295 fetchBlockedCycles++;
297 if (status == SerializeBlocked) {
298 dispatchSerializeStallCycles++;
302 } else if (status == QuiescePending) {
303 DPRINTF(FE, "Waiting for quiesce to execute or get squashed.\n");
305 } else if (status != IcacheMissComplete) {
306 if (fetchCacheLineNextCycle) {
307 Fault fault = fetchCacheLine();
308 if (fault != NoFault) {
313 fetchCacheLineNextCycle = false;
315 // If miss, stall until it returns.
316 if (status == IcacheMissStall) {
317 // Tell CPU to not tick me for now.
326 // Otherwise loop and process instructions.
327 // One way to hack infinite width is to set width and maxInstBufferSize
328 // both really high. Inelegant, but probably will work.
329 while (num_inst < width &&
330 instBufferSize < maxInstBufferSize) {
331 // Get instruction from cache line.
332 DynInstPtr inst = getInstFromCacheline();
335 // PC is no longer in the cache line, end fetch.
336 // Might want to check this at the end of the cycle so that
337 // there's no cycle lost to checking for a new cache line.
338 DPRINTF(FE, "Need to get new cache line\n");
339 fetchCacheLineNextCycle = true;
345 if (status == SerializeBlocked) {
349 // Possibly push into a time buffer that estimates the front end
351 instBuffer.push_back(inst);
356 if (inst->isQuiesce()) {
357 warn("%lli: Quiesce instruction encountered, halting fetch!", curTick);
358 status = QuiescePending;
363 if (inst->predTaken()) {
364 // Start over with tick?
366 } else if (freeRegs <= 0) {
367 DPRINTF(FE, "Ran out of free registers to rename to!\n");
368 status = RenameBlocked;
370 } else if (serializeNext) {
375 fetchNisnDist.sample(num_inst);
378 DPRINTF(FE, "Num insts processed: %i, Inst Buffer size: %i, Free "
379 "Regs %i\n", num_inst, instBufferSize, freeRegs);
382 template <class Impl>
384 FrontEnd<Impl>::fetchCacheLine()
386 // Read a cache line, based on the current PC.
388 // Flag to say whether or not address is physical addr.
389 unsigned flags = cpu->inPalMode(PC) ? PHYSICAL : 0;
392 #endif // FULL_SYSTEM
393 Fault fault = NoFault;
395 if (interruptPending && flags == 0) {
399 // Align the fetch PC so it's at the start of a cache block.
400 Addr fetch_PC = icacheBlockAlignPC(PC);
402 DPRINTF(FE, "Fetching cache line starting at %#x.\n", fetch_PC);
404 // Setup the memReq to do a read of the first isntruction's address.
405 // Set the appropriate read size and flags as well.
406 memReq = new MemReq();
409 memReq->thread_num = 0;
410 memReq->data = new uint8_t[64];
413 memReq->reset(fetch_PC, cacheBlkSize, flags);
415 // Translate the instruction request.
416 fault = cpu->translateInstReq(memReq);
418 // Now do the timing access to see whether or not the instruction
419 // exists within the cache.
420 if (icacheInterface && fault == NoFault) {
422 if (cpu->system->memctrl->badaddr(memReq->paddr) ||
423 memReq->flags & UNCACHEABLE) {
424 DPRINTF(FE, "Fetch: Bad address %#x (hopefully on a "
425 "misspeculating path!",
427 return TheISA::genMachineCheckFault();
431 memReq->completionEvent = NULL;
433 memReq->time = curTick;
434 fault = cpu->mem->read(memReq, cacheData);
436 MemAccessResult res = icacheInterface->access(memReq);
438 // If the cache missed then schedule an event to wake
439 // up this stage once the cache miss completes.
440 if (icacheInterface->doEvents() && res != MA_HIT) {
441 memReq->completionEvent = new ICacheCompletionEvent(memReq, this);
443 status = IcacheMissStall;
445 cacheBlkValid = false;
447 DPRINTF(FE, "Cache miss.\n");
449 DPRINTF(FE, "Cache hit.\n");
451 cacheBlkValid = true;
453 // memcpy(cacheData, memReq->data, memReq->size);
457 // Note that this will set the cache block PC a bit earlier than it should
459 cacheBlkPC = fetch_PC;
463 DPRINTF(FE, "Done fetching cache line.\n");
468 template <class Impl>
470 FrontEnd<Impl>::processInst(DynInstPtr &inst)
472 if (processBarriers(inst)) {
476 Addr inst_PC = inst->readPC();
478 if (!inst->isControl()) {
479 inst->setPredTarg(inst->readNextPC());
482 if (branchPred.predict(inst, inst_PC, inst->threadNumber)) {
487 Addr next_PC = inst->readPredTarg();
489 DPRINTF(FE, "[sn:%lli] Predicted and processed inst PC %#x, next PC "
490 "%#x\n", inst->seqNum, inst_PC, next_PC);
492 // inst->setNextPC(next_PC);
494 // Not sure where I should set this
500 template <class Impl>
502 FrontEnd<Impl>::processBarriers(DynInstPtr &inst)
505 inst->setSerializeBefore();
506 serializeNext = false;
507 } else if (!inst->isSerializing() &&
508 !inst->isIprAccess() &&
509 !inst->isStoreConditional()) {
513 if ((inst->isIprAccess() || inst->isSerializeBefore()) &&
514 !inst->isSerializeHandled()) {
515 DPRINTF(FE, "Serialize before instruction encountered.\n");
517 if (!inst->isTempSerializeBefore()) {
518 dispatchedSerializing++;
519 inst->setSerializeHandled();
521 dispatchedTempSerializing++;
524 // Change status over to SerializeBlocked so that other stages know
525 // what this is blocked on.
526 status = SerializeBlocked;
530 } else if ((inst->isStoreConditional() || inst->isSerializeAfter())
531 && !inst->isSerializeHandled()) {
532 DPRINTF(FE, "Serialize after instruction encountered.\n");
534 inst->setSerializeHandled();
536 dispatchedSerializing++;
538 serializeNext = true;
544 template <class Impl>
546 FrontEnd<Impl>::handleFault(Fault &fault)
548 DPRINTF(FE, "Fault at fetch, telling commit\n");
550 // We're blocked on the back end until it handles this fault.
551 status = TrapPending;
553 // Get a sequence number.
554 InstSeqNum inst_seq = getAndIncrementInstSeq();
555 // We will use a nop in order to carry the fault.
556 ExtMachInst ext_inst = TheISA::NoopMachInst;
558 // Create a new DynInst from the dummy nop.
559 DynInstPtr instruction = new DynInst(ext_inst, PC,
562 instruction->setPredTarg(instruction->readNextPC());
563 // instruction->setThread(tid);
565 // instruction->setASID(tid);
567 instruction->setState(thread);
569 instruction->traceData = NULL;
571 instruction->fault = fault;
572 instruction->setCanIssue();
573 instBuffer.push_back(instruction);
577 template <class Impl>
579 FrontEnd<Impl>::squash(const InstSeqNum &squash_num, const Addr &next_PC,
580 const bool is_branch, const bool branch_taken)
582 DPRINTF(FE, "Squashing from [sn:%lli], setting PC to %#x\n",
583 squash_num, next_PC);
585 if (fetchFault != NoFault)
586 fetchFault = NoFault;
588 while (!instBuffer.empty() &&
589 instBuffer.back()->seqNum > squash_num) {
590 DynInstPtr inst = instBuffer.back();
592 DPRINTF(FE, "Squashing instruction [sn:%lli] PC %#x\n",
593 inst->seqNum, inst->readPC());
595 inst->clearDependents();
597 instBuffer.pop_back();
600 freeRegs+= inst->numDestRegs();
603 // Copy over rename table from the back end.
604 renameTable.copyFrom(backEnd->renameTable);
608 // Update BP with proper information.
610 branchPred.squash(squash_num, next_PC, branch_taken, 0);
612 branchPred.squash(squash_num, 0);
615 // Clear the icache miss if it's outstanding.
616 if (status == IcacheMissStall && icacheInterface) {
617 DPRINTF(FE, "Squashing outstanding Icache miss.\n");
621 if (status == SerializeBlocked) {
622 assert(barrierInst->seqNum > squash_num);
626 // Unless this squash originated from the front end, we're probably
627 // in running mode now.
628 // Actually might want to make this latency dependent.
630 fetchCacheLineNextCycle = true;
633 template <class Impl>
634 typename Impl::DynInstPtr
635 FrontEnd<Impl>::getInst()
637 if (instBufferSize == 0) {
641 DynInstPtr inst = instBuffer.front();
643 instBuffer.pop_front();
652 template <class Impl>
654 FrontEnd<Impl>::processCacheCompletion(MemReqPtr &req)
656 DPRINTF(FE, "Processing cache completion\n");
658 // Do something here.
659 if (status != IcacheMissStall ||
662 DPRINTF(FE, "Previous fetch was squashed.\n");
663 fetchIcacheSquashes++;
667 status = IcacheMissComplete;
669 /* if (checkStall(tid)) {
670 fetchStatus[tid] = Blocked;
672 fetchStatus[tid] = IcacheMissComplete;
675 // memcpy(cacheData, memReq->data, memReq->size);
677 // Reset the completion event to NULL.
678 // memReq->completionEvent = NULL;
682 template <class Impl>
684 FrontEnd<Impl>::addFreeRegs(int num_freed)
686 if (status == RenameBlocked && freeRegs + num_freed > 0) {
690 DPRINTF(FE, "Adding %i freed registers\n", num_freed);
692 freeRegs+= num_freed;
694 // assert(freeRegs <= numPhysRegs);
695 if (freeRegs > numPhysRegs)
696 freeRegs = numPhysRegs;
699 template <class Impl>
701 FrontEnd<Impl>::updateStatus()
703 bool serialize_block = !backEnd->robEmpty() || instBufferSize;
704 bool be_block = cpu->decoupledFrontEnd ? false : backEnd->isBlocked();
705 bool ret_val = false;
707 if (status == SerializeBlocked && !serialize_block) {
708 status = SerializeComplete;
712 if (status == BEBlocked && !be_block) {
714 status = SerializeBlocked;
723 template <class Impl>
725 FrontEnd<Impl>::checkBE()
727 bool be_block = cpu->decoupledFrontEnd ? false : backEnd->isBlocked();
729 if (status == Running || status == Idle) {
735 template <class Impl>
736 typename Impl::DynInstPtr
737 FrontEnd<Impl>::getInstFromCacheline()
739 if (status == SerializeComplete) {
740 DynInstPtr inst = barrierInst;
743 inst->clearSerializeBefore();
749 // @todo: Fix this magic number used here to handle word offset (and
750 // getting rid of PAL bit)
751 unsigned offset = (PC & cacheBlkMask) & ~3;
753 // PC of inst is not in this cache block
754 if (PC >= (cacheBlkPC + cacheBlkSize) || PC < cacheBlkPC || !cacheBlkValid) {
758 //////////////////////////
759 // Fetch one instruction
760 //////////////////////////
762 // Get a sequence number.
763 inst_seq = getAndIncrementInstSeq();
765 // Make sure this is a valid index.
766 assert(offset <= cacheBlkSize - sizeof(MachInst));
768 // Get the instruction from the array of the cache line.
769 inst = htog(*reinterpret_cast<MachInst *>(&cacheData[offset]));
771 ExtMachInst decode_inst = TheISA::makeExtMI(inst, PC);
773 // Create a new DynInst from the instruction fetched.
774 DynInstPtr instruction = new DynInst(decode_inst, PC, PC+sizeof(MachInst),
777 instruction->setState(thread);
779 DPRINTF(FE, "Instruction [sn:%lli] created, with PC %#x\n%s\n",
780 inst_seq, instruction->readPC(),
781 instruction->staticInst->disassemble(PC));
783 instruction->traceData =
784 Trace::getInstRecord(curTick, tc, cpu,
785 instruction->staticInst,
786 instruction->readPC(), 0);
788 // Increment stat of fetched instructions.
794 template <class Impl>
796 FrontEnd<Impl>::renameInst(DynInstPtr &inst)
798 DynInstPtr src_inst = NULL;
799 int num_src_regs = inst->numSrcRegs();
800 if (num_src_regs == 0) {
803 for (int i = 0; i < num_src_regs; ++i) {
804 src_inst = renameTable[inst->srcRegIdx(i)];
806 inst->setSrcInst(src_inst, i);
808 DPRINTF(FE, "[sn:%lli]: Src reg %i is inst [sn:%lli]\n",
809 inst->seqNum, (int)inst->srcRegIdx(i), src_inst->seqNum);
811 if (src_inst->isResultReady()) {
812 DPRINTF(FE, "Reg ready.\n");
813 inst->markSrcRegReady(i);
815 DPRINTF(FE, "Adding to dependent list.\n");
816 src_inst->addDependent(inst);
821 for (int i = 0; i < inst->numDestRegs(); ++i) {
822 RegIndex idx = inst->destRegIdx(i);
824 DPRINTF(FE, "Dest reg %i is now inst [sn:%lli], was previously "
826 (int)inst->destRegIdx(i), inst->seqNum,
827 renameTable[idx]->seqNum);
829 inst->setPrevDestInst(renameTable[idx], i);
831 renameTable[idx] = inst;
836 template <class Impl>
838 FrontEnd<Impl>::wakeFromQuiesce()
840 DPRINTF(FE, "Waking up from quiesce\n");
841 // Hopefully this is safe
845 template <class Impl>
847 FrontEnd<Impl>::switchOut()
850 cpu->signalSwitched();
853 template <class Impl>
855 FrontEnd<Impl>::doSwitchOut()
864 template <class Impl>
866 FrontEnd<Impl>::takeOverFrom(ThreadContext *old_tc)
868 assert(freeRegs == numPhysRegs);
869 fetchCacheLineNextCycle = true;
871 cacheBlkValid = false;
874 // pTable = params->pTable;
876 fetchFault = NoFault;
877 serializeNext = false;
881 interruptPending = false;
884 template <class Impl>
886 FrontEnd<Impl>::dumpInsts()
888 cprintf("instBuffer size: %i\n", instBuffer.size());
890 InstBuffIt buff_it = instBuffer.begin();
892 for (int num = 0; buff_it != instBuffer.end(); num++) {
893 cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
895 num, (*buff_it)->readPC(), (*buff_it)->threadNumber,
896 (*buff_it)->seqNum, (*buff_it)->isIssued(),
897 (*buff_it)->isSquashed());
902 template <class Impl>
903 FrontEnd<Impl>::ICacheCompletionEvent::ICacheCompletionEvent(MemReqPtr &_req, FrontEnd *fe)
904 : Event(&mainEventQueue, Delayed_Writeback_Pri), req(_req), frontEnd(fe)
906 this->setFlags(Event::AutoDelete);
909 template <class Impl>
911 FrontEnd<Impl>::ICacheCompletionEvent::process()
913 frontEnd->processCacheCompletion(req);
916 template <class Impl>
918 FrontEnd<Impl>::ICacheCompletionEvent::description()
920 return "ICache completion event";