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