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