rename_impl.hh revision 2361
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
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.
15 *
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.
27 */
28
29#include <list>
30
31#include "config/full_system.hh"
32#include "cpu/o3/rename.hh"
33
34using namespace std;
35
36template <class Impl>
37DefaultRename<Impl>::DefaultRename(Params *params)
38    : iewToRenameDelay(params->iewToRenameDelay),
39      decodeToRenameDelay(params->decodeToRenameDelay),
40      commitToRenameDelay(params->commitToRenameDelay),
41      renameWidth(params->renameWidth),
42      commitWidth(params->commitWidth),
43      numThreads(params->numberOfThreads),
44      maxPhysicalRegs(params->numPhysIntRegs + params->numPhysFloatRegs)
45{
46    _status = Inactive;
47
48    for (int i=0; i< numThreads; i++) {
49        renameStatus[i] = Idle;
50
51        freeEntries[i].iqEntries = 0;
52        freeEntries[i].lsqEntries = 0;
53        freeEntries[i].robEntries = 0;
54
55        stalls[i].iew = false;
56        stalls[i].commit = false;
57        serializeInst[i] = NULL;
58
59        instsInProgress[i] = 0;
60
61        emptyROB[i] = true;
62
63        serializeOnNextInst[i] = false;
64    }
65
66    // @todo: Make into a parameter.
67    skidBufferMax = (2 * (iewToRenameDelay * params->decodeWidth)) + renameWidth;
68}
69
70template <class Impl>
71std::string
72DefaultRename<Impl>::name() const
73{
74    return cpu->name() + ".rename";
75}
76
77template <class Impl>
78void
79DefaultRename<Impl>::regStats()
80{
81    renameSquashCycles
82        .name(name() + ".RENAME:SquashCycles")
83        .desc("Number of cycles rename is squashing")
84        .prereq(renameSquashCycles);
85    renameIdleCycles
86        .name(name() + ".RENAME:IdleCycles")
87        .desc("Number of cycles rename is idle")
88        .prereq(renameIdleCycles);
89    renameBlockCycles
90        .name(name() + ".RENAME:BlockCycles")
91        .desc("Number of cycles rename is blocking")
92        .prereq(renameBlockCycles);
93    renameSerializeStallCycles
94        .name(name() + ".RENAME:serializeStallCycles")
95        .desc("count of cycles rename stalled for serializing inst")
96        .flags(Stats::total);
97    renameRunCycles
98        .name(name() + ".RENAME:RunCycles")
99        .desc("Number of cycles rename is running")
100        .prereq(renameIdleCycles);
101    renameUnblockCycles
102        .name(name() + ".RENAME:UnblockCycles")
103        .desc("Number of cycles rename is unblocking")
104        .prereq(renameUnblockCycles);
105    renameRenamedInsts
106        .name(name() + ".RENAME:RenamedInsts")
107        .desc("Number of instructions processed by rename")
108        .prereq(renameRenamedInsts);
109    renameSquashedInsts
110        .name(name() + ".RENAME:SquashedInsts")
111        .desc("Number of squashed instructions processed by rename")
112        .prereq(renameSquashedInsts);
113    renameROBFullEvents
114        .name(name() + ".RENAME:ROBFullEvents")
115        .desc("Number of times rename has blocked due to ROB full")
116        .prereq(renameROBFullEvents);
117    renameIQFullEvents
118        .name(name() + ".RENAME:IQFullEvents")
119        .desc("Number of times rename has blocked due to IQ full")
120        .prereq(renameIQFullEvents);
121    renameLSQFullEvents
122        .name(name() + ".RENAME:LSQFullEvents")
123        .desc("Number of times rename has blocked due to LSQ full")
124        .prereq(renameLSQFullEvents);
125    renameFullRegistersEvents
126        .name(name() + ".RENAME:FullRegisterEvents")
127        .desc("Number of times there has been no free registers")
128        .prereq(renameFullRegistersEvents);
129    renameRenamedOperands
130        .name(name() + ".RENAME:RenamedOperands")
131        .desc("Number of destination operands rename has renamed")
132        .prereq(renameRenamedOperands);
133    renameRenameLookups
134        .name(name() + ".RENAME:RenameLookups")
135        .desc("Number of register rename lookups that rename has made")
136        .prereq(renameRenameLookups);
137    renameCommittedMaps
138        .name(name() + ".RENAME:CommittedMaps")
139        .desc("Number of HB maps that are committed")
140        .prereq(renameCommittedMaps);
141    renameUndoneMaps
142        .name(name() + ".RENAME:UndoneMaps")
143        .desc("Number of HB maps that are undone due to squashing")
144        .prereq(renameUndoneMaps);
145    renamedSerializing
146        .name(name() + ".RENAME:serializingInsts")
147        .desc("count of serializing insts renamed")
148        .flags(Stats::total)
149        ;
150    renamedTempSerializing
151        .name(name() + ".RENAME:tempSerializingInsts")
152        .desc("count of temporary serializing insts renamed")
153        .flags(Stats::total)
154        ;
155    renameSkidInsts
156        .name(name() + ".RENAME:skidInsts")
157        .desc("count of insts added to the skid buffer")
158        .flags(Stats::total)
159        ;
160}
161
162template <class Impl>
163void
164DefaultRename<Impl>::setCPU(FullCPU *cpu_ptr)
165{
166    DPRINTF(Rename, "Setting CPU pointer.\n");
167    cpu = cpu_ptr;
168}
169
170template <class Impl>
171void
172DefaultRename<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
173{
174    DPRINTF(Rename, "Setting time buffer pointer.\n");
175    timeBuffer = tb_ptr;
176
177    // Setup wire to read information from time buffer, from IEW stage.
178    fromIEW = timeBuffer->getWire(-iewToRenameDelay);
179
180    // Setup wire to read infromation from time buffer, from commit stage.
181    fromCommit = timeBuffer->getWire(-commitToRenameDelay);
182
183    // Setup wire to write information to previous stages.
184    toDecode = timeBuffer->getWire(0);
185}
186
187template <class Impl>
188void
189DefaultRename<Impl>::setRenameQueue(TimeBuffer<RenameStruct> *rq_ptr)
190{
191    DPRINTF(Rename, "Setting rename queue pointer.\n");
192    renameQueue = rq_ptr;
193
194    // Setup wire to write information to future stages.
195    toIEW = renameQueue->getWire(0);
196}
197
198template <class Impl>
199void
200DefaultRename<Impl>::setDecodeQueue(TimeBuffer<DecodeStruct> *dq_ptr)
201{
202    DPRINTF(Rename, "Setting decode queue pointer.\n");
203    decodeQueue = dq_ptr;
204
205    // Setup wire to get information from decode.
206    fromDecode = decodeQueue->getWire(-decodeToRenameDelay);
207}
208
209template <class Impl>
210void
211DefaultRename<Impl>::initStage()
212{
213    // Grab the number of free entries directly from the stages.
214    for (int tid=0; tid < numThreads; tid++) {
215        freeEntries[tid].iqEntries = iew_ptr->instQueue.numFreeEntries(tid);
216        freeEntries[tid].lsqEntries = iew_ptr->ldstQueue.numFreeEntries(tid);
217        freeEntries[tid].robEntries = commit_ptr->numROBFreeEntries(tid);
218        emptyROB[tid] = true;
219    }
220}
221
222template<class Impl>
223void
224DefaultRename<Impl>::setActiveThreads(list<unsigned> *at_ptr)
225{
226    DPRINTF(Rename, "Setting active threads list pointer.\n");
227    activeThreads = at_ptr;
228}
229
230
231template <class Impl>
232void
233DefaultRename<Impl>::setRenameMap(RenameMap rm_ptr[])
234{
235    DPRINTF(Rename, "Setting rename map pointers.\n");
236
237    for (int i=0; i<numThreads; i++) {
238        renameMap[i] = &rm_ptr[i];
239    }
240}
241
242template <class Impl>
243void
244DefaultRename<Impl>::setFreeList(FreeList *fl_ptr)
245{
246    DPRINTF(Rename, "Setting free list pointer.\n");
247    freeList = fl_ptr;
248}
249
250template<class Impl>
251void
252DefaultRename<Impl>::setScoreboard(Scoreboard *_scoreboard)
253{
254    DPRINTF(Rename, "Setting scoreboard pointer.\n");
255    scoreboard = _scoreboard;
256}
257
258template <class Impl>
259void
260DefaultRename<Impl>::switchOut()
261{
262    // Rename is ready to switch out at any time.
263    cpu->signalSwitched();
264}
265
266template <class Impl>
267void
268DefaultRename<Impl>::doSwitchOut()
269{
270    // Clear any state, fix up the rename map.
271    for (int i = 0; i < numThreads; i++) {
272        typename list<RenameHistory>::iterator hb_it = historyBuffer[i].begin();
273
274        while (!historyBuffer[i].empty()) {
275            assert(hb_it != historyBuffer[i].end());
276
277            DPRINTF(Rename, "[tid:%u]: Removing history entry with sequence "
278                    "number %i.\n", i, (*hb_it).instSeqNum);
279
280            // Tell the rename map to set the architected register to the
281            // previous physical register that it was renamed to.
282            renameMap[i]->setEntry(hb_it->archReg, hb_it->prevPhysReg);
283
284            // Put the renamed physical register back on the free list.
285            freeList->addReg(hb_it->newPhysReg);
286
287            // Be sure to mark its register as ready if it's a misc register.
288            if (hb_it->newPhysReg >= maxPhysicalRegs) {
289                scoreboard->setReg(hb_it->newPhysReg);
290            }
291
292            historyBuffer[i].erase(hb_it++);
293        }
294        insts[i].clear();
295        skidBuffer[i].clear();
296    }
297}
298
299template <class Impl>
300void
301DefaultRename<Impl>::takeOverFrom()
302{
303    _status = Inactive;
304    initStage();
305
306    // Reset all state prior to taking over from the other CPU.
307    for (int i=0; i< numThreads; i++) {
308        renameStatus[i] = Idle;
309
310        stalls[i].iew = false;
311        stalls[i].commit = false;
312        serializeInst[i] = NULL;
313
314        instsInProgress[i] = 0;
315
316        emptyROB[i] = true;
317
318        serializeOnNextInst[i] = false;
319    }
320}
321
322template <class Impl>
323void
324DefaultRename<Impl>::squash(unsigned tid)
325{
326    DPRINTF(Rename, "[tid:%u]: Squashing instructions.\n",tid);
327
328    // Clear the stall signal if rename was blocked or unblocking before.
329    // If it still needs to block, the blocking should happen the next
330    // cycle and there should be space to hold everything due to the squash.
331    if (renameStatus[tid] == Blocked ||
332        renameStatus[tid] == Unblocking ||
333        renameStatus[tid] == SerializeStall) {
334#if 0
335        // In syscall emulation, we can have both a block and a squash due
336        // to a syscall in the same cycle.  This would cause both signals to
337        // be high.  This shouldn't happen in full system.
338        if (toDecode->renameBlock[tid]) {
339            toDecode->renameBlock[tid] = 0;
340        } else {
341            toDecode->renameUnblock[tid] = 1;
342        }
343#else
344        toDecode->renameUnblock[tid] = 1;
345#endif
346        serializeInst[tid] = NULL;
347    }
348
349    // Set the status to Squashing.
350    renameStatus[tid] = Squashing;
351
352    // Squash any instructions from decode.
353    unsigned squashCount = 0;
354
355    for (int i=0; i<fromDecode->size; i++) {
356        if (fromDecode->insts[i]->threadNumber == tid) {
357            fromDecode->insts[i]->setSquashed();
358            wroteToTimeBuffer = true;
359            squashCount++;
360        }
361    }
362
363    insts[tid].clear();
364
365    // Clear the skid buffer in case it has any data in it.
366    skidBuffer[tid].clear();
367
368    doSquash(tid);
369}
370
371template <class Impl>
372void
373DefaultRename<Impl>::tick()
374{
375    wroteToTimeBuffer = false;
376
377    blockThisCycle = false;
378
379    bool status_change = false;
380
381    toIEWIndex = 0;
382
383    sortInsts();
384
385    list<unsigned>::iterator threads = (*activeThreads).begin();
386
387    // Check stall and squash signals.
388    while (threads != (*activeThreads).end()) {
389        unsigned tid = *threads++;
390
391        DPRINTF(Rename, "Processing [tid:%i]\n", tid);
392
393        status_change = checkSignalsAndUpdate(tid) || status_change;
394
395        rename(status_change, tid);
396    }
397
398    if (status_change) {
399        updateStatus();
400    }
401
402    if (wroteToTimeBuffer) {
403        DPRINTF(Activity, "Activity this cycle.\n");
404        cpu->activityThisCycle();
405    }
406
407    threads = (*activeThreads).begin();
408
409    while (threads != (*activeThreads).end()) {
410        unsigned tid = *threads++;
411
412        // If we committed this cycle then doneSeqNum will be > 0
413        if (fromCommit->commitInfo[tid].doneSeqNum != 0 &&
414            !fromCommit->commitInfo[tid].squash &&
415            renameStatus[tid] != Squashing) {
416
417            removeFromHistory(fromCommit->commitInfo[tid].doneSeqNum,
418                                  tid);
419        }
420    }
421
422    // @todo: make into updateProgress function
423    for (int tid=0; tid < numThreads; tid++) {
424        instsInProgress[tid] -= fromIEW->iewInfo[tid].dispatched;
425
426        assert(instsInProgress[tid] >=0);
427    }
428
429}
430
431template<class Impl>
432void
433DefaultRename<Impl>::rename(bool &status_change, unsigned tid)
434{
435    // If status is Running or idle,
436    //     call renameInsts()
437    // If status is Unblocking,
438    //     buffer any instructions coming from decode
439    //     continue trying to empty skid buffer
440    //     check if stall conditions have passed
441
442    if (renameStatus[tid] == Blocked) {
443        ++renameBlockCycles;
444    } else if (renameStatus[tid] == Squashing) {
445        ++renameSquashCycles;
446    } else if (renameStatus[tid] == SerializeStall) {
447        ++renameSerializeStallCycles;
448    }
449
450    if (renameStatus[tid] == Running ||
451        renameStatus[tid] == Idle) {
452        DPRINTF(Rename, "[tid:%u]: Not blocked, so attempting to run "
453                "stage.\n", tid);
454
455        renameInsts(tid);
456    } else if (renameStatus[tid] == Unblocking) {
457        renameInsts(tid);
458
459        if (validInsts()) {
460            // Add the current inputs to the skid buffer so they can be
461            // reprocessed when this stage unblocks.
462            skidInsert(tid);
463        }
464
465        // If we switched over to blocking, then there's a potential for
466        // an overall status change.
467        status_change = unblock(tid) || status_change || blockThisCycle;
468    }
469}
470
471template <class Impl>
472void
473DefaultRename<Impl>::renameInsts(unsigned tid)
474{
475    // Instructions can be either in the skid buffer or the queue of
476    // instructions coming from decode, depending on the status.
477    int insts_available = renameStatus[tid] == Unblocking ?
478        skidBuffer[tid].size() : insts[tid].size();
479
480    // Check the decode queue to see if instructions are available.
481    // If there are no available instructions to rename, then do nothing.
482    if (insts_available == 0) {
483        DPRINTF(Rename, "[tid:%u]: Nothing to do, breaking out early.\n",
484                tid);
485        // Should I change status to idle?
486        ++renameIdleCycles;
487        return;
488    } else if (renameStatus[tid] == Unblocking) {
489        ++renameUnblockCycles;
490    } else if (renameStatus[tid] == Running) {
491        ++renameRunCycles;
492    }
493
494    DynInstPtr inst;
495
496    // Will have to do a different calculation for the number of free
497    // entries.
498    int free_rob_entries = calcFreeROBEntries(tid);
499    int free_iq_entries  = calcFreeIQEntries(tid);
500    int free_lsq_entries = calcFreeLSQEntries(tid);
501    int min_free_entries = free_rob_entries;
502
503    FullSource source = ROB;
504
505    if (free_iq_entries < min_free_entries) {
506        min_free_entries = free_iq_entries;
507        source = IQ;
508    }
509
510    if (free_lsq_entries < min_free_entries) {
511        min_free_entries = free_lsq_entries;
512        source = LSQ;
513    }
514
515    // Check if there's any space left.
516    if (min_free_entries <= 0) {
517        DPRINTF(Rename, "[tid:%u]: Blocking due to no free ROB/IQ/LSQ "
518                "entries.\n"
519                "ROB has %i free entries.\n"
520                "IQ has %i free entries.\n"
521                "LSQ has %i free entries.\n",
522                tid,
523                free_rob_entries,
524                free_iq_entries,
525                free_lsq_entries);
526
527        blockThisCycle = true;
528
529        block(tid);
530
531        incrFullStat(source);
532
533        return;
534    } else if (min_free_entries < insts_available) {
535        DPRINTF(Rename, "[tid:%u]: Will have to block this cycle."
536                "%i insts available, but only %i insts can be "
537                "renamed due to ROB/IQ/LSQ limits.\n",
538                tid, insts_available, min_free_entries);
539
540        insts_available = min_free_entries;
541
542        blockThisCycle = true;
543
544        incrFullStat(source);
545    }
546
547    InstQueue &insts_to_rename = renameStatus[tid] == Unblocking ?
548        skidBuffer[tid] : insts[tid];
549
550    DPRINTF(Rename, "[tid:%u]: %i available instructions to "
551            "send iew.\n", tid, insts_available);
552
553    DPRINTF(Rename, "[tid:%u]: %i insts pipelining from Rename | %i insts "
554            "dispatched to IQ last cycle.\n",
555            tid, instsInProgress[tid], fromIEW->iewInfo[tid].dispatched);
556
557    // Handle serializing the next instruction if necessary.
558    if (serializeOnNextInst[tid]) {
559        if (emptyROB[tid] && instsInProgress[tid] == 0) {
560            // ROB already empty; no need to serialize.
561            serializeOnNextInst[tid] = false;
562        } else if (!insts_to_rename.empty()) {
563            insts_to_rename.front()->setSerializeBefore();
564        }
565    }
566
567    int renamed_insts = 0;
568
569    while (insts_available > 0 &&  toIEWIndex < renameWidth) {
570        DPRINTF(Rename, "[tid:%u]: Sending instructions to IEW.\n", tid);
571
572        assert(!insts_to_rename.empty());
573
574        inst = insts_to_rename.front();
575
576        insts_to_rename.pop_front();
577
578        if (renameStatus[tid] == Unblocking) {
579            DPRINTF(Rename,"[tid:%u]: Removing [sn:%lli] PC:%#x from rename "
580                    "skidBuffer\n",
581                    tid, inst->seqNum, inst->readPC());
582        }
583
584        if (inst->isSquashed()) {
585            DPRINTF(Rename, "[tid:%u]: instruction %i with PC %#x is "
586                    "squashed, skipping.\n",
587                    tid, inst->seqNum, inst->threadNumber,inst->readPC());
588
589            ++renameSquashedInsts;
590
591            // Decrement how many instructions are available.
592            --insts_available;
593
594            continue;
595        }
596
597        DPRINTF(Rename, "[tid:%u]: Processing instruction [sn:%lli] with "
598                "PC %#x.\n",
599                tid, inst->seqNum, inst->readPC());
600
601        // Handle serializeAfter/serializeBefore instructions.
602        // serializeAfter marks the next instruction as serializeBefore.
603        // serializeBefore makes the instruction wait in rename until the ROB
604        // is empty.
605
606        // In this model, IPR accesses are serialize before
607        // instructions, and store conditionals are serialize after
608        // instructions.  This is mainly due to lack of support for
609        // out-of-order operations of either of those classes of
610        // instructions.
611        if ((inst->isIprAccess() || inst->isSerializeBefore()) &&
612            !inst->isSerializeHandled()) {
613            DPRINTF(Rename, "Serialize before instruction encountered.\n");
614
615            if (!inst->isTempSerializeBefore()) {
616                renamedSerializing++;
617                inst->setSerializeHandled();
618            } else {
619                renamedTempSerializing++;
620            }
621
622            // Change status over to SerializeStall so that other stages know
623            // what this is blocked on.
624            renameStatus[tid] = SerializeStall;
625
626            serializeInst[tid] = inst;
627
628            blockThisCycle = true;
629
630            break;
631        } else if ((inst->isStoreConditional() || inst->isSerializeAfter()) &&
632                   !inst->isSerializeHandled()) {
633            DPRINTF(Rename, "Serialize after instruction encountered.\n");
634
635            renamedSerializing++;
636
637            inst->setSerializeHandled();
638
639            serializeAfter(insts_to_rename, tid);
640        }
641
642        // Check here to make sure there are enough destination registers
643        // to rename to.  Otherwise block.
644        if (renameMap[tid]->numFreeEntries() < inst->numDestRegs()) {
645            DPRINTF(Rename, "Blocking due to lack of free "
646                    "physical registers to rename to.\n");
647            blockThisCycle = true;
648
649            ++renameFullRegistersEvents;
650
651            break;
652        }
653
654        renameSrcRegs(inst, inst->threadNumber);
655
656        renameDestRegs(inst, inst->threadNumber);
657
658        ++renamed_insts;
659
660        // Put instruction in rename queue.
661        toIEW->insts[toIEWIndex] = inst;
662        ++(toIEW->size);
663
664        // Increment which instruction we're on.
665        ++toIEWIndex;
666
667        // Decrement how many instructions are available.
668        --insts_available;
669    }
670
671    instsInProgress[tid] += renamed_insts;
672    renameRenamedInsts += renamed_insts;
673
674    // If we wrote to the time buffer, record this.
675    if (toIEWIndex) {
676        wroteToTimeBuffer = true;
677    }
678
679    // Check if there's any instructions left that haven't yet been renamed.
680    // If so then block.
681    if (insts_available) {
682        blockThisCycle = true;
683    }
684
685    if (blockThisCycle) {
686        block(tid);
687        toDecode->renameUnblock[tid] = false;
688    }
689}
690
691template<class Impl>
692void
693DefaultRename<Impl>::skidInsert(unsigned tid)
694{
695    DynInstPtr inst = NULL;
696
697    while (!insts[tid].empty()) {
698        inst = insts[tid].front();
699
700        insts[tid].pop_front();
701
702        assert(tid == inst->threadNumber);
703
704        DPRINTF(Rename, "[tid:%u]: Inserting [sn:%lli] PC:%#x into Rename "
705                "skidBuffer\n", tid, inst->seqNum, inst->readPC());
706
707        ++renameSkidInsts;
708
709        skidBuffer[tid].push_back(inst);
710    }
711
712    if (skidBuffer[tid].size() > skidBufferMax)
713        panic("Skidbuffer Exceeded Max Size");
714}
715
716template <class Impl>
717void
718DefaultRename<Impl>::sortInsts()
719{
720    int insts_from_decode = fromDecode->size;
721#ifdef DEBUG
722    for (int i=0; i < numThreads; i++)
723        assert(insts[i].empty());
724#endif
725    for (int i = 0; i < insts_from_decode; ++i) {
726        DynInstPtr inst = fromDecode->insts[i];
727        insts[inst->threadNumber].push_back(inst);
728    }
729}
730
731template<class Impl>
732bool
733DefaultRename<Impl>::skidsEmpty()
734{
735    list<unsigned>::iterator threads = (*activeThreads).begin();
736
737    while (threads != (*activeThreads).end()) {
738        if (!skidBuffer[*threads++].empty())
739            return false;
740    }
741
742    return true;
743}
744
745template<class Impl>
746void
747DefaultRename<Impl>::updateStatus()
748{
749    bool any_unblocking = false;
750
751    list<unsigned>::iterator threads = (*activeThreads).begin();
752
753    threads = (*activeThreads).begin();
754
755    while (threads != (*activeThreads).end()) {
756        unsigned tid = *threads++;
757
758        if (renameStatus[tid] == Unblocking) {
759            any_unblocking = true;
760            break;
761        }
762    }
763
764    // Rename will have activity if it's unblocking.
765    if (any_unblocking) {
766        if (_status == Inactive) {
767            _status = Active;
768
769            DPRINTF(Activity, "Activating stage.\n");
770
771            cpu->activateStage(FullCPU::RenameIdx);
772        }
773    } else {
774        // If it's not unblocking, then rename will not have any internal
775        // activity.  Switch it to inactive.
776        if (_status == Active) {
777            _status = Inactive;
778            DPRINTF(Activity, "Deactivating stage.\n");
779
780            cpu->deactivateStage(FullCPU::RenameIdx);
781        }
782    }
783}
784
785template <class Impl>
786bool
787DefaultRename<Impl>::block(unsigned tid)
788{
789    DPRINTF(Rename, "[tid:%u]: Blocking.\n", tid);
790
791    // Add the current inputs onto the skid buffer, so they can be
792    // reprocessed when this stage unblocks.
793    skidInsert(tid);
794
795    // Only signal backwards to block if the previous stages do not think
796    // rename is already blocked.
797    if (renameStatus[tid] != Blocked) {
798        if (renameStatus[tid] != Unblocking) {
799            toDecode->renameBlock[tid] = true;
800            toDecode->renameUnblock[tid] = false;
801            wroteToTimeBuffer = true;
802        }
803
804        // Rename can not go from SerializeStall to Blocked, otherwise
805        // it would not know to complete the serialize stall.
806        if (renameStatus[tid] != SerializeStall) {
807            // Set status to Blocked.
808            renameStatus[tid] = Blocked;
809            return true;
810        }
811    }
812
813    return false;
814}
815
816template <class Impl>
817bool
818DefaultRename<Impl>::unblock(unsigned tid)
819{
820    DPRINTF(Rename, "[tid:%u]: Trying to unblock.\n", tid);
821
822    // Rename is done unblocking if the skid buffer is empty.
823    if (skidBuffer[tid].empty() && renameStatus[tid] != SerializeStall) {
824
825        DPRINTF(Rename, "[tid:%u]: Done unblocking.\n", tid);
826
827        toDecode->renameUnblock[tid] = true;
828        wroteToTimeBuffer = true;
829
830        renameStatus[tid] = Running;
831        return true;
832    }
833
834    return false;
835}
836
837template <class Impl>
838void
839DefaultRename<Impl>::doSquash(unsigned tid)
840{
841    typename list<RenameHistory>::iterator hb_it = historyBuffer[tid].begin();
842
843    InstSeqNum squashed_seq_num = fromCommit->commitInfo[tid].doneSeqNum;
844
845    // After a syscall squashes everything, the history buffer may be empty
846    // but the ROB may still be squashing instructions.
847    if (historyBuffer[tid].empty()) {
848        return;
849    }
850
851    // Go through the most recent instructions, undoing the mappings
852    // they did and freeing up the registers.
853    while (!historyBuffer[tid].empty() &&
854           (*hb_it).instSeqNum > squashed_seq_num) {
855        assert(hb_it != historyBuffer[tid].end());
856
857        DPRINTF(Rename, "[tid:%u]: Removing history entry with sequence "
858                "number %i.\n", tid, (*hb_it).instSeqNum);
859
860        // Tell the rename map to set the architected register to the
861        // previous physical register that it was renamed to.
862        renameMap[tid]->setEntry(hb_it->archReg, hb_it->prevPhysReg);
863
864        // Put the renamed physical register back on the free list.
865        freeList->addReg(hb_it->newPhysReg);
866
867        historyBuffer[tid].erase(hb_it++);
868
869        ++renameUndoneMaps;
870    }
871}
872
873template<class Impl>
874void
875DefaultRename<Impl>::removeFromHistory(InstSeqNum inst_seq_num, unsigned tid)
876{
877    DPRINTF(Rename, "[tid:%u]: Removing a committed instruction from the "
878            "history buffer %u (size=%i), until [sn:%lli].\n",
879            tid, tid, historyBuffer[tid].size(), inst_seq_num);
880
881    typename list<RenameHistory>::iterator hb_it = historyBuffer[tid].end();
882
883    --hb_it;
884
885    if (historyBuffer[tid].empty()) {
886        DPRINTF(Rename, "[tid:%u]: History buffer is empty.\n", tid);
887        return;
888    } else if (hb_it->instSeqNum > inst_seq_num) {
889        DPRINTF(Rename, "[tid:%u]: Old sequence number encountered.  Ensure "
890                "that a syscall happened recently.\n", tid);
891        return;
892    }
893
894    // Commit all the renames up until (and including) the committed sequence
895    // number. Some or even all of the committed instructions may not have
896    // rename histories if they did not have destination registers that were
897    // renamed.
898    while (!historyBuffer[tid].empty() &&
899           hb_it != historyBuffer[tid].end() &&
900           (*hb_it).instSeqNum <= inst_seq_num) {
901
902        DPRINTF(Rename, "[tid:%u]: Freeing up older rename of reg %i, "
903                "[sn:%lli].\n",
904                tid, (*hb_it).prevPhysReg, (*hb_it).instSeqNum);
905
906        freeList->addReg((*hb_it).prevPhysReg);
907        ++renameCommittedMaps;
908
909        historyBuffer[tid].erase(hb_it--);
910    }
911}
912
913template <class Impl>
914inline void
915DefaultRename<Impl>::renameSrcRegs(DynInstPtr &inst,unsigned tid)
916{
917    assert(renameMap[tid] != 0);
918
919    unsigned num_src_regs = inst->numSrcRegs();
920
921    // Get the architectual register numbers from the source and
922    // destination operands, and redirect them to the right register.
923    // Will need to mark dependencies though.
924    for (int src_idx = 0; src_idx < num_src_regs; src_idx++) {
925        RegIndex src_reg = inst->srcRegIdx(src_idx);
926
927        // Look up the source registers to get the phys. register they've
928        // been renamed to, and set the sources to those registers.
929        PhysRegIndex renamed_reg = renameMap[tid]->lookup(src_reg);
930
931        DPRINTF(Rename, "[tid:%u]: Looking up arch reg %i, got "
932                "physical reg %i.\n", tid, (int)src_reg,
933                (int)renamed_reg);
934
935        inst->renameSrcReg(src_idx, renamed_reg);
936
937        // See if the register is ready or not.
938        if (scoreboard->getReg(renamed_reg) == true) {
939            DPRINTF(Rename, "[tid:%u]: Register is ready.\n", tid);
940
941            inst->markSrcRegReady(src_idx);
942        }
943
944        ++renameRenameLookups;
945    }
946}
947
948template <class Impl>
949inline void
950DefaultRename<Impl>::renameDestRegs(DynInstPtr &inst,unsigned tid)
951{
952    typename RenameMap::RenameInfo rename_result;
953
954    unsigned num_dest_regs = inst->numDestRegs();
955
956    // Rename the destination registers.
957    for (int dest_idx = 0; dest_idx < num_dest_regs; dest_idx++) {
958        RegIndex dest_reg = inst->destRegIdx(dest_idx);
959
960        // Get the physical register that the destination will be
961        // renamed to.
962        rename_result = renameMap[tid]->rename(dest_reg);
963
964        //Mark Scoreboard entry as not ready
965        scoreboard->unsetReg(rename_result.first);
966
967        DPRINTF(Rename, "[tid:%u]: Renaming arch reg %i to physical "
968                "reg %i.\n", tid, (int)dest_reg,
969                (int)rename_result.first);
970
971        // Record the rename information so that a history can be kept.
972        RenameHistory hb_entry(inst->seqNum, dest_reg,
973                               rename_result.first,
974                               rename_result.second);
975
976        historyBuffer[tid].push_front(hb_entry);
977
978        DPRINTF(Rename, "[tid:%u]: Adding instruction to history buffer, "
979                "[sn:%lli].\n",tid,
980                (*historyBuffer[tid].begin()).instSeqNum);
981
982        // Tell the instruction to rename the appropriate destination
983        // register (dest_idx) to the new physical register
984        // (rename_result.first), and record the previous physical
985        // register that the same logical register was renamed to
986        // (rename_result.second).
987        inst->renameDestReg(dest_idx,
988                            rename_result.first,
989                            rename_result.second);
990
991        ++renameRenamedOperands;
992    }
993}
994
995template <class Impl>
996inline int
997DefaultRename<Impl>::calcFreeROBEntries(unsigned tid)
998{
999    int num_free = freeEntries[tid].robEntries -
1000                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatched);
1001
1002    //DPRINTF(Rename,"[tid:%i]: %i rob free\n",tid,num_free);
1003
1004    return num_free;
1005}
1006
1007template <class Impl>
1008inline int
1009DefaultRename<Impl>::calcFreeIQEntries(unsigned tid)
1010{
1011    int num_free = freeEntries[tid].iqEntries -
1012                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatched);
1013
1014    //DPRINTF(Rename,"[tid:%i]: %i iq free\n",tid,num_free);
1015
1016    return num_free;
1017}
1018
1019template <class Impl>
1020inline int
1021DefaultRename<Impl>::calcFreeLSQEntries(unsigned tid)
1022{
1023    int num_free = freeEntries[tid].lsqEntries -
1024                  (instsInProgress[tid] - fromIEW->iewInfo[tid].dispatchedToLSQ);
1025
1026    //DPRINTF(Rename,"[tid:%i]: %i lsq free\n",tid,num_free);
1027
1028    return num_free;
1029}
1030
1031template <class Impl>
1032unsigned
1033DefaultRename<Impl>::validInsts()
1034{
1035    unsigned inst_count = 0;
1036
1037    for (int i=0; i<fromDecode->size; i++) {
1038        if (!fromDecode->insts[i]->isSquashed())
1039            inst_count++;
1040    }
1041
1042    return inst_count;
1043}
1044
1045template <class Impl>
1046void
1047DefaultRename<Impl>::readStallSignals(unsigned tid)
1048{
1049    if (fromIEW->iewBlock[tid]) {
1050        stalls[tid].iew = true;
1051    }
1052
1053    if (fromIEW->iewUnblock[tid]) {
1054        assert(stalls[tid].iew);
1055        stalls[tid].iew = false;
1056    }
1057
1058    if (fromCommit->commitBlock[tid]) {
1059        stalls[tid].commit = true;
1060    }
1061
1062    if (fromCommit->commitUnblock[tid]) {
1063        assert(stalls[tid].commit);
1064        stalls[tid].commit = false;
1065    }
1066}
1067
1068template <class Impl>
1069bool
1070DefaultRename<Impl>::checkStall(unsigned tid)
1071{
1072    bool ret_val = false;
1073
1074    if (stalls[tid].iew) {
1075        DPRINTF(Rename,"[tid:%i]: Stall from IEW stage detected.\n", tid);
1076        ret_val = true;
1077    } else if (stalls[tid].commit) {
1078        DPRINTF(Rename,"[tid:%i]: Stall from Commit stage detected.\n", tid);
1079        ret_val = true;
1080    } else if (calcFreeROBEntries(tid) <= 0) {
1081        DPRINTF(Rename,"[tid:%i]: Stall: ROB has 0 free entries.\n", tid);
1082        ret_val = true;
1083    } else if (calcFreeIQEntries(tid) <= 0) {
1084        DPRINTF(Rename,"[tid:%i]: Stall: IQ has 0 free entries.\n", tid);
1085        ret_val = true;
1086    } else if (calcFreeLSQEntries(tid) <= 0) {
1087        DPRINTF(Rename,"[tid:%i]: Stall: LSQ has 0 free entries.\n", tid);
1088        ret_val = true;
1089    } else if (renameMap[tid]->numFreeEntries() <= 0) {
1090        DPRINTF(Rename,"[tid:%i]: Stall: RenameMap has 0 free entries.\n", tid);
1091        ret_val = true;
1092    } else if (renameStatus[tid] == SerializeStall &&
1093               (!emptyROB[tid] || instsInProgress[tid])) {
1094        DPRINTF(Rename,"[tid:%i]: Stall: Serialize stall and ROB is not "
1095                "empty.\n",
1096                tid);
1097        ret_val = true;
1098    }
1099
1100    return ret_val;
1101}
1102
1103template <class Impl>
1104void
1105DefaultRename<Impl>::readFreeEntries(unsigned tid)
1106{
1107    bool updated = false;
1108    if (fromIEW->iewInfo[tid].usedIQ) {
1109        freeEntries[tid].iqEntries =
1110            fromIEW->iewInfo[tid].freeIQEntries;
1111        updated = true;
1112    }
1113
1114    if (fromIEW->iewInfo[tid].usedLSQ) {
1115        freeEntries[tid].lsqEntries =
1116            fromIEW->iewInfo[tid].freeLSQEntries;
1117        updated = true;
1118    }
1119
1120    if (fromCommit->commitInfo[tid].usedROB) {
1121        freeEntries[tid].robEntries =
1122            fromCommit->commitInfo[tid].freeROBEntries;
1123        emptyROB[tid] = fromCommit->commitInfo[tid].emptyROB;
1124        updated = true;
1125    }
1126
1127    DPRINTF(Rename, "[tid:%i]: Free IQ: %i, Free ROB: %i, Free LSQ: %i\n",
1128            tid,
1129            freeEntries[tid].iqEntries,
1130            freeEntries[tid].robEntries,
1131            freeEntries[tid].lsqEntries);
1132
1133    DPRINTF(Rename, "[tid:%i]: %i instructions not yet in ROB\n",
1134            tid, instsInProgress[tid]);
1135}
1136
1137template <class Impl>
1138bool
1139DefaultRename<Impl>::checkSignalsAndUpdate(unsigned tid)
1140{
1141    // Check if there's a squash signal, squash if there is
1142    // Check stall signals, block if necessary.
1143    // If status was blocked
1144    //     check if stall conditions have passed
1145    //         if so then go to unblocking
1146    // If status was Squashing
1147    //     check if squashing is not high.  Switch to running this cycle.
1148    // If status was serialize stall
1149    //     check if ROB is empty and no insts are in flight to the ROB
1150
1151    readFreeEntries(tid);
1152    readStallSignals(tid);
1153
1154    if (fromCommit->commitInfo[tid].squash) {
1155        DPRINTF(Rename, "[tid:%u]: Squashing instructions due to squash from "
1156                "commit.\n", tid);
1157
1158        squash(tid);
1159
1160        return true;
1161    }
1162
1163    if (fromCommit->commitInfo[tid].robSquashing) {
1164        DPRINTF(Rename, "[tid:%u]: ROB is still squashing.\n", tid);
1165
1166        renameStatus[tid] = Squashing;
1167
1168        return true;
1169    }
1170
1171    if (checkStall(tid)) {
1172        return block(tid);
1173    }
1174
1175    if (renameStatus[tid] == Blocked) {
1176        DPRINTF(Rename, "[tid:%u]: Done blocking, switching to unblocking.\n",
1177                tid);
1178
1179        renameStatus[tid] = Unblocking;
1180
1181        unblock(tid);
1182
1183        return true;
1184    }
1185
1186    if (renameStatus[tid] == Squashing) {
1187        // Switch status to running if rename isn't being told to block or
1188        // squash this cycle.
1189        DPRINTF(Rename, "[tid:%u]: Done squashing, switching to running.\n",
1190                tid);
1191
1192        renameStatus[tid] = Running;
1193
1194        return false;
1195    }
1196
1197    if (renameStatus[tid] == SerializeStall) {
1198        // Stall ends once the ROB is free.
1199        DPRINTF(Rename, "[tid:%u]: Done with serialize stall, switching to "
1200                "unblocking.\n", tid);
1201
1202        DynInstPtr serial_inst = serializeInst[tid];
1203
1204        renameStatus[tid] = Unblocking;
1205
1206        unblock(tid);
1207
1208        DPRINTF(Rename, "[tid:%u]: Processing instruction [%lli] with "
1209                "PC %#x.\n",
1210                tid, serial_inst->seqNum, serial_inst->readPC());
1211
1212        // Put instruction into queue here.
1213        serial_inst->clearSerializeBefore();
1214
1215        if (!skidBuffer[tid].empty()) {
1216            skidBuffer[tid].push_front(serial_inst);
1217        } else {
1218            insts[tid].push_front(serial_inst);
1219        }
1220
1221        DPRINTF(Rename, "[tid:%u]: Instruction must be processed by rename."
1222                " Adding to front of list.", tid);
1223
1224        serializeInst[tid] = NULL;
1225
1226        return true;
1227    }
1228
1229    // If we've reached this point, we have not gotten any signals that
1230    // cause rename to change its status.  Rename remains the same as before.
1231    return false;
1232}
1233
1234template<class Impl>
1235void
1236DefaultRename<Impl>::serializeAfter(InstQueue &inst_list,
1237                                   unsigned tid)
1238{
1239    if (inst_list.empty()) {
1240        // Mark a bit to say that I must serialize on the next instruction.
1241        serializeOnNextInst[tid] = true;
1242        return;
1243    }
1244
1245    // Set the next instruction as serializing.
1246    inst_list.front()->setSerializeBefore();
1247}
1248
1249template <class Impl>
1250inline void
1251DefaultRename<Impl>::incrFullStat(const FullSource &source)
1252{
1253    switch (source) {
1254      case ROB:
1255        ++renameROBFullEvents;
1256        break;
1257      case IQ:
1258        ++renameIQFullEvents;
1259        break;
1260      case LSQ:
1261        ++renameLSQFullEvents;
1262        break;
1263      default:
1264        panic("Rename full stall stat should be incremented for a reason!");
1265        break;
1266    }
1267}
1268
1269template <class Impl>
1270void
1271DefaultRename<Impl>::dumpHistory()
1272{
1273    typename list<RenameHistory>::iterator buf_it;
1274
1275    for (int i = 0; i < numThreads; i++) {
1276
1277        buf_it = historyBuffer[i].begin();
1278
1279        while (buf_it != historyBuffer[i].end()) {
1280            cprintf("Seq num: %i\nArch reg: %i New phys reg: %i Old phys "
1281                    "reg: %i\n", (*buf_it).instSeqNum, (int)(*buf_it).archReg,
1282                    (int)(*buf_it).newPhysReg, (int)(*buf_it).prevPhysReg);
1283
1284            buf_it++;
1285        }
1286    }
1287}
1288