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