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