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