regop.isa revision 6454:755cf9b6185f
1// Copyright (c) 2007-2008 The Hewlett-Packard Development Company
2// All rights reserved.
3//
4// Redistribution and use of this software in source and binary forms,
5// with or without modification, are permitted provided that the
6// following conditions are met:
7//
8// The software must be used only for Non-Commercial Use which means any
9// use which is NOT directed to receiving any direct monetary
10// compensation for, or commercial advantage from such use.  Illustrative
11// examples of non-commercial use are academic research, personal study,
12// teaching, education and corporate research & development.
13// Illustrative examples of commercial use are distributing products for
14// commercial advantage and providing services using the software for
15// commercial advantage.
16//
17// If you wish to use this software or functionality therein that may be
18// covered by patents for commercial use, please contact:
19//     Director of Intellectual Property Licensing
20//     Office of Strategy and Technology
21//     Hewlett-Packard Company
22//     1501 Page Mill Road
23//     Palo Alto, California  94304
24//
25// Redistributions of source code must retain the above copyright notice,
26// this list of conditions and the following disclaimer.  Redistributions
27// in binary form must reproduce the above copyright notice, this list of
28// conditions and the following disclaimer in the documentation and/or
29// other materials provided with the distribution.  Neither the name of
30// the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
31// contributors may be used to endorse or promote products derived from
32// this software without specific prior written permission.  No right of
33// sublicense is granted herewith.  Derivatives of the software and
34// output created using the software may be prepared, but only for
35// Non-Commercial Uses.  Derivatives of the software may be shared with
36// others provided: (i) the others agree to abide by the list of
37// conditions herein which includes the Non-Commercial Use restrictions;
38// and (ii) such Derivatives of the software include the above copyright
39// notice to acknowledge the contribution from this software where
40// applicable, this list of conditions and the disclaimer below.
41//
42// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
43// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
44// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
45// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
46// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
48// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
49// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
50// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
51// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
52// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
53//
54// Authors: Gabe Black
55
56//////////////////////////////////////////////////////////////////////////
57//
58// RegOp Microop templates
59//
60//////////////////////////////////////////////////////////////////////////
61
62def template MicroRegOpExecute {{
63        Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
64                Trace::InstRecord *traceData) const
65        {
66            Fault fault = NoFault;
67
68            DPRINTF(X86, "The data size is %d\n", dataSize);
69            %(op_decl)s;
70            %(op_rd)s;
71
72            if(%(cond_check)s)
73            {
74                %(code)s;
75                %(flag_code)s;
76            }
77            else
78            {
79                %(else_code)s;
80            }
81
82            //Write the resulting state to the execution context
83            if(fault == NoFault)
84            {
85                %(op_wb)s;
86            }
87            return fault;
88        }
89}};
90
91def template MicroRegOpImmExecute {{
92        Fault %(class_name)s::execute(%(CPU_exec_context)s *xc,
93                Trace::InstRecord *traceData) const
94        {
95            Fault fault = NoFault;
96
97            %(op_decl)s;
98            %(op_rd)s;
99
100            if(%(cond_check)s)
101            {
102                %(code)s;
103                %(flag_code)s;
104            }
105            else
106            {
107                %(else_code)s;
108            }
109
110            //Write the resulting state to the execution context
111            if(fault == NoFault)
112            {
113                %(op_wb)s;
114            }
115            return fault;
116        }
117}};
118
119def template MicroRegOpDeclare {{
120    class %(class_name)s : public %(base_class)s
121    {
122      protected:
123        void buildMe();
124
125      public:
126        %(class_name)s(ExtMachInst _machInst,
127                const char * instMnem,
128                bool isMicro, bool isDelayed, bool isFirst, bool isLast,
129                InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
130                uint8_t _dataSize, uint16_t _ext);
131
132        %(class_name)s(ExtMachInst _machInst,
133                const char * instMnem,
134                InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
135                uint8_t _dataSize, uint16_t _ext);
136
137        %(BasicExecDeclare)s
138    };
139}};
140
141def template MicroRegOpImmDeclare {{
142
143    class %(class_name)s : public %(base_class)s
144    {
145      protected:
146        void buildMe();
147
148      public:
149        %(class_name)s(ExtMachInst _machInst,
150                const char * instMnem,
151                bool isMicro, bool isDelayed, bool isFirst, bool isLast,
152                InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
153                uint8_t _dataSize, uint16_t _ext);
154
155        %(class_name)s(ExtMachInst _machInst,
156                const char * instMnem,
157                InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
158                uint8_t _dataSize, uint16_t _ext);
159
160        %(BasicExecDeclare)s
161    };
162}};
163
164def template MicroRegOpConstructor {{
165
166    inline void %(class_name)s::buildMe()
167    {
168        %(constructor)s;
169    }
170
171    inline %(class_name)s::%(class_name)s(
172            ExtMachInst machInst, const char * instMnem,
173            InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
174            uint8_t _dataSize, uint16_t _ext) :
175        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
176                false, false, false, false,
177                _src1, _src2, _dest, _dataSize, _ext,
178                %(op_class)s)
179    {
180        buildMe();
181    }
182
183    inline %(class_name)s::%(class_name)s(
184            ExtMachInst machInst, const char * instMnem,
185            bool isMicro, bool isDelayed, bool isFirst, bool isLast,
186            InstRegIndex _src1, InstRegIndex _src2, InstRegIndex _dest,
187            uint8_t _dataSize, uint16_t _ext) :
188        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
189                isMicro, isDelayed, isFirst, isLast,
190                _src1, _src2, _dest, _dataSize, _ext,
191                %(op_class)s)
192    {
193        buildMe();
194    }
195}};
196
197def template MicroRegOpImmConstructor {{
198
199    inline void %(class_name)s::buildMe()
200    {
201        %(constructor)s;
202    }
203
204    inline %(class_name)s::%(class_name)s(
205            ExtMachInst machInst, const char * instMnem,
206            InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
207            uint8_t _dataSize, uint16_t _ext) :
208        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
209                false, false, false, false,
210                _src1, _imm8, _dest, _dataSize, _ext,
211                %(op_class)s)
212    {
213        buildMe();
214    }
215
216    inline %(class_name)s::%(class_name)s(
217            ExtMachInst machInst, const char * instMnem,
218            bool isMicro, bool isDelayed, bool isFirst, bool isLast,
219            InstRegIndex _src1, uint16_t _imm8, InstRegIndex _dest,
220            uint8_t _dataSize, uint16_t _ext) :
221        %(base_class)s(machInst, "%(mnemonic)s", instMnem,
222                isMicro, isDelayed, isFirst, isLast,
223                _src1, _imm8, _dest, _dataSize, _ext,
224                %(op_class)s)
225    {
226        buildMe();
227    }
228}};
229
230output header {{
231    void
232    divide(uint64_t dividend, uint64_t divisor,
233            uint64_t &quotient, uint64_t &remainder);
234
235    enum SegmentSelectorCheck {
236      SegNoCheck, SegCSCheck, SegCallGateCheck, SegIntGateCheck,
237      SegSoftIntGateCheck, SegSSCheck, SegIretCheck, SegIntCSCheck,
238      SegTRCheck, SegTSSCheck, SegInGDTCheck, SegLDTCheck
239    };
240
241    enum LongModeDescriptorType {
242        LDT64 = 2,
243        AvailableTSS64 = 9,
244        BusyTSS64 = 0xb,
245        CallGate64 = 0xc,
246        IntGate64 = 0xe,
247        TrapGate64 = 0xf
248    };
249}};
250
251output decoder {{
252    void
253    divide(uint64_t dividend, uint64_t divisor,
254            uint64_t &quotient, uint64_t &remainder)
255    {
256        //Check for divide by zero.
257        if (divisor == 0)
258            panic("Divide by zero!\\n");
259        //If the divisor is bigger than the dividend, don't do anything.
260        if (divisor <= dividend) {
261            //Shift the divisor so it's msb lines up with the dividend.
262            int dividendMsb = findMsbSet(dividend);
263            int divisorMsb = findMsbSet(divisor);
264            int shift = dividendMsb - divisorMsb;
265            divisor <<= shift;
266            //Compute what we'll add to the quotient if the divisor isn't
267            //now larger than the dividend.
268            uint64_t quotientBit = 1;
269            quotientBit <<= shift;
270            //If we need to step back a bit (no pun intended) because the
271            //divisor got too to large, do that here. This is the "or two"
272            //part of one or two bit division.
273            if (divisor > dividend) {
274                quotientBit >>= 1;
275                divisor >>= 1;
276            }
277            //Decrement the remainder and increment the quotient.
278            quotient += quotientBit;
279            remainder -= divisor;
280        }
281    }
282}};
283
284let {{
285    # Make these empty strings so that concatenating onto
286    # them will always work.
287    header_output = ""
288    decoder_output = ""
289    exec_output = ""
290
291    immTemplates = (
292            MicroRegOpImmDeclare,
293            MicroRegOpImmConstructor,
294            MicroRegOpImmExecute)
295
296    regTemplates = (
297            MicroRegOpDeclare,
298            MicroRegOpConstructor,
299            MicroRegOpExecute)
300
301    class RegOpMeta(type):
302        def buildCppClasses(self, name, Name, suffix, \
303                code, flag_code, cond_check, else_code):
304
305            # Globals to stick the output in
306            global header_output
307            global decoder_output
308            global exec_output
309
310            # Stick all the code together so it can be searched at once
311            allCode = "|".join((code, flag_code, cond_check, else_code))
312
313            # If op2 is used anywhere, make register and immediate versions
314            # of this code.
315            matcher = re.compile("(?<!\\w)(?P<prefix>s?)op2(?P<typeQual>\\.\\w+)?")
316            match = matcher.search(allCode)
317            if match:
318                typeQual = ""
319                if match.group("typeQual"):
320                    typeQual = match.group("typeQual")
321                src2_name = "%spsrc2%s" % (match.group("prefix"), typeQual)
322                self.buildCppClasses(name, Name, suffix,
323                        matcher.sub(src2_name, code),
324                        matcher.sub(src2_name, flag_code),
325                        matcher.sub(src2_name, cond_check),
326                        matcher.sub(src2_name, else_code))
327                self.buildCppClasses(name + "i", Name, suffix + "Imm",
328                        matcher.sub("imm8", code),
329                        matcher.sub("imm8", flag_code),
330                        matcher.sub("imm8", cond_check),
331                        matcher.sub("imm8", else_code))
332                return
333
334            # If there's something optional to do with flags, generate
335            # a version without it and fix up this version to use it.
336            if flag_code != "" or cond_check != "true":
337                self.buildCppClasses(name, Name, suffix,
338                        code, "", "true", else_code)
339                suffix = "Flags" + suffix
340
341            # If psrc1 or psrc2 is used, we need to actually insert code to
342            # compute it.
343            matcher = re.compile("(?<!\w)psrc1(?!\w)")
344            if matcher.search(allCode):
345                code = "uint64_t psrc1 = pick(SrcReg1, 0, dataSize);" + code
346            matcher = re.compile("(?<!\w)psrc2(?!\w)")
347            if matcher.search(allCode):
348                code = "uint64_t psrc2 = pick(SrcReg2, 1, dataSize);" + code
349            # Also make available versions which do sign extension
350            matcher = re.compile("(?<!\w)spsrc1(?!\w)")
351            if matcher.search(allCode):
352                code = "int64_t spsrc1 = signedPick(SrcReg1, 0, dataSize);" + code
353            matcher = re.compile("(?<!\w)spsrc2(?!\w)")
354            if matcher.search(allCode):
355                code = "int64_t spsrc2 = signedPick(SrcReg2, 1, dataSize);" + code
356
357            base = "X86ISA::RegOp"
358
359            # If imm8 shows up in the code, use the immediate templates, if
360            # not, hopefully the register ones will be correct.
361            templates = regTemplates
362            matcher = re.compile("(?<!\w)imm8(?!\w)")
363            if matcher.search(allCode):
364                base += "Imm"
365                templates = immTemplates
366
367            # Get everything ready for the substitution
368            iop = InstObjParams(name, Name + suffix, base,
369                    {"code" : code,
370                     "flag_code" : flag_code,
371                     "cond_check" : cond_check,
372                     "else_code" : else_code})
373
374            # Generate the actual code (finally!)
375            header_output += templates[0].subst(iop)
376            decoder_output += templates[1].subst(iop)
377            exec_output += templates[2].subst(iop)
378
379
380        def __new__(mcls, Name, bases, dict):
381            abstract = False
382            name = Name.lower()
383            if "abstract" in dict:
384                abstract = dict['abstract']
385                del dict['abstract']
386
387            cls = super(RegOpMeta, mcls).__new__(mcls, Name, bases, dict)
388            if not abstract:
389                cls.className = Name
390                cls.base_mnemonic = name
391                code = cls.code
392                flag_code = cls.flag_code
393                cond_check = cls.cond_check
394                else_code = cls.else_code
395
396                # Set up the C++ classes
397                mcls.buildCppClasses(cls, name, Name, "",
398                        code, flag_code, cond_check, else_code)
399
400                # Hook into the microassembler dict
401                global microopClasses
402                microopClasses[name] = cls
403
404                allCode = "|".join((code, flag_code, cond_check, else_code))
405
406                # If op2 is used anywhere, make register and immediate versions
407                # of this code.
408                matcher = re.compile("op2(?P<typeQual>\\.\\w+)?")
409                if matcher.search(allCode):
410                    microopClasses[name + 'i'] = cls
411            return cls
412
413
414    class RegOp(X86Microop):
415        __metaclass__ = RegOpMeta
416        # This class itself doesn't act as a microop
417        abstract = True
418
419        # Default template parameter values
420        flag_code = ""
421        cond_check = "true"
422        else_code = ";"
423
424        def __init__(self, dest, src1, op2, flags = None, dataSize = "env.dataSize"):
425            self.dest = dest
426            self.src1 = src1
427            self.op2 = op2
428            self.flags = flags
429            self.dataSize = dataSize
430            if flags is None:
431                self.ext = 0
432            else:
433                if not isinstance(flags, (list, tuple)):
434                    raise Exception, "flags must be a list or tuple of flags"
435                self.ext = " | ".join(flags)
436                self.className += "Flags"
437
438        def getAllocator(self, *microFlags):
439            className = self.className
440            if self.mnemonic == self.base_mnemonic + 'i':
441                className += "Imm"
442            allocator = '''new %(class_name)s(machInst, macrocodeBlock
443                    %(flags)s, %(src1)s, %(op2)s, %(dest)s,
444                    %(dataSize)s, %(ext)s)''' % {
445                "class_name" : className,
446                "flags" : self.microFlagsText(microFlags),
447                "src1" : self.src1, "op2" : self.op2,
448                "dest" : self.dest,
449                "dataSize" : self.dataSize,
450                "ext" : self.ext}
451            return allocator
452
453    class LogicRegOp(RegOp):
454        abstract = True
455        flag_code = '''
456            //Don't have genFlags handle the OF or CF bits
457            uint64_t mask = CFBit | ECFBit | OFBit;
458            ccFlagBits = genFlags(ccFlagBits, ext & ~mask, DestReg, psrc1, op2);
459            //If a logic microop wants to set these, it wants to set them to 0.
460            ccFlagBits &= ~(CFBit & ext);
461            ccFlagBits &= ~(ECFBit & ext);
462            ccFlagBits &= ~(OFBit & ext);
463        '''
464
465    class FlagRegOp(RegOp):
466        abstract = True
467        flag_code = \
468            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, op2);"
469
470    class SubRegOp(RegOp):
471        abstract = True
472        flag_code = \
473            "ccFlagBits = genFlags(ccFlagBits, ext, DestReg, psrc1, ~op2, true);"
474
475    class CondRegOp(RegOp):
476        abstract = True
477        cond_check = "checkCondition(ccFlagBits, ext)"
478
479    class RdRegOp(RegOp):
480        abstract = True
481        def __init__(self, dest, src1=None, dataSize="env.dataSize"):
482            if not src1:
483                src1 = dest
484            super(RdRegOp, self).__init__(dest, src1, \
485                    "InstRegIndex(NUM_INTREGS)", None, dataSize)
486
487    class WrRegOp(RegOp):
488        abstract = True
489        def __init__(self, src1, src2, flags=None, dataSize="env.dataSize"):
490            super(WrRegOp, self).__init__("InstRegIndex(NUM_INTREGS)", \
491                    src1, src2, flags, dataSize)
492
493    class Add(FlagRegOp):
494        code = 'DestReg = merge(DestReg, psrc1 + op2, dataSize);'
495
496    class Or(LogicRegOp):
497        code = 'DestReg = merge(DestReg, psrc1 | op2, dataSize);'
498
499    class Adc(FlagRegOp):
500        code = '''
501            CCFlagBits flags = ccFlagBits;
502            DestReg = merge(DestReg, psrc1 + op2 + flags.cf, dataSize);
503            '''
504
505    class Sbb(SubRegOp):
506        code = '''
507            CCFlagBits flags = ccFlagBits;
508            DestReg = merge(DestReg, psrc1 - op2 - flags.cf, dataSize);
509            '''
510
511    class And(LogicRegOp):
512        code = 'DestReg = merge(DestReg, psrc1 & op2, dataSize)'
513
514    class Sub(SubRegOp):
515        code = 'DestReg = merge(DestReg, psrc1 - op2, dataSize)'
516
517    class Xor(LogicRegOp):
518        code = 'DestReg = merge(DestReg, psrc1 ^ op2, dataSize)'
519
520    class Mul1s(WrRegOp):
521        code = '''
522            ProdLow = psrc1 * op2;
523            int halfSize = (dataSize * 8) / 2;
524            uint64_t shifter = (1ULL << halfSize);
525            uint64_t hiResult;
526            uint64_t psrc1_h = psrc1 / shifter;
527            uint64_t psrc1_l = psrc1 & mask(halfSize);
528            uint64_t psrc2_h = op2 / shifter;
529            uint64_t psrc2_l = op2 & mask(halfSize);
530            hiResult = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
531                        ((psrc1_l * psrc2_l) / shifter)) /shifter) +
532                       psrc1_h * psrc2_h;
533            if (spsrc1 < 0)
534                hiResult -= op2;
535            int64_t bigSop2 = sop2;
536            if (bigSop2 < 0)
537                hiResult -= psrc1;
538            ProdHi = hiResult;
539            '''
540
541    class Mul1u(WrRegOp):
542        code = '''
543            ProdLow = psrc1 * op2;
544            int halfSize = (dataSize * 8) / 2;
545            uint64_t shifter = (1ULL << halfSize);
546            uint64_t psrc1_h = psrc1 / shifter;
547            uint64_t psrc1_l = psrc1 & mask(halfSize);
548            uint64_t psrc2_h = op2 / shifter;
549            uint64_t psrc2_l = op2 & mask(halfSize);
550            ProdHi = ((psrc1_l * psrc2_h + psrc1_h * psrc2_l +
551                      ((psrc1_l * psrc2_l) / shifter)) / shifter) +
552                     psrc1_h * psrc2_h;
553            '''
554
555    class Mulel(RdRegOp):
556        code = 'DestReg = merge(SrcReg1, ProdLow, dataSize);'
557
558    class Muleh(RdRegOp):
559        def __init__(self, dest, src1=None, flags=None, dataSize="env.dataSize"):
560            if not src1:
561                src1 = dest
562            super(RdRegOp, self).__init__(dest, src1, \
563                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
564        code = 'DestReg = merge(SrcReg1, ProdHi, dataSize);'
565        flag_code = '''
566            if (ProdHi)
567                ccFlagBits = ccFlagBits | (ext & (CFBit | OFBit | ECFBit));
568            else
569                ccFlagBits = ccFlagBits & ~(ext & (CFBit | OFBit | ECFBit));
570        '''
571
572    # One or two bit divide
573    class Div1(WrRegOp):
574        code = '''
575            //These are temporaries so that modifying them later won't make
576            //the ISA parser think they're also sources.
577            uint64_t quotient = 0;
578            uint64_t remainder = psrc1;
579            //Similarly, this is a temporary so changing it doesn't make it
580            //a source.
581            uint64_t divisor = op2;
582            //This is a temporary just for consistency and clarity.
583            uint64_t dividend = remainder;
584            //Do the division.
585            divide(dividend, divisor, quotient, remainder);
586            //Record the final results.
587            Remainder = remainder;
588            Quotient = quotient;
589            Divisor = divisor;
590            '''
591
592    # Step divide
593    class Div2(RegOp):
594        code = '''
595            uint64_t dividend = Remainder;
596            uint64_t divisor = Divisor;
597            uint64_t quotient = Quotient;
598            uint64_t remainder = dividend;
599            int remaining = op2;
600            //If we overshot, do nothing. This lets us unrool division loops a
601            //little.
602            if (remaining) {
603                //Shift in bits from the low order portion of the dividend
604                while(dividend < divisor && remaining) {
605                    dividend = (dividend << 1) | bits(SrcReg1, remaining - 1);
606                    quotient <<= 1;
607                    remaining--;
608                }
609                remainder = dividend;
610                //Do the division.
611                divide(dividend, divisor, quotient, remainder);
612            }
613            //Keep track of how many bits there are still to pull in.
614            DestReg = merge(DestReg, remaining, dataSize);
615            //Record the final results
616            Remainder = remainder;
617            Quotient = quotient;
618        '''
619        flag_code = '''
620            if (DestReg == 0)
621                ccFlagBits = ccFlagBits | (ext & EZFBit);
622            else
623                ccFlagBits = ccFlagBits & ~(ext & EZFBit);
624        '''
625
626    class Divq(RdRegOp):
627        code = 'DestReg = merge(SrcReg1, Quotient, dataSize);'
628
629    class Divr(RdRegOp):
630        code = 'DestReg = merge(SrcReg1, Remainder, dataSize);'
631
632    class Mov(CondRegOp):
633        code = 'DestReg = merge(SrcReg1, op2, dataSize)'
634        else_code = 'DestReg=DestReg;'
635
636    # Shift instructions
637
638    class Sll(RegOp):
639        code = '''
640            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
641            DestReg = merge(DestReg, psrc1 << shiftAmt, dataSize);
642            '''
643        flag_code = '''
644            // If the shift amount is zero, no flags should be modified.
645            if (shiftAmt) {
646                //Zero out any flags we might modify. This way we only have to
647                //worry about setting them.
648                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
649                int CFBits = 0;
650                //Figure out if we -would- set the CF bits if requested.
651                if (shiftAmt <= dataSize * 8 &&
652                        bits(SrcReg1, dataSize * 8 - shiftAmt)) {
653                    CFBits = 1;
654                }
655                //If some combination of the CF bits need to be set, set them.
656                if ((ext & (CFBit | ECFBit)) && CFBits)
657                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
658                //Figure out what the OF bit should be.
659                if ((ext & OFBit) && (CFBits ^ bits(DestReg, dataSize * 8 - 1)))
660                    ccFlagBits = ccFlagBits | OFBit;
661                //Use the regular mechanisms to calculate the other flags.
662                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
663                        DestReg, psrc1, op2);
664            }
665        '''
666
667    class Srl(RegOp):
668        code = '''
669            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
670            // Because what happens to the bits shift -in- on a right shift
671            // is not defined in the C/C++ standard, we have to mask them out
672            // to be sure they're zero.
673            uint64_t logicalMask = mask(dataSize * 8 - shiftAmt);
674            DestReg = merge(DestReg, (psrc1 >> shiftAmt) & logicalMask, dataSize);
675            '''
676        flag_code = '''
677            // If the shift amount is zero, no flags should be modified.
678            if (shiftAmt) {
679                //Zero out any flags we might modify. This way we only have to
680                //worry about setting them.
681                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
682                //If some combination of the CF bits need to be set, set them.
683                if ((ext & (CFBit | ECFBit)) && 
684                        shiftAmt <= dataSize * 8 &&
685                        bits(SrcReg1, shiftAmt - 1)) {
686                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
687                }
688                //Figure out what the OF bit should be.
689                if ((ext & OFBit) && bits(SrcReg1, dataSize * 8 - 1))
690                    ccFlagBits = ccFlagBits | OFBit;
691                //Use the regular mechanisms to calculate the other flags.
692                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
693                        DestReg, psrc1, op2);
694            }
695        '''
696
697    class Sra(RegOp):
698        code = '''
699            uint8_t shiftAmt = (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
700            // Because what happens to the bits shift -in- on a right shift
701            // is not defined in the C/C++ standard, we have to sign extend
702            // them manually to be sure.
703            uint64_t arithMask = (shiftAmt == 0) ? 0 :
704                -bits(psrc1, dataSize * 8 - 1) << (dataSize * 8 - shiftAmt);
705            DestReg = merge(DestReg, (psrc1 >> shiftAmt) | arithMask, dataSize);
706            '''
707        flag_code = '''
708            // If the shift amount is zero, no flags should be modified.
709            if (shiftAmt) {
710                //Zero out any flags we might modify. This way we only have to
711                //worry about setting them.
712                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
713                //If some combination of the CF bits need to be set, set them.
714                uint8_t effectiveShift =
715                    (shiftAmt <= dataSize * 8) ? shiftAmt : (dataSize * 8);
716                if ((ext & (CFBit | ECFBit)) &&
717                        bits(SrcReg1, effectiveShift - 1)) {
718                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
719                }
720                //Use the regular mechanisms to calculate the other flags.
721                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
722                        DestReg, psrc1, op2);
723            }
724        '''
725
726    class Ror(RegOp):
727        code = '''
728            uint8_t shiftAmt =
729                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
730            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
731            if(realShiftAmt)
732            {
733                uint64_t top = psrc1 << (dataSize * 8 - realShiftAmt);
734                uint64_t bottom = bits(psrc1, dataSize * 8, realShiftAmt);
735                DestReg = merge(DestReg, top | bottom, dataSize);
736            }
737            else
738                DestReg = merge(DestReg, DestReg, dataSize);
739            '''
740        flag_code = '''
741            // If the shift amount is zero, no flags should be modified.
742            if (shiftAmt) {
743                //Zero out any flags we might modify. This way we only have to
744                //worry about setting them.
745                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
746                //Find the most and second most significant bits of the result.
747                int msb = bits(DestReg, dataSize * 8 - 1);
748                int smsb = bits(DestReg, dataSize * 8 - 2);
749                //If some combination of the CF bits need to be set, set them.
750                if ((ext & (CFBit | ECFBit)) && msb)
751                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
752                //Figure out what the OF bit should be.
753                if ((ext & OFBit) && (msb ^ smsb))
754                    ccFlagBits = ccFlagBits | OFBit;
755                //Use the regular mechanisms to calculate the other flags.
756                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
757                        DestReg, psrc1, op2);
758            }
759        '''
760
761    class Rcr(RegOp):
762        code = '''
763            uint8_t shiftAmt =
764                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
765            uint8_t realShiftAmt = shiftAmt % (dataSize * 8 + 1);
766            if(realShiftAmt)
767            {
768                CCFlagBits flags = ccFlagBits;
769                uint64_t top = flags.cf << (dataSize * 8 - realShiftAmt);
770                if (realShiftAmt > 1)
771                    top |= psrc1 << (dataSize * 8 - realShiftAmt + 1);
772                uint64_t bottom = bits(psrc1, dataSize * 8 - 1, realShiftAmt);
773                DestReg = merge(DestReg, top | bottom, dataSize);
774            }
775            else
776                DestReg = merge(DestReg, DestReg, dataSize);
777            '''
778        flag_code = '''
779            // If the shift amount is zero, no flags should be modified.
780            if (shiftAmt) {
781                int origCFBit = (ccFlagBits & CFBit) ? 1 : 0;
782                //Zero out any flags we might modify. This way we only have to
783                //worry about setting them.
784                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
785                //Figure out what the OF bit should be.
786                if ((ext & OFBit) && (origCFBit ^
787                                      bits(SrcReg1, dataSize * 8 - 1))) {
788                    ccFlagBits = ccFlagBits | OFBit;
789                }
790                //If some combination of the CF bits need to be set, set them.
791                if ((ext & (CFBit | ECFBit)) &&
792                        (realShiftAmt == 0) ? origCFBit :
793                        bits(SrcReg1, realShiftAmt - 1)) {
794                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
795                }
796                //Use the regular mechanisms to calculate the other flags.
797                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
798                        DestReg, psrc1, op2);
799            }
800        '''
801
802    class Rol(RegOp):
803        code = '''
804            uint8_t shiftAmt =
805                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
806            uint8_t realShiftAmt = shiftAmt % (dataSize * 8);
807            if(realShiftAmt)
808            {
809                uint64_t top = psrc1 << realShiftAmt;
810                uint64_t bottom =
811                    bits(psrc1, dataSize * 8 - 1, dataSize * 8 - realShiftAmt);
812                DestReg = merge(DestReg, top | bottom, dataSize);
813            }
814            else
815                DestReg = merge(DestReg, DestReg, dataSize);
816            '''
817        flag_code = '''
818            // If the shift amount is zero, no flags should be modified.
819            if (shiftAmt) {
820                //Zero out any flags we might modify. This way we only have to
821                //worry about setting them.
822                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
823                //The CF bits, if set, would be set to the lsb of the result.
824                int lsb = DestReg & 0x1;
825                int msb = bits(DestReg, dataSize * 8 - 1);
826                //If some combination of the CF bits need to be set, set them.
827                if ((ext & (CFBit | ECFBit)) && lsb)
828                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
829                //Figure out what the OF bit should be.
830                if ((ext & OFBit) && (msb ^ lsb))
831                    ccFlagBits = ccFlagBits | OFBit;
832                //Use the regular mechanisms to calculate the other flags.
833                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
834                        DestReg, psrc1, op2);
835            }
836        '''
837
838    class Rcl(RegOp):
839        code = '''
840            uint8_t shiftAmt =
841                (op2 & ((dataSize == 8) ? mask(6) : mask(5)));
842            if(shiftAmt)
843            {
844                CCFlagBits flags = ccFlagBits;
845                uint64_t top = psrc1 << shiftAmt;
846                uint64_t bottom = flags.cf << (shiftAmt - 1);
847                if(shiftAmt > 1)
848                    bottom |=
849                        bits(psrc1, dataSize * 8 - 1,
850                                   dataSize * 8 - shiftAmt + 1);
851                DestReg = merge(DestReg, top | bottom, dataSize);
852            }
853            else
854                DestReg = merge(DestReg, DestReg, dataSize);
855            '''
856        flag_code = '''
857            // If the shift amount is zero, no flags should be modified.
858            if (shiftAmt) {
859                //Zero out any flags we might modify. This way we only have to
860                //worry about setting them.
861                ccFlagBits = ccFlagBits & ~(ext & (CFBit | ECFBit | OFBit));
862                int msb = bits(DestReg, dataSize * 8 - 1);
863                int CFBits = bits(SrcReg1, dataSize * 8 - shiftAmt);
864                //If some combination of the CF bits need to be set, set them.
865                if ((ext & (CFBit | ECFBit)) && CFBits)
866                    ccFlagBits = ccFlagBits | (ext & (CFBit | ECFBit));
867                //Figure out what the OF bit should be.
868                if ((ext & OFBit) && (msb ^ CFBits))
869                    ccFlagBits = ccFlagBits | OFBit;
870                //Use the regular mechanisms to calculate the other flags.
871                ccFlagBits = genFlags(ccFlagBits, ext & ~(CFBit | ECFBit | OFBit),
872                        DestReg, psrc1, op2);
873            }
874        '''
875
876    class Wrip(WrRegOp, CondRegOp):
877        code = 'RIP = psrc1 + sop2 + CSBase'
878        else_code="RIP = RIP;"
879
880    class Wruflags(WrRegOp):
881        code = 'ccFlagBits = psrc1 ^ op2'
882
883    class Wrflags(WrRegOp):
884        code = '''
885            MiscReg newFlags = psrc1 ^ op2;
886            MiscReg userFlagMask = 0xDD5;
887            // Get only the user flags
888            ccFlagBits = newFlags & userFlagMask;
889            // Get everything else
890            nccFlagBits = newFlags & ~userFlagMask;
891        '''
892
893    class Rdip(RdRegOp):
894        code = 'DestReg = RIP - CSBase'
895
896    class Ruflags(RdRegOp):
897        code = 'DestReg = ccFlagBits'
898
899    class Rflags(RdRegOp):
900        code = 'DestReg = ccFlagBits | nccFlagBits'
901
902    class Ruflag(RegOp):
903        code = '''
904            int flag = bits(ccFlagBits, imm8);
905            DestReg = merge(DestReg, flag, dataSize);
906            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
907                                       (ccFlagBits & ~EZFBit);
908            '''
909        def __init__(self, dest, imm, flags=None, \
910                dataSize="env.dataSize"):
911            super(Ruflag, self).__init__(dest, \
912                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
913
914    class Rflag(RegOp):
915        code = '''
916            MiscReg flagMask = 0x3F7FDD5;
917            MiscReg flags = (nccFlagBits | ccFlagBits) & flagMask;
918            int flag = bits(flags, imm8);
919            DestReg = merge(DestReg, flag, dataSize);
920            ccFlagBits = (flag == 0) ? (ccFlagBits | EZFBit) :
921                                       (ccFlagBits & ~EZFBit);
922            '''
923        def __init__(self, dest, imm, flags=None, \
924                dataSize="env.dataSize"):
925            super(Rflag, self).__init__(dest, \
926                    "InstRegIndex(NUM_INTREGS)", imm, flags, dataSize)
927
928    class Sext(RegOp):
929        code = '''
930            IntReg val = psrc1;
931            // Mask the bit position so that it wraps.
932            int bitPos = op2 & (dataSize * 8 - 1);
933            int sign_bit = bits(val, bitPos, bitPos);
934            uint64_t maskVal = mask(bitPos+1);
935            val = sign_bit ? (val | ~maskVal) : (val & maskVal);
936            DestReg = merge(DestReg, val, dataSize);
937            '''
938        flag_code = '''
939            if (!sign_bit)
940                ccFlagBits = ccFlagBits &
941                    ~(ext & (CFBit | ECFBit | ZFBit | EZFBit));
942            else
943                ccFlagBits = ccFlagBits |
944                    (ext & (CFBit | ECFBit | ZFBit | EZFBit));
945            '''
946
947    class Zext(RegOp):
948        code = 'DestReg = merge(DestReg, bits(psrc1, op2, 0), dataSize);'
949
950    class Rddr(RegOp):
951        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
952            super(Rddr, self).__init__(dest, \
953                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
954        code = '''
955            CR4 cr4 = CR4Op;
956            DR7 dr7 = DR7Op;
957            if ((cr4.de == 1 && (src1 == 4 || src1 == 5)) || src1 >= 8) {
958                fault = new InvalidOpcode();
959            } else if (dr7.gd) {
960                fault = new DebugException();
961            } else {
962                DestReg = merge(DestReg, DebugSrc1, dataSize);
963            }
964        '''
965
966    class Wrdr(RegOp):
967        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
968            super(Wrdr, self).__init__(dest, \
969                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
970        code = '''
971            CR4 cr4 = CR4Op;
972            DR7 dr7 = DR7Op;
973            if ((cr4.de == 1 && (dest == 4 || dest == 5)) || dest >= 8) {
974                fault = new InvalidOpcode();
975            } else if ((dest == 6 || dest == 7) && bits(psrc1, 63, 32) &&
976                    machInst.mode.mode == LongMode) {
977                fault = new GeneralProtection(0);
978            } else if (dr7.gd) {
979                fault = new DebugException();
980            } else {
981                DebugDest = psrc1;
982            }
983        '''
984
985    class Rdcr(RegOp):
986        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
987            super(Rdcr, self).__init__(dest, \
988                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
989        code = '''
990            if (src1 == 1 || (src1 > 4 && src1 < 8) || (src1 > 8)) {
991                fault = new InvalidOpcode();
992            } else {
993                DestReg = merge(DestReg, ControlSrc1, dataSize);
994            }
995        '''
996
997    class Wrcr(RegOp):
998        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
999            super(Wrcr, self).__init__(dest, \
1000                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1001        code = '''
1002            if (dest == 1 || (dest > 4 && dest < 8) || (dest > 8)) {
1003                fault = new InvalidOpcode();
1004            } else {
1005                // There are *s in the line below so it doesn't confuse the
1006                // parser. They may be unnecessary.
1007                //Mis*cReg old*Val = pick(Cont*rolDest, 0, dat*aSize);
1008                MiscReg newVal = psrc1;
1009
1010                // Check for any modifications that would cause a fault.
1011                switch(dest) {
1012                  case 0:
1013                    {
1014                        Efer efer = EferOp;
1015                        CR0 cr0 = newVal;
1016                        CR4 oldCr4 = CR4Op;
1017                        if (bits(newVal, 63, 32) ||
1018                                (!cr0.pe && cr0.pg) ||
1019                                (!cr0.cd && cr0.nw) ||
1020                                (cr0.pg && efer.lme && !oldCr4.pae))
1021                            fault = new GeneralProtection(0);
1022                    }
1023                    break;
1024                  case 2:
1025                    break;
1026                  case 3:
1027                    break;
1028                  case 4:
1029                    {
1030                        CR4 cr4 = newVal;
1031                        // PAE can't be disabled in long mode.
1032                        if (bits(newVal, 63, 11) ||
1033                                (machInst.mode.mode == LongMode && !cr4.pae))
1034                            fault = new GeneralProtection(0);
1035                    }
1036                    break;
1037                  case 8:
1038                    {
1039                        if (bits(newVal, 63, 4))
1040                            fault = new GeneralProtection(0);
1041                    }
1042                  default:
1043                    panic("Unrecognized control register %d.\\n", dest);
1044                }
1045                ControlDest = newVal;
1046            }
1047            '''
1048
1049    # Microops for manipulating segmentation registers
1050    class SegOp(CondRegOp):
1051        abstract = True
1052        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1053            super(SegOp, self).__init__(dest, \
1054                    src1, "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1055
1056    class Wrbase(SegOp):
1057        code = '''
1058            SegBaseDest = psrc1;
1059        '''
1060
1061    class Wrlimit(SegOp):
1062        code = '''
1063            SegLimitDest = psrc1;
1064        '''
1065
1066    class Wrsel(SegOp):
1067        code = '''
1068            SegSelDest = psrc1;
1069        '''
1070
1071    class WrAttr(SegOp):
1072        code = '''
1073            SegAttrDest = psrc1;
1074        '''
1075
1076    class Rdbase(SegOp):
1077        code = '''
1078            DestReg = merge(DestReg, SegBaseSrc1, dataSize);
1079        '''
1080
1081    class Rdlimit(SegOp):
1082        code = '''
1083            DestReg = merge(DestReg, SegLimitSrc1, dataSize);
1084        '''
1085
1086    class RdAttr(SegOp):
1087        code = '''
1088            DestReg = merge(DestReg, SegAttrSrc1, dataSize);
1089        '''
1090
1091    class Rdsel(SegOp):
1092        code = '''
1093            DestReg = merge(DestReg, SegSelSrc1, dataSize);
1094        '''
1095
1096    class Rdval(RegOp):
1097        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1098            super(Rdval, self).__init__(dest, src1, \
1099                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1100        code = '''
1101            DestReg = MiscRegSrc1;
1102        '''
1103
1104    class Wrval(RegOp):
1105        def __init__(self, dest, src1, flags=None, dataSize="env.dataSize"):
1106            super(Wrval, self).__init__(dest, src1, \
1107                    "InstRegIndex(NUM_INTREGS)", flags, dataSize)
1108        code = '''
1109            MiscRegDest = SrcReg1;
1110        '''
1111
1112    class Chks(RegOp):
1113        def __init__(self, dest, src1, src2=0,
1114                flags=None, dataSize="env.dataSize"):
1115            super(Chks, self).__init__(dest,
1116                    src1, src2, flags, dataSize)
1117        code = '''
1118            // The selector is in source 1 and can be at most 16 bits.
1119            SegSelector selector = DestReg;
1120            SegDescriptor desc = SrcReg1;
1121            HandyM5Reg m5reg = M5Reg;
1122
1123            switch (imm8)
1124            {
1125              case SegNoCheck:
1126                break;
1127              case SegCSCheck:
1128                // Make sure it's the right type
1129                if (desc.s == 0 || desc.type.codeOrData != 1) {
1130                    fault = new GeneralProtection(0);
1131                } else if (m5reg.cpl != desc.dpl) {
1132                    fault = new GeneralProtection(0);
1133                }
1134                break;
1135              case SegCallGateCheck:
1136                panic("CS checks for far calls/jumps through call gates"
1137                        "not implemented.\\n");
1138                break;
1139              case SegSoftIntGateCheck:
1140                // Check permissions.
1141                if (desc.dpl < m5reg.cpl) {
1142                    fault = new GeneralProtection(selector);
1143                    break;
1144                }
1145                // Fall through on purpose
1146              case SegIntGateCheck:
1147                // Make sure the gate's the right type.
1148                if ((m5reg.mode == LongMode && (desc.type & 0xe) != 0xe) ||
1149                        ((desc.type & 0x6) != 0x6)) {
1150                    fault = new GeneralProtection(0);
1151                }
1152                break;
1153              case SegSSCheck:
1154                if (selector.si || selector.ti) {
1155                    if (!desc.p) {
1156                        fault = new StackFault(selector);
1157                    }
1158                } else {
1159                    if ((m5reg.submode != SixtyFourBitMode ||
1160                                m5reg.cpl == 3) ||
1161                            !(desc.s == 1 &&
1162                            desc.type.codeOrData == 0 && desc.type.w) ||
1163                            (desc.dpl != m5reg.cpl) ||
1164                            (selector.rpl != m5reg.cpl)) {
1165                        fault = new GeneralProtection(selector);
1166                    }
1167                }
1168                break;
1169              case SegIretCheck:
1170                {
1171                    if ((!selector.si && !selector.ti) ||
1172                            (selector.rpl < m5reg.cpl) ||
1173                            !(desc.s == 1 && desc.type.codeOrData == 1) ||
1174                            (!desc.type.c && desc.dpl != selector.rpl) ||
1175                            (desc.type.c && desc.dpl > selector.rpl)) {
1176                        fault = new GeneralProtection(selector);
1177                    } else if (!desc.p) {
1178                        fault = new SegmentNotPresent(selector);
1179                    }
1180                    break;
1181                }
1182              case SegIntCSCheck:
1183                if (m5reg.mode == LongMode) {
1184                    if (desc.l != 1 || desc.d != 0) {
1185                        fault = new GeneralProtection(selector);
1186                    }
1187                } else {
1188                    panic("Interrupt CS checks not implemented "
1189                            "in legacy mode.\\n");
1190                }
1191                break;
1192              case SegTRCheck:
1193                if (!selector.si || selector.ti) {
1194                    fault = new GeneralProtection(selector);
1195                }
1196                break;
1197              case SegTSSCheck:
1198                if (!desc.p) {
1199                    fault = new SegmentNotPresent(selector);
1200                } else if (!(desc.type == 0x9 ||
1201                        (desc.type == 1 &&
1202                         m5reg.mode != LongMode))) {
1203                    fault = new GeneralProtection(selector);
1204                }
1205                break;
1206              case SegInGDTCheck:
1207                if (selector.ti) {
1208                    fault = new GeneralProtection(selector);
1209                }
1210                break;
1211              case SegLDTCheck:
1212                if (!desc.p) {
1213                    fault = new SegmentNotPresent(selector);
1214                } else if (desc.type != 0x2) {
1215                    fault = new GeneralProtection(selector);
1216                }
1217                break;
1218              default:
1219                panic("Undefined segment check type.\\n");
1220            }
1221        '''
1222        flag_code = '''
1223            // Check for a NULL selector and set ZF,EZF appropriately.
1224            ccFlagBits = ccFlagBits & ~(ext & (ZFBit | EZFBit));
1225            if (!selector.si && !selector.ti)
1226                ccFlagBits = ccFlagBits | (ext & (ZFBit | EZFBit));
1227        '''
1228
1229    class Wrdh(RegOp):
1230        code = '''
1231            SegDescriptor desc = SrcReg1;
1232
1233            uint64_t target = bits(SrcReg2, 31, 0) << 32;
1234            switch(desc.type) {
1235              case LDT64:
1236              case AvailableTSS64:
1237              case BusyTSS64:
1238                replaceBits(target, 23, 0, desc.baseLow);
1239                replaceBits(target, 31, 24, desc.baseHigh);
1240                break;
1241              case CallGate64:
1242              case IntGate64:
1243              case TrapGate64:
1244                replaceBits(target, 15, 0, bits(desc, 15, 0));
1245                replaceBits(target, 31, 16, bits(desc, 63, 48));
1246                break;
1247              default:
1248                panic("Wrdh used with wrong descriptor type!\\n");
1249            }
1250            DestReg = target;
1251        '''
1252
1253    class Wrtsc(WrRegOp):
1254        code = '''
1255            TscOp = psrc1;
1256        '''
1257
1258    class Rdtsc(RdRegOp):
1259        code = '''
1260            DestReg = TscOp;
1261        '''
1262
1263    class Rdm5reg(RdRegOp):
1264        code = '''
1265            DestReg = M5Reg;
1266        '''
1267
1268    class Wrdl(RegOp):
1269        code = '''
1270            SegDescriptor desc = SrcReg1;
1271            SegSelector selector = SrcReg2;
1272            if (selector.si || selector.ti) {
1273                if (!desc.p)
1274                    panic("Segment not present.\\n");
1275                SegAttr attr = 0;
1276                attr.dpl = desc.dpl;
1277                attr.unusable = 0;
1278                attr.defaultSize = desc.d;
1279                attr.longMode = desc.l;
1280                attr.avl = desc.avl;
1281                attr.granularity = desc.g;
1282                attr.present = desc.p;
1283                attr.system = desc.s;
1284                attr.type = desc.type;
1285                if (!desc.s) {
1286                    // The expand down bit happens to be set for gates.
1287                    if (desc.type.e) {
1288                        panic("Gate descriptor encountered.\\n");
1289                    }
1290                    attr.readable = 1;
1291                    attr.writable = 1;
1292                    attr.expandDown = 0;
1293                } else {
1294                    if (desc.type.codeOrData) {
1295                        attr.expandDown = 0;
1296                        attr.readable = desc.type.r;
1297                        attr.writable = 0;
1298                    } else {
1299                        attr.expandDown = desc.type.e;
1300                        attr.readable = 1;
1301                        attr.writable = desc.type.w;
1302                    }
1303                }
1304                Addr base = desc.baseLow | (desc.baseHigh << 24);
1305                Addr limit = desc.limitLow | (desc.limitHigh << 16);
1306                if (desc.g)
1307                    limit = (limit << 12) | mask(12);
1308                SegBaseDest = base;
1309                SegLimitDest = limit;
1310                SegAttrDest = attr;
1311            } else {
1312                SegBaseDest = SegBaseDest;
1313                SegLimitDest = SegLimitDest;
1314                SegAttrDest = SegAttrDest;
1315            }
1316        '''
1317}};
1318