inst_queue_impl.hh revision 2336
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 <limits>
30#include <vector>
31
32#include "sim/root.hh"
33
34#include "cpu/o3/fu_pool.hh"
35#include "cpu/o3/inst_queue.hh"
36
37using namespace std;
38
39template <class Impl>
40InstructionQueue<Impl>::FUCompletion::FUCompletion(DynInstPtr &_inst,
41                                                   int fu_idx,
42                                                   InstructionQueue<Impl> *iq_ptr)
43    : Event(&mainEventQueue, Stat_Event_Pri),
44      inst(_inst), fuIdx(fu_idx), iqPtr(iq_ptr), freeFU(false)
45{
46    this->setFlags(Event::AutoDelete);
47}
48
49template <class Impl>
50void
51InstructionQueue<Impl>::FUCompletion::process()
52{
53    iqPtr->processFUCompletion(inst, freeFU ? fuIdx : -1);
54    inst = NULL;
55}
56
57
58template <class Impl>
59const char *
60InstructionQueue<Impl>::FUCompletion::description()
61{
62    return "Functional unit completion event";
63}
64
65template <class Impl>
66InstructionQueue<Impl>::InstructionQueue(Params *params)
67    : dcacheInterface(params->dcacheInterface),
68      fuPool(params->fuPool),
69      numEntries(params->numIQEntries),
70      totalWidth(params->issueWidth),
71      numPhysIntRegs(params->numPhysIntRegs),
72      numPhysFloatRegs(params->numPhysFloatRegs),
73      commitToIEWDelay(params->commitToIEWDelay)
74{
75    assert(fuPool);
76
77    switchedOut = false;
78
79    numThreads = params->numberOfThreads;
80
81    // Set the number of physical registers as the number of int + float
82    numPhysRegs = numPhysIntRegs + numPhysFloatRegs;
83
84    DPRINTF(IQ, "There are %i physical registers.\n", numPhysRegs);
85
86    //Create an entry for each physical register within the
87    //dependency graph.
88    dependGraph.resize(numPhysRegs);
89
90    // Resize the register scoreboard.
91    regScoreboard.resize(numPhysRegs);
92
93    //Initialize Mem Dependence Units
94    for (int i = 0; i < numThreads; i++) {
95        memDepUnit[i].init(params,i);
96        memDepUnit[i].setIQ(this);
97    }
98
99    resetState();
100
101    string policy = params->smtIQPolicy;
102
103    //Convert string to lowercase
104    std::transform(policy.begin(), policy.end(), policy.begin(),
105                   (int(*)(int)) tolower);
106
107    //Figure out resource sharing policy
108    if (policy == "dynamic") {
109        iqPolicy = Dynamic;
110
111        //Set Max Entries to Total ROB Capacity
112        for (int i = 0; i < numThreads; i++) {
113            maxEntries[i] = numEntries;
114        }
115
116    } else if (policy == "partitioned") {
117        iqPolicy = Partitioned;
118
119        //@todo:make work if part_amt doesnt divide evenly.
120        int part_amt = numEntries / numThreads;
121
122        //Divide ROB up evenly
123        for (int i = 0; i < numThreads; i++) {
124            maxEntries[i] = part_amt;
125        }
126
127        DPRINTF(Fetch, "IQ sharing policy set to Partitioned:"
128                "%i entries per thread.\n",part_amt);
129
130    } else if (policy == "threshold") {
131        iqPolicy = Threshold;
132
133        double threshold =  (double)params->smtIQThreshold / 100;
134
135        int thresholdIQ = (int)((double)threshold * numEntries);
136
137        //Divide up by threshold amount
138        for (int i = 0; i < numThreads; i++) {
139            maxEntries[i] = thresholdIQ;
140        }
141
142        DPRINTF(Fetch, "IQ sharing policy set to Threshold:"
143                "%i entries per thread.\n",thresholdIQ);
144   } else {
145       assert(0 && "Invalid IQ Sharing Policy.Options Are:{Dynamic,"
146              "Partitioned, Threshold}");
147   }
148}
149
150template <class Impl>
151InstructionQueue<Impl>::~InstructionQueue()
152{
153    dependGraph.reset();
154    cprintf("Nodes traversed: %i, removed: %i\n",
155            dependGraph.nodesTraversed, dependGraph.nodesRemoved);
156}
157
158template <class Impl>
159std::string
160InstructionQueue<Impl>::name() const
161{
162    return cpu->name() + ".iq";
163}
164
165template <class Impl>
166void
167InstructionQueue<Impl>::regStats()
168{
169    using namespace Stats;
170    iqInstsAdded
171        .name(name() + ".iqInstsAdded")
172        .desc("Number of instructions added to the IQ (excludes non-spec)")
173        .prereq(iqInstsAdded);
174
175    iqNonSpecInstsAdded
176        .name(name() + ".iqNonSpecInstsAdded")
177        .desc("Number of non-speculative instructions added to the IQ")
178        .prereq(iqNonSpecInstsAdded);
179
180    iqInstsIssued
181        .name(name() + ".iqInstsIssued")
182        .desc("Number of instructions issued")
183        .prereq(iqInstsIssued);
184
185    iqIntInstsIssued
186        .name(name() + ".iqIntInstsIssued")
187        .desc("Number of integer instructions issued")
188        .prereq(iqIntInstsIssued);
189
190    iqFloatInstsIssued
191        .name(name() + ".iqFloatInstsIssued")
192        .desc("Number of float instructions issued")
193        .prereq(iqFloatInstsIssued);
194
195    iqBranchInstsIssued
196        .name(name() + ".iqBranchInstsIssued")
197        .desc("Number of branch instructions issued")
198        .prereq(iqBranchInstsIssued);
199
200    iqMemInstsIssued
201        .name(name() + ".iqMemInstsIssued")
202        .desc("Number of memory instructions issued")
203        .prereq(iqMemInstsIssued);
204
205    iqMiscInstsIssued
206        .name(name() + ".iqMiscInstsIssued")
207        .desc("Number of miscellaneous instructions issued")
208        .prereq(iqMiscInstsIssued);
209
210    iqSquashedInstsIssued
211        .name(name() + ".iqSquashedInstsIssued")
212        .desc("Number of squashed instructions issued")
213        .prereq(iqSquashedInstsIssued);
214
215    iqSquashedInstsExamined
216        .name(name() + ".iqSquashedInstsExamined")
217        .desc("Number of squashed instructions iterated over during squash;"
218              " mainly for profiling")
219        .prereq(iqSquashedInstsExamined);
220
221    iqSquashedOperandsExamined
222        .name(name() + ".iqSquashedOperandsExamined")
223        .desc("Number of squashed operands that are examined and possibly "
224              "removed from graph")
225        .prereq(iqSquashedOperandsExamined);
226
227    iqSquashedNonSpecRemoved
228        .name(name() + ".iqSquashedNonSpecRemoved")
229        .desc("Number of squashed non-spec instructions that were removed")
230        .prereq(iqSquashedNonSpecRemoved);
231
232    queueResDist
233        .init(Num_OpClasses, 0, 99, 2)
234        .name(name() + ".IQ:residence:")
235        .desc("cycles from dispatch to issue")
236        .flags(total | pdf | cdf )
237        ;
238    for (int i = 0; i < Num_OpClasses; ++i) {
239        queueResDist.subname(i, opClassStrings[i]);
240    }
241    numIssuedDist
242        .init(0,totalWidth,1)
243        .name(name() + ".ISSUE:issued_per_cycle")
244        .desc("Number of insts issued each cycle")
245        .flags(pdf)
246        ;
247/*
248    dist_unissued
249        .init(Num_OpClasses+2)
250        .name(name() + ".ISSUE:unissued_cause")
251        .desc("Reason ready instruction not issued")
252        .flags(pdf | dist)
253        ;
254    for (int i=0; i < (Num_OpClasses + 2); ++i) {
255        dist_unissued.subname(i, unissued_names[i]);
256    }
257*/
258    statIssuedInstType
259        .init(numThreads,Num_OpClasses)
260        .name(name() + ".ISSUE:FU_type")
261        .desc("Type of FU issued")
262        .flags(total | pdf | dist)
263        ;
264    statIssuedInstType.ysubnames(opClassStrings);
265
266    //
267    //  How long did instructions for a particular FU type wait prior to issue
268    //
269
270    issueDelayDist
271        .init(Num_OpClasses,0,99,2)
272        .name(name() + ".ISSUE:")
273        .desc("cycles from operands ready to issue")
274        .flags(pdf | cdf)
275        ;
276
277    for (int i=0; i<Num_OpClasses; ++i) {
278        stringstream subname;
279        subname << opClassStrings[i] << "_delay";
280        issueDelayDist.subname(i, subname.str());
281    }
282
283    issueRate
284        .name(name() + ".ISSUE:rate")
285        .desc("Inst issue rate")
286        .flags(total)
287        ;
288    issueRate = iqInstsIssued / cpu->numCycles;
289/*
290    issue_stores
291        .name(name() + ".ISSUE:stores")
292        .desc("Number of stores issued")
293        .flags(total)
294        ;
295    issue_stores = exe_refs - exe_loads;
296*/
297/*
298    issue_op_rate
299        .name(name() + ".ISSUE:op_rate")
300        .desc("Operation issue rate")
301        .flags(total)
302        ;
303    issue_op_rate = issued_ops / numCycles;
304*/
305    statFuBusy
306        .init(Num_OpClasses)
307        .name(name() + ".ISSUE:fu_full")
308        .desc("attempts to use FU when none available")
309        .flags(pdf | dist)
310        ;
311    for (int i=0; i < Num_OpClasses; ++i) {
312        statFuBusy.subname(i, opClassStrings[i]);
313    }
314
315    fuBusy
316        .init(numThreads)
317        .name(name() + ".ISSUE:fu_busy_cnt")
318        .desc("FU busy when requested")
319        .flags(total)
320        ;
321
322    fuBusyRate
323        .name(name() + ".ISSUE:fu_busy_rate")
324        .desc("FU busy rate (busy events/executed inst)")
325        .flags(total)
326        ;
327    fuBusyRate = fuBusy / iqInstsIssued;
328
329    for ( int i=0; i < numThreads; i++) {
330        // Tell mem dependence unit to reg stats as well.
331        memDepUnit[i].regStats();
332    }
333}
334
335template <class Impl>
336void
337InstructionQueue<Impl>::resetState()
338{
339    //Initialize thread IQ counts
340    for (int i = 0; i <numThreads; i++) {
341        count[i] = 0;
342        instList[i].clear();
343    }
344
345    // Initialize the number of free IQ entries.
346    freeEntries = numEntries;
347
348    // Note that in actuality, the registers corresponding to the logical
349    // registers start off as ready.  However this doesn't matter for the
350    // IQ as the instruction should have been correctly told if those
351    // registers are ready in rename.  Thus it can all be initialized as
352    // unready.
353    for (int i = 0; i < numPhysRegs; ++i) {
354        regScoreboard[i] = false;
355    }
356
357    for (int i = 0; i < numThreads; ++i) {
358        squashedSeqNum[i] = 0;
359    }
360
361    for (int i = 0; i < Num_OpClasses; ++i) {
362        while (!readyInsts[i].empty())
363            readyInsts[i].pop();
364        queueOnList[i] = false;
365        readyIt[i] = listOrder.end();
366    }
367    nonSpecInsts.clear();
368    listOrder.clear();
369}
370
371template <class Impl>
372void
373InstructionQueue<Impl>::setActiveThreads(list<unsigned> *at_ptr)
374{
375    DPRINTF(IQ, "Setting active threads list pointer.\n");
376    activeThreads = at_ptr;
377}
378
379template <class Impl>
380void
381InstructionQueue<Impl>::setIssueToExecuteQueue(TimeBuffer<IssueStruct> *i2e_ptr)
382{
383    DPRINTF(IQ, "Set the issue to execute queue.\n");
384    issueToExecuteQueue = i2e_ptr;
385}
386
387template <class Impl>
388void
389InstructionQueue<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
390{
391    DPRINTF(IQ, "Set the time buffer.\n");
392    timeBuffer = tb_ptr;
393
394    fromCommit = timeBuffer->getWire(-commitToIEWDelay);
395}
396
397template <class Impl>
398void
399InstructionQueue<Impl>::switchOut()
400{
401    resetState();
402    dependGraph.reset();
403    switchedOut = true;
404    for (int i = 0; i < numThreads; ++i) {
405        memDepUnit[i].switchOut();
406    }
407}
408
409template <class Impl>
410void
411InstructionQueue<Impl>::takeOverFrom()
412{
413    switchedOut = false;
414}
415
416template <class Impl>
417int
418InstructionQueue<Impl>::entryAmount(int num_threads)
419{
420    if (iqPolicy == Partitioned) {
421        return numEntries / num_threads;
422    } else {
423        return 0;
424    }
425}
426
427
428template <class Impl>
429void
430InstructionQueue<Impl>::resetEntries()
431{
432    if (iqPolicy != Dynamic || numThreads > 1) {
433        int active_threads = (*activeThreads).size();
434
435        list<unsigned>::iterator threads  = (*activeThreads).begin();
436        list<unsigned>::iterator list_end = (*activeThreads).end();
437
438        while (threads != list_end) {
439            if (iqPolicy == Partitioned) {
440                maxEntries[*threads++] = numEntries / active_threads;
441            } else if(iqPolicy == Threshold && active_threads == 1) {
442                maxEntries[*threads++] = numEntries;
443            }
444        }
445    }
446}
447
448template <class Impl>
449unsigned
450InstructionQueue<Impl>::numFreeEntries()
451{
452    return freeEntries;
453}
454
455template <class Impl>
456unsigned
457InstructionQueue<Impl>::numFreeEntries(unsigned tid)
458{
459    return maxEntries[tid] - count[tid];
460}
461
462// Might want to do something more complex if it knows how many instructions
463// will be issued this cycle.
464template <class Impl>
465bool
466InstructionQueue<Impl>::isFull()
467{
468    if (freeEntries == 0) {
469        return(true);
470    } else {
471        return(false);
472    }
473}
474
475template <class Impl>
476bool
477InstructionQueue<Impl>::isFull(unsigned tid)
478{
479    if (numFreeEntries(tid) == 0) {
480        return(true);
481    } else {
482        return(false);
483    }
484}
485
486template <class Impl>
487bool
488InstructionQueue<Impl>::hasReadyInsts()
489{
490    if (!listOrder.empty()) {
491        return true;
492    }
493
494    for (int i = 0; i < Num_OpClasses; ++i) {
495        if (!readyInsts[i].empty()) {
496            return true;
497        }
498    }
499
500    return false;
501}
502
503template <class Impl>
504void
505InstructionQueue<Impl>::insert(DynInstPtr &new_inst)
506{
507    // Make sure the instruction is valid
508    assert(new_inst);
509
510    DPRINTF(IQ, "Adding instruction [sn:%lli] PC %#x to the IQ.\n",
511            new_inst->seqNum, new_inst->readPC());
512
513    assert(freeEntries != 0);
514
515    instList[new_inst->threadNumber].push_back(new_inst);
516
517    --freeEntries;
518
519    new_inst->setInIQ();
520
521    // Look through its source registers (physical regs), and mark any
522    // dependencies.
523    addToDependents(new_inst);
524
525    // Have this instruction set itself as the producer of its destination
526    // register(s).
527    addToProducers(new_inst);
528
529    if (new_inst->isMemRef()) {
530        memDepUnit[new_inst->threadNumber].insert(new_inst);
531    } else {
532        addIfReady(new_inst);
533    }
534
535    ++iqInstsAdded;
536
537    count[new_inst->threadNumber]++;
538
539    assert(freeEntries == (numEntries - countInsts()));
540}
541
542template <class Impl>
543void
544InstructionQueue<Impl>::insertNonSpec(DynInstPtr &new_inst)
545{
546    // @todo: Clean up this code; can do it by setting inst as unable
547    // to issue, then calling normal insert on the inst.
548
549    assert(new_inst);
550
551    nonSpecInsts[new_inst->seqNum] = new_inst;
552
553    DPRINTF(IQ, "Adding non-speculative instruction [sn:%lli] PC %#x "
554            "to the IQ.\n",
555            new_inst->seqNum, new_inst->readPC());
556
557    assert(freeEntries != 0);
558
559    instList[new_inst->threadNumber].push_back(new_inst);
560
561    --freeEntries;
562
563    new_inst->setInIQ();
564
565    // Have this instruction set itself as the producer of its destination
566    // register(s).
567    addToProducers(new_inst);
568
569    // If it's a memory instruction, add it to the memory dependency
570    // unit.
571    if (new_inst->isMemRef()) {
572        memDepUnit[new_inst->threadNumber].insertNonSpec(new_inst);
573    }
574
575    ++iqNonSpecInstsAdded;
576
577    count[new_inst->threadNumber]++;
578
579    assert(freeEntries == (numEntries - countInsts()));
580}
581
582template <class Impl>
583void
584InstructionQueue<Impl>::insertBarrier(DynInstPtr &barr_inst)
585{
586    memDepUnit[barr_inst->threadNumber].insertBarrier(barr_inst);
587
588    insertNonSpec(barr_inst);
589}
590
591template <class Impl>
592void
593InstructionQueue<Impl>::addToOrderList(OpClass op_class)
594{
595    assert(!readyInsts[op_class].empty());
596
597    ListOrderEntry queue_entry;
598
599    queue_entry.queueType = op_class;
600
601    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
602
603    ListOrderIt list_it = listOrder.begin();
604    ListOrderIt list_end_it = listOrder.end();
605
606    while (list_it != list_end_it) {
607        if ((*list_it).oldestInst > queue_entry.oldestInst) {
608            break;
609        }
610
611        list_it++;
612    }
613
614    readyIt[op_class] = listOrder.insert(list_it, queue_entry);
615    queueOnList[op_class] = true;
616}
617
618template <class Impl>
619void
620InstructionQueue<Impl>::moveToYoungerInst(ListOrderIt list_order_it)
621{
622    // Get iterator of next item on the list
623    // Delete the original iterator
624    // Determine if the next item is either the end of the list or younger
625    // than the new instruction.  If so, then add in a new iterator right here.
626    // If not, then move along.
627    ListOrderEntry queue_entry;
628    OpClass op_class = (*list_order_it).queueType;
629    ListOrderIt next_it = list_order_it;
630
631    ++next_it;
632
633    queue_entry.queueType = op_class;
634    queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
635
636    while (next_it != listOrder.end() &&
637           (*next_it).oldestInst < queue_entry.oldestInst) {
638        ++next_it;
639    }
640
641    readyIt[op_class] = listOrder.insert(next_it, queue_entry);
642}
643
644template <class Impl>
645void
646InstructionQueue<Impl>::processFUCompletion(DynInstPtr &inst, int fu_idx)
647{
648    // The CPU could have been sleeping until this op completed (*extremely*
649    // long latency op).  Wake it if it was.  This may be overkill.
650    if (isSwitchedOut()) {
651        return;
652    }
653
654    iewStage->wakeCPU();
655
656    if (fu_idx > -1)
657        fuPool->freeUnitNextCycle(fu_idx);
658
659    // @todo: Ensure that these FU Completions happen at the beginning
660    // of a cycle, otherwise they could add too many instructions to
661    // the queue.
662    // @todo: This could break if there's multiple multi-cycle ops
663    // finishing on this cycle.  Maybe implement something like
664    // instToCommit in iew_impl.hh.
665    int &size = issueToExecuteQueue->access(0)->size;
666
667    issueToExecuteQueue->access(0)->insts[size++] = inst;
668}
669
670// @todo: Figure out a better way to remove the squashed items from the
671// lists.  Checking the top item of each list to see if it's squashed
672// wastes time and forces jumps.
673template <class Impl>
674void
675InstructionQueue<Impl>::scheduleReadyInsts()
676{
677    DPRINTF(IQ, "Attempting to schedule ready instructions from "
678            "the IQ.\n");
679
680    IssueStruct *i2e_info = issueToExecuteQueue->access(0);
681
682    // Have iterator to head of the list
683    // While I haven't exceeded bandwidth or reached the end of the list,
684    // Try to get a FU that can do what this op needs.
685    // If successful, change the oldestInst to the new top of the list, put
686    // the queue in the proper place in the list.
687    // Increment the iterator.
688    // This will avoid trying to schedule a certain op class if there are no
689    // FUs that handle it.
690    ListOrderIt order_it = listOrder.begin();
691    ListOrderIt order_end_it = listOrder.end();
692    int total_issued = 0;
693    int exec_queue_slot = i2e_info->size;
694
695    while (exec_queue_slot < totalWidth && total_issued < totalWidth &&
696           order_it != order_end_it) {
697        OpClass op_class = (*order_it).queueType;
698
699        assert(!readyInsts[op_class].empty());
700
701        DynInstPtr issuing_inst = readyInsts[op_class].top();
702
703        assert(issuing_inst->seqNum == (*order_it).oldestInst);
704
705        if (issuing_inst->isSquashed()) {
706            readyInsts[op_class].pop();
707
708            if (!readyInsts[op_class].empty()) {
709                moveToYoungerInst(order_it);
710            } else {
711                readyIt[op_class] = listOrder.end();
712                queueOnList[op_class] = false;
713            }
714
715            listOrder.erase(order_it++);
716
717            ++iqSquashedInstsIssued;
718
719            continue;
720        }
721
722        int idx = -2;
723        int op_latency = 1;
724        int tid = issuing_inst->threadNumber;
725
726        if (op_class != No_OpClass) {
727            idx = fuPool->getUnit(op_class);
728
729            if (idx > -1) {
730                op_latency = fuPool->getOpLatency(op_class);
731            }
732        }
733
734        if (idx == -2 || idx != -1) {
735            if (op_latency == 1) {
736                i2e_info->insts[exec_queue_slot++] = issuing_inst;
737                i2e_info->size++;
738
739                // Add the FU onto the list of FU's to be freed next
740                // cycle if we used one.
741                if (idx >= 0)
742                    fuPool->freeUnitNextCycle(idx);
743            } else {
744                int issue_latency = fuPool->getIssueLatency(op_class);
745                // Generate completion event for the FU
746                FUCompletion *execution = new FUCompletion(issuing_inst,
747                                                           idx, this);
748
749                execution->schedule(curTick + cpu->cycles(issue_latency - 1));
750
751                // @todo: Enforce that issue_latency == 1 or op_latency
752                if (issue_latency > 1) {
753                    execution->setFreeFU();
754                } else {
755                    // @todo: Not sure I'm accounting for the
756                    // multi-cycle op in a pipelined FU properly, or
757                    // the number of instructions issued in one cycle.
758//                    i2e_info->insts[exec_queue_slot++] = issuing_inst;
759//                    i2e_info->size++;
760
761                    // Add the FU onto the list of FU's to be freed next cycle.
762                    fuPool->freeUnitNextCycle(idx);
763                }
764            }
765
766            DPRINTF(IQ, "Thread %i: Issuing instruction PC %#x "
767                    "[sn:%lli]\n",
768                    tid, issuing_inst->readPC(),
769                    issuing_inst->seqNum);
770
771            readyInsts[op_class].pop();
772
773            if (!readyInsts[op_class].empty()) {
774                moveToYoungerInst(order_it);
775            } else {
776                readyIt[op_class] = listOrder.end();
777                queueOnList[op_class] = false;
778            }
779
780            issuing_inst->setIssued();
781            ++total_issued;
782
783            if (!issuing_inst->isMemRef()) {
784                // Memory instructions can not be freed from the IQ until they
785                // complete.
786                ++freeEntries;
787                count[tid]--;
788                issuing_inst->removeInIQ();
789            } else {
790                memDepUnit[tid].issue(issuing_inst);
791            }
792
793            listOrder.erase(order_it++);
794            statIssuedInstType[tid][op_class]++;
795        } else {
796            statFuBusy[op_class]++;
797            fuBusy[tid]++;
798            ++order_it;
799        }
800    }
801
802    numIssuedDist.sample(total_issued);
803    iqInstsIssued+= total_issued;
804
805    if (total_issued) {
806        cpu->activityThisCycle();
807    } else {
808        DPRINTF(IQ, "Not able to schedule any instructions.\n");
809    }
810}
811
812template <class Impl>
813void
814InstructionQueue<Impl>::scheduleNonSpec(const InstSeqNum &inst)
815{
816    DPRINTF(IQ, "Marking nonspeculative instruction [sn:%lli] as ready "
817            "to execute.\n", inst);
818
819    NonSpecMapIt inst_it = nonSpecInsts.find(inst);
820
821    assert(inst_it != nonSpecInsts.end());
822
823    unsigned tid = (*inst_it).second->threadNumber;
824
825    (*inst_it).second->setCanIssue();
826
827    if (!(*inst_it).second->isMemRef()) {
828        addIfReady((*inst_it).second);
829    } else {
830        memDepUnit[tid].nonSpecInstReady((*inst_it).second);
831    }
832
833    (*inst_it).second = NULL;
834
835    nonSpecInsts.erase(inst_it);
836}
837
838template <class Impl>
839void
840InstructionQueue<Impl>::commit(const InstSeqNum &inst, unsigned tid)
841{
842    DPRINTF(IQ, "[tid:%i]: Committing instructions older than [sn:%i]\n",
843            tid,inst);
844
845    ListIt iq_it = instList[tid].begin();
846
847    while (iq_it != instList[tid].end() &&
848           (*iq_it)->seqNum <= inst) {
849        ++iq_it;
850        instList[tid].pop_front();
851    }
852
853    assert(freeEntries == (numEntries - countInsts()));
854}
855
856template <class Impl>
857int
858InstructionQueue<Impl>::wakeDependents(DynInstPtr &completed_inst)
859{
860    int dependents = 0;
861
862    DPRINTF(IQ, "Waking dependents of completed instruction.\n");
863
864    assert(!completed_inst->isSquashed());
865
866    // Tell the memory dependence unit to wake any dependents on this
867    // instruction if it is a memory instruction.  Also complete the memory
868    // instruction at this point since we know it executed without issues.
869    // @todo: Might want to rename "completeMemInst" to something that
870    // indicates that it won't need to be replayed, and call this
871    // earlier.  Might not be a big deal.
872    if (completed_inst->isMemRef()) {
873        memDepUnit[completed_inst->threadNumber].wakeDependents(completed_inst);
874        completeMemInst(completed_inst);
875    } else if (completed_inst->isMemBarrier() ||
876               completed_inst->isWriteBarrier()) {
877        memDepUnit[completed_inst->threadNumber].completeBarrier(completed_inst);
878    }
879
880    for (int dest_reg_idx = 0;
881         dest_reg_idx < completed_inst->numDestRegs();
882         dest_reg_idx++)
883    {
884        PhysRegIndex dest_reg =
885            completed_inst->renamedDestRegIdx(dest_reg_idx);
886
887        // Special case of uniq or control registers.  They are not
888        // handled by the IQ and thus have no dependency graph entry.
889        // @todo Figure out a cleaner way to handle this.
890        if (dest_reg >= numPhysRegs) {
891            continue;
892        }
893
894        DPRINTF(IQ, "Waking any dependents on register %i.\n",
895                (int) dest_reg);
896
897        //Go through the dependency chain, marking the registers as
898        //ready within the waiting instructions.
899        DynInstPtr dep_inst = dependGraph.pop(dest_reg);
900
901        while (dep_inst) {
902            DPRINTF(IQ, "Waking up a dependent instruction, PC%#x.\n",
903                    dep_inst->readPC());
904
905            // Might want to give more information to the instruction
906            // so that it knows which of its source registers is
907            // ready.  However that would mean that the dependency
908            // graph entries would need to hold the src_reg_idx.
909            dep_inst->markSrcRegReady();
910
911            addIfReady(dep_inst);
912
913            dep_inst = dependGraph.pop(dest_reg);
914
915            ++dependents;
916        }
917
918        // Reset the head node now that all of its dependents have
919        // been woken up.
920        assert(dependGraph.empty(dest_reg));
921        dependGraph.clearInst(dest_reg);
922
923        // Mark the scoreboard as having that register ready.
924        regScoreboard[dest_reg] = true;
925    }
926    return dependents;
927}
928
929template <class Impl>
930void
931InstructionQueue<Impl>::addReadyMemInst(DynInstPtr &ready_inst)
932{
933    OpClass op_class = ready_inst->opClass();
934
935    readyInsts[op_class].push(ready_inst);
936
937    // Will need to reorder the list if either a queue is not on the list,
938    // or it has an older instruction than last time.
939    if (!queueOnList[op_class]) {
940        addToOrderList(op_class);
941    } else if (readyInsts[op_class].top()->seqNum  <
942               (*readyIt[op_class]).oldestInst) {
943        listOrder.erase(readyIt[op_class]);
944        addToOrderList(op_class);
945    }
946
947    DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
948            "the ready list, PC %#x opclass:%i [sn:%lli].\n",
949            ready_inst->readPC(), op_class, ready_inst->seqNum);
950}
951
952template <class Impl>
953void
954InstructionQueue<Impl>::rescheduleMemInst(DynInstPtr &resched_inst)
955{
956    memDepUnit[resched_inst->threadNumber].reschedule(resched_inst);
957}
958
959template <class Impl>
960void
961InstructionQueue<Impl>::replayMemInst(DynInstPtr &replay_inst)
962{
963    memDepUnit[replay_inst->threadNumber].replay(replay_inst);
964}
965
966template <class Impl>
967void
968InstructionQueue<Impl>::completeMemInst(DynInstPtr &completed_inst)
969{
970    int tid = completed_inst->threadNumber;
971
972    DPRINTF(IQ, "Completing mem instruction PC:%#x [sn:%lli]\n",
973            completed_inst->readPC(), completed_inst->seqNum);
974
975    ++freeEntries;
976
977    completed_inst->memOpDone = true;
978
979    memDepUnit[tid].completed(completed_inst);
980
981    count[tid]--;
982}
983
984template <class Impl>
985void
986InstructionQueue<Impl>::violation(DynInstPtr &store,
987                                  DynInstPtr &faulting_load)
988{
989    memDepUnit[store->threadNumber].violation(store, faulting_load);
990}
991
992template <class Impl>
993void
994InstructionQueue<Impl>::squash(unsigned tid)
995{
996    DPRINTF(IQ, "[tid:%i]: Starting to squash instructions in "
997            "the IQ.\n", tid);
998
999    // Read instruction sequence number of last instruction out of the
1000    // time buffer.
1001    squashedSeqNum[tid] = fromCommit->commitInfo[tid].doneSeqNum;
1002
1003    // Call doSquash if there are insts in the IQ
1004    if (count[tid] > 0) {
1005        doSquash(tid);
1006    }
1007
1008    // Also tell the memory dependence unit to squash.
1009    memDepUnit[tid].squash(squashedSeqNum[tid], tid);
1010}
1011
1012template <class Impl>
1013void
1014InstructionQueue<Impl>::doSquash(unsigned tid)
1015{
1016    // Start at the tail.
1017    ListIt squash_it = instList[tid].end();
1018    --squash_it;
1019
1020    DPRINTF(IQ, "[tid:%i]: Squashing until sequence number %i!\n",
1021            tid, squashedSeqNum[tid]);
1022
1023    // Squash any instructions younger than the squashed sequence number
1024    // given.
1025    while (squash_it != instList[tid].end() &&
1026           (*squash_it)->seqNum > squashedSeqNum[tid]) {
1027
1028        DynInstPtr squashed_inst = (*squash_it);
1029
1030        // Only handle the instruction if it actually is in the IQ and
1031        // hasn't already been squashed in the IQ.
1032        if (squashed_inst->threadNumber != tid ||
1033            squashed_inst->isSquashedInIQ()) {
1034            --squash_it;
1035            continue;
1036        }
1037
1038        if (!squashed_inst->isIssued() ||
1039            (squashed_inst->isMemRef() &&
1040             !squashed_inst->memOpDone)) {
1041
1042            // Remove the instruction from the dependency list.
1043            if (!squashed_inst->isNonSpeculative() &&
1044                !squashed_inst->isStoreConditional() &&
1045                !squashed_inst->isMemBarrier() &&
1046                !squashed_inst->isWriteBarrier()) {
1047
1048                for (int src_reg_idx = 0;
1049                     src_reg_idx < squashed_inst->numSrcRegs();
1050                     src_reg_idx++)
1051                {
1052                    PhysRegIndex src_reg =
1053                        squashed_inst->renamedSrcRegIdx(src_reg_idx);
1054
1055                    // Only remove it from the dependency graph if it
1056                    // was placed there in the first place.
1057
1058                    // Instead of doing a linked list traversal, we
1059                    // can just remove these squashed instructions
1060                    // either at issue time, or when the register is
1061                    // overwritten.  The only downside to this is it
1062                    // leaves more room for error.
1063
1064                    if (!squashed_inst->isReadySrcRegIdx(src_reg_idx) &&
1065                        src_reg < numPhysRegs) {
1066                        dependGraph.remove(src_reg, squashed_inst);
1067                    }
1068
1069
1070                    ++iqSquashedOperandsExamined;
1071                }
1072            } else {
1073                NonSpecMapIt ns_inst_it =
1074                    nonSpecInsts.find(squashed_inst->seqNum);
1075                assert(ns_inst_it != nonSpecInsts.end());
1076
1077                (*ns_inst_it).second = NULL;
1078
1079                nonSpecInsts.erase(ns_inst_it);
1080
1081                ++iqSquashedNonSpecRemoved;
1082            }
1083
1084            // Might want to also clear out the head of the dependency graph.
1085
1086            // Mark it as squashed within the IQ.
1087            squashed_inst->setSquashedInIQ();
1088
1089            // @todo: Remove this hack where several statuses are set so the
1090            // inst will flow through the rest of the pipeline.
1091            squashed_inst->setIssued();
1092            squashed_inst->setCanCommit();
1093            squashed_inst->removeInIQ();
1094
1095            //Update Thread IQ Count
1096            count[squashed_inst->threadNumber]--;
1097
1098            ++freeEntries;
1099
1100            DPRINTF(IQ, "[tid:%i]: Instruction [sn:%lli] PC %#x "
1101                    "squashed.\n",
1102                    tid, squashed_inst->seqNum, squashed_inst->readPC());
1103        }
1104
1105        instList[tid].erase(squash_it--);
1106        ++iqSquashedInstsExamined;
1107    }
1108}
1109
1110template <class Impl>
1111bool
1112InstructionQueue<Impl>::addToDependents(DynInstPtr &new_inst)
1113{
1114    // Loop through the instruction's source registers, adding
1115    // them to the dependency list if they are not ready.
1116    int8_t total_src_regs = new_inst->numSrcRegs();
1117    bool return_val = false;
1118
1119    for (int src_reg_idx = 0;
1120         src_reg_idx < total_src_regs;
1121         src_reg_idx++)
1122    {
1123        // Only add it to the dependency graph if it's not ready.
1124        if (!new_inst->isReadySrcRegIdx(src_reg_idx)) {
1125            PhysRegIndex src_reg = new_inst->renamedSrcRegIdx(src_reg_idx);
1126
1127            // Check the IQ's scoreboard to make sure the register
1128            // hasn't become ready while the instruction was in flight
1129            // between stages.  Only if it really isn't ready should
1130            // it be added to the dependency graph.
1131            if (src_reg >= numPhysRegs) {
1132                continue;
1133            } else if (regScoreboard[src_reg] == false) {
1134                DPRINTF(IQ, "Instruction PC %#x has src reg %i that "
1135                        "is being added to the dependency chain.\n",
1136                        new_inst->readPC(), src_reg);
1137
1138                dependGraph.insert(src_reg, new_inst);
1139
1140                // Change the return value to indicate that something
1141                // was added to the dependency graph.
1142                return_val = true;
1143            } else {
1144                DPRINTF(IQ, "Instruction PC %#x has src reg %i that "
1145                        "became ready before it reached the IQ.\n",
1146                        new_inst->readPC(), src_reg);
1147                // Mark a register ready within the instruction.
1148                new_inst->markSrcRegReady(src_reg_idx);
1149            }
1150        }
1151    }
1152
1153    return return_val;
1154}
1155
1156template <class Impl>
1157void
1158InstructionQueue<Impl>::addToProducers(DynInstPtr &new_inst)
1159{
1160    // Nothing really needs to be marked when an instruction becomes
1161    // the producer of a register's value, but for convenience a ptr
1162    // to the producing instruction will be placed in the head node of
1163    // the dependency links.
1164    int8_t total_dest_regs = new_inst->numDestRegs();
1165
1166    for (int dest_reg_idx = 0;
1167         dest_reg_idx < total_dest_regs;
1168         dest_reg_idx++)
1169    {
1170        PhysRegIndex dest_reg = new_inst->renamedDestRegIdx(dest_reg_idx);
1171
1172        // Instructions that use the misc regs will have a reg number
1173        // higher than the normal physical registers.  In this case these
1174        // registers are not renamed, and there is no need to track
1175        // dependencies as these instructions must be executed at commit.
1176        if (dest_reg >= numPhysRegs) {
1177            continue;
1178        }
1179
1180        if (!dependGraph.empty(dest_reg)) {
1181            dependGraph.dump();
1182            panic("Dependency graph %i not empty!", dest_reg);
1183        }
1184
1185        dependGraph.setInst(dest_reg, new_inst);
1186
1187        // Mark the scoreboard to say it's not yet ready.
1188        regScoreboard[dest_reg] = false;
1189    }
1190}
1191
1192template <class Impl>
1193void
1194InstructionQueue<Impl>::addIfReady(DynInstPtr &inst)
1195{
1196    // If the instruction now has all of its source registers
1197    // available, then add it to the list of ready instructions.
1198    if (inst->readyToIssue()) {
1199
1200        //Add the instruction to the proper ready list.
1201        if (inst->isMemRef()) {
1202
1203            DPRINTF(IQ, "Checking if memory instruction can issue.\n");
1204
1205            // Message to the mem dependence unit that this instruction has
1206            // its registers ready.
1207            memDepUnit[inst->threadNumber].regsReady(inst);
1208
1209            return;
1210        }
1211
1212        OpClass op_class = inst->opClass();
1213
1214        DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
1215                "the ready list, PC %#x opclass:%i [sn:%lli].\n",
1216                inst->readPC(), op_class, inst->seqNum);
1217
1218        readyInsts[op_class].push(inst);
1219
1220        // Will need to reorder the list if either a queue is not on the list,
1221        // or it has an older instruction than last time.
1222        if (!queueOnList[op_class]) {
1223            addToOrderList(op_class);
1224        } else if (readyInsts[op_class].top()->seqNum  <
1225                   (*readyIt[op_class]).oldestInst) {
1226            listOrder.erase(readyIt[op_class]);
1227            addToOrderList(op_class);
1228        }
1229    }
1230}
1231
1232template <class Impl>
1233int
1234InstructionQueue<Impl>::countInsts()
1235{
1236    //ksewell:This works but definitely could use a cleaner write
1237    //with a more intuitive way of counting. Right now it's
1238    //just brute force ....
1239
1240#if 0
1241    int total_insts = 0;
1242
1243    for (int i = 0; i < numThreads; ++i) {
1244        ListIt count_it = instList[i].begin();
1245
1246        while (count_it != instList[i].end()) {
1247            if (!(*count_it)->isSquashed() && !(*count_it)->isSquashedInIQ()) {
1248                if (!(*count_it)->isIssued()) {
1249                    ++total_insts;
1250                } else if ((*count_it)->isMemRef() &&
1251                           !(*count_it)->memOpDone) {
1252                    // Loads that have not been marked as executed still count
1253                    // towards the total instructions.
1254                    ++total_insts;
1255                }
1256            }
1257
1258            ++count_it;
1259        }
1260    }
1261
1262    return total_insts;
1263#else
1264    return numEntries - freeEntries;
1265#endif
1266}
1267
1268template <class Impl>
1269void
1270InstructionQueue<Impl>::dumpLists()
1271{
1272    for (int i = 0; i < Num_OpClasses; ++i) {
1273        cprintf("Ready list %i size: %i\n", i, readyInsts[i].size());
1274
1275        cprintf("\n");
1276    }
1277
1278    cprintf("Non speculative list size: %i\n", nonSpecInsts.size());
1279
1280    NonSpecMapIt non_spec_it = nonSpecInsts.begin();
1281    NonSpecMapIt non_spec_end_it = nonSpecInsts.end();
1282
1283    cprintf("Non speculative list: ");
1284
1285    while (non_spec_it != non_spec_end_it) {
1286        cprintf("%#x [sn:%lli]", (*non_spec_it).second->readPC(),
1287                (*non_spec_it).second->seqNum);
1288        ++non_spec_it;
1289    }
1290
1291    cprintf("\n");
1292
1293    ListOrderIt list_order_it = listOrder.begin();
1294    ListOrderIt list_order_end_it = listOrder.end();
1295    int i = 1;
1296
1297    cprintf("List order: ");
1298
1299    while (list_order_it != list_order_end_it) {
1300        cprintf("%i OpClass:%i [sn:%lli] ", i, (*list_order_it).queueType,
1301                (*list_order_it).oldestInst);
1302
1303        ++list_order_it;
1304        ++i;
1305    }
1306
1307    cprintf("\n");
1308}
1309
1310
1311template <class Impl>
1312void
1313InstructionQueue<Impl>::dumpInsts()
1314{
1315    for (int i = 0; i < numThreads; ++i) {
1316        int num = 0;
1317        int valid_num = 0;
1318        ListIt inst_list_it = instList[i].begin();
1319
1320        while (inst_list_it != instList[i].end())
1321        {
1322            cprintf("Instruction:%i\n",
1323                    num);
1324            if (!(*inst_list_it)->isSquashed()) {
1325                if (!(*inst_list_it)->isIssued()) {
1326                    ++valid_num;
1327                    cprintf("Count:%i\n", valid_num);
1328                } else if ((*inst_list_it)->isMemRef() &&
1329                           !(*inst_list_it)->memOpDone) {
1330                    // Loads that have not been marked as executed
1331                    // still count towards the total instructions.
1332                    ++valid_num;
1333                    cprintf("Count:%i\n", valid_num);
1334                }
1335            }
1336
1337            cprintf("PC:%#x\n[sn:%lli]\n[tid:%i]\n"
1338                    "Issued:%i\nSquashed:%i\n",
1339                    (*inst_list_it)->readPC(),
1340                    (*inst_list_it)->seqNum,
1341                    (*inst_list_it)->threadNumber,
1342                    (*inst_list_it)->isIssued(),
1343                    (*inst_list_it)->isSquashed());
1344
1345            if ((*inst_list_it)->isMemRef()) {
1346                cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone);
1347            }
1348
1349            cprintf("\n");
1350
1351            inst_list_it++;
1352            ++num;
1353        }
1354    }
1355}
1356