LLVM API Documentation

X86MCInstLower.cpp
Go to the documentation of this file.
00001 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains code to lower X86 MachineInstrs to their corresponding
00011 // MCInst records.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "X86AsmPrinter.h"
00016 #include "X86RegisterInfo.h"
00017 #include "InstPrinter/X86ATTInstPrinter.h"
00018 #include "MCTargetDesc/X86BaseInfo.h"
00019 #include "Utils/X86ShuffleDecode.h"
00020 #include "llvm/ADT/SmallString.h"
00021 #include "llvm/CodeGen/MachineFunction.h"
00022 #include "llvm/CodeGen/MachineConstantPool.h"
00023 #include "llvm/CodeGen/MachineOperand.h"
00024 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00025 #include "llvm/CodeGen/StackMaps.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/GlobalValue.h"
00028 #include "llvm/IR/Mangler.h"
00029 #include "llvm/MC/MCAsmInfo.h"
00030 #include "llvm/MC/MCCodeEmitter.h"
00031 #include "llvm/MC/MCContext.h"
00032 #include "llvm/MC/MCExpr.h"
00033 #include "llvm/MC/MCInst.h"
00034 #include "llvm/MC/MCInstBuilder.h"
00035 #include "llvm/MC/MCStreamer.h"
00036 #include "llvm/MC/MCSymbol.h"
00037 #include "llvm/Support/TargetRegistry.h"
00038 using namespace llvm;
00039 
00040 namespace {
00041 
00042 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
00043 class X86MCInstLower {
00044   MCContext &Ctx;
00045   const MachineFunction &MF;
00046   const TargetMachine &TM;
00047   const MCAsmInfo &MAI;
00048   X86AsmPrinter &AsmPrinter;
00049 public:
00050   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
00051 
00052   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
00053 
00054   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
00055   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
00056 
00057 private:
00058   MachineModuleInfoMachO &getMachOMMI() const;
00059   Mangler *getMang() const {
00060     return AsmPrinter.Mang;
00061   }
00062 };
00063 
00064 } // end anonymous namespace
00065 
00066 // Emit a minimal sequence of nops spanning NumBytes bytes.
00067 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
00068                      const MCSubtargetInfo &STI);
00069 
00070 namespace llvm {
00071    X86AsmPrinter::StackMapShadowTracker::StackMapShadowTracker(TargetMachine &TM)
00072      : TM(TM), InShadow(false), RequiredShadowSize(0), CurrentShadowSize(0) {}
00073 
00074   X86AsmPrinter::StackMapShadowTracker::~StackMapShadowTracker() {}
00075 
00076   void
00077   X86AsmPrinter::StackMapShadowTracker::startFunction(MachineFunction &MF) {
00078     CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
00079         *TM.getSubtargetImpl()->getInstrInfo(),
00080         *TM.getSubtargetImpl()->getRegisterInfo(), *TM.getSubtargetImpl(),
00081         MF.getContext()));
00082   }
00083 
00084   void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
00085                                                    const MCSubtargetInfo &STI) {
00086     if (InShadow) {
00087       SmallString<256> Code;
00088       SmallVector<MCFixup, 4> Fixups;
00089       raw_svector_ostream VecOS(Code);
00090       CodeEmitter->EncodeInstruction(Inst, VecOS, Fixups, STI);
00091       VecOS.flush();
00092       CurrentShadowSize += Code.size();
00093       if (CurrentShadowSize >= RequiredShadowSize)
00094         InShadow = false; // The shadow is big enough. Stop counting.
00095     }
00096   }
00097 
00098   void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
00099     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
00100     if (InShadow && CurrentShadowSize < RequiredShadowSize) {
00101       InShadow = false;
00102       EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
00103                TM.getSubtarget<X86Subtarget>().is64Bit(), STI);
00104     }
00105   }
00106 
00107   void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
00108     OutStreamer.EmitInstruction(Inst, getSubtargetInfo());
00109     SMShadowTracker.count(Inst, getSubtargetInfo());
00110   }
00111 } // end llvm namespace
00112 
00113 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
00114                                X86AsmPrinter &asmprinter)
00115 : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()),
00116   MAI(*TM.getMCAsmInfo()), AsmPrinter(asmprinter) {}
00117 
00118 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
00119   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
00120 }
00121 
00122 
00123 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
00124 /// operand to an MCSymbol.
00125 MCSymbol *X86MCInstLower::
00126 GetSymbolFromOperand(const MachineOperand &MO) const {
00127   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
00128   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
00129 
00130   SmallString<128> Name;
00131   StringRef Suffix;
00132 
00133   switch (MO.getTargetFlags()) {
00134   case X86II::MO_DLLIMPORT:
00135     // Handle dllimport linkage.
00136     Name += "__imp_";
00137     break;
00138   case X86II::MO_DARWIN_STUB:
00139     Suffix = "$stub";
00140     break;
00141   case X86II::MO_DARWIN_NONLAZY:
00142   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00143   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00144     Suffix = "$non_lazy_ptr";
00145     break;
00146   }
00147 
00148   if (!Suffix.empty())
00149     Name += DL->getPrivateGlobalPrefix();
00150 
00151   unsigned PrefixLen = Name.size();
00152 
00153   if (MO.isGlobal()) {
00154     const GlobalValue *GV = MO.getGlobal();
00155     AsmPrinter.getNameWithPrefix(Name, GV);
00156   } else if (MO.isSymbol()) {
00157     getMang()->getNameWithPrefix(Name, MO.getSymbolName());
00158   } else if (MO.isMBB()) {
00159     Name += MO.getMBB()->getSymbol()->getName();
00160   }
00161   unsigned OrigLen = Name.size() - PrefixLen;
00162 
00163   Name += Suffix;
00164   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
00165 
00166   StringRef OrigName = StringRef(Name).substr(PrefixLen, OrigLen);
00167 
00168   // If the target flags on the operand changes the name of the symbol, do that
00169   // before we return the symbol.
00170   switch (MO.getTargetFlags()) {
00171   default: break;
00172   case X86II::MO_DARWIN_NONLAZY:
00173   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
00174     MachineModuleInfoImpl::StubValueTy &StubSym =
00175       getMachOMMI().getGVStubEntry(Sym);
00176     if (!StubSym.getPointer()) {
00177       assert(MO.isGlobal() && "Extern symbol not handled yet");
00178       StubSym =
00179         MachineModuleInfoImpl::
00180         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00181                     !MO.getGlobal()->hasInternalLinkage());
00182     }
00183     break;
00184   }
00185   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE: {
00186     MachineModuleInfoImpl::StubValueTy &StubSym =
00187       getMachOMMI().getHiddenGVStubEntry(Sym);
00188     if (!StubSym.getPointer()) {
00189       assert(MO.isGlobal() && "Extern symbol not handled yet");
00190       StubSym =
00191         MachineModuleInfoImpl::
00192         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00193                     !MO.getGlobal()->hasInternalLinkage());
00194     }
00195     break;
00196   }
00197   case X86II::MO_DARWIN_STUB: {
00198     MachineModuleInfoImpl::StubValueTy &StubSym =
00199       getMachOMMI().getFnStubEntry(Sym);
00200     if (StubSym.getPointer())
00201       return Sym;
00202 
00203     if (MO.isGlobal()) {
00204       StubSym =
00205         MachineModuleInfoImpl::
00206         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00207                     !MO.getGlobal()->hasInternalLinkage());
00208     } else {
00209       StubSym =
00210         MachineModuleInfoImpl::
00211         StubValueTy(Ctx.GetOrCreateSymbol(OrigName), false);
00212     }
00213     break;
00214   }
00215   }
00216 
00217   return Sym;
00218 }
00219 
00220 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
00221                                              MCSymbol *Sym) const {
00222   // FIXME: We would like an efficient form for this, so we don't have to do a
00223   // lot of extra uniquing.
00224   const MCExpr *Expr = nullptr;
00225   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
00226 
00227   switch (MO.getTargetFlags()) {
00228   default: llvm_unreachable("Unknown target flag on GV operand");
00229   case X86II::MO_NO_FLAG:    // No flag.
00230   // These affect the name of the symbol, not any suffix.
00231   case X86II::MO_DARWIN_NONLAZY:
00232   case X86II::MO_DLLIMPORT:
00233   case X86II::MO_DARWIN_STUB:
00234     break;
00235 
00236   case X86II::MO_TLVP:      RefKind = MCSymbolRefExpr::VK_TLVP; break;
00237   case X86II::MO_TLVP_PIC_BASE:
00238     Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
00239     // Subtract the pic base.
00240     Expr = MCBinaryExpr::CreateSub(Expr,
00241                                   MCSymbolRefExpr::Create(MF.getPICBaseSymbol(),
00242                                                            Ctx),
00243                                    Ctx);
00244     break;
00245   case X86II::MO_SECREL:    RefKind = MCSymbolRefExpr::VK_SECREL; break;
00246   case X86II::MO_TLSGD:     RefKind = MCSymbolRefExpr::VK_TLSGD; break;
00247   case X86II::MO_TLSLD:     RefKind = MCSymbolRefExpr::VK_TLSLD; break;
00248   case X86II::MO_TLSLDM:    RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
00249   case X86II::MO_GOTTPOFF:  RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
00250   case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
00251   case X86II::MO_TPOFF:     RefKind = MCSymbolRefExpr::VK_TPOFF; break;
00252   case X86II::MO_DTPOFF:    RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
00253   case X86II::MO_NTPOFF:    RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
00254   case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
00255   case X86II::MO_GOTPCREL:  RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
00256   case X86II::MO_GOT:       RefKind = MCSymbolRefExpr::VK_GOT; break;
00257   case X86II::MO_GOTOFF:    RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
00258   case X86II::MO_PLT:       RefKind = MCSymbolRefExpr::VK_PLT; break;
00259   case X86II::MO_PIC_BASE_OFFSET:
00260   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00261   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00262     Expr = MCSymbolRefExpr::Create(Sym, Ctx);
00263     // Subtract the pic base.
00264     Expr = MCBinaryExpr::CreateSub(Expr,
00265                             MCSymbolRefExpr::Create(MF.getPICBaseSymbol(), Ctx),
00266                                    Ctx);
00267     if (MO.isJTI() && MAI.hasSetDirective()) {
00268       // If .set directive is supported, use it to reduce the number of
00269       // relocations the assembler will generate for differences between
00270       // local labels. This is only safe when the symbols are in the same
00271       // section so we are restricting it to jumptable references.
00272       MCSymbol *Label = Ctx.CreateTempSymbol();
00273       AsmPrinter.OutStreamer.EmitAssignment(Label, Expr);
00274       Expr = MCSymbolRefExpr::Create(Label, Ctx);
00275     }
00276     break;
00277   }
00278 
00279   if (!Expr)
00280     Expr = MCSymbolRefExpr::Create(Sym, RefKind, Ctx);
00281 
00282   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
00283     Expr = MCBinaryExpr::CreateAdd(Expr,
00284                                    MCConstantExpr::Create(MO.getOffset(), Ctx),
00285                                    Ctx);
00286   return MCOperand::CreateExpr(Expr);
00287 }
00288 
00289 
00290 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
00291 /// a short fixed-register form.
00292 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
00293   unsigned ImmOp = Inst.getNumOperands() - 1;
00294   assert(Inst.getOperand(0).isReg() &&
00295          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
00296          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
00297            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
00298           Inst.getNumOperands() == 2) && "Unexpected instruction!");
00299 
00300   // Check whether the destination register can be fixed.
00301   unsigned Reg = Inst.getOperand(0).getReg();
00302   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00303     return;
00304 
00305   // If so, rewrite the instruction.
00306   MCOperand Saved = Inst.getOperand(ImmOp);
00307   Inst = MCInst();
00308   Inst.setOpcode(Opcode);
00309   Inst.addOperand(Saved);
00310 }
00311 
00312 /// \brief If a movsx instruction has a shorter encoding for the used register
00313 /// simplify the instruction to use it instead.
00314 static void SimplifyMOVSX(MCInst &Inst) {
00315   unsigned NewOpcode = 0;
00316   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
00317   switch (Inst.getOpcode()) {
00318   default:
00319     llvm_unreachable("Unexpected instruction!");
00320   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
00321     if (Op0 == X86::AX && Op1 == X86::AL)
00322       NewOpcode = X86::CBW;
00323     break;
00324   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
00325     if (Op0 == X86::EAX && Op1 == X86::AX)
00326       NewOpcode = X86::CWDE;
00327     break;
00328   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
00329     if (Op0 == X86::RAX && Op1 == X86::EAX)
00330       NewOpcode = X86::CDQE;
00331     break;
00332   }
00333 
00334   if (NewOpcode != 0) {
00335     Inst = MCInst();
00336     Inst.setOpcode(NewOpcode);
00337   }
00338 }
00339 
00340 /// \brief Simplify things like MOV32rm to MOV32o32a.
00341 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
00342                                   unsigned Opcode) {
00343   // Don't make these simplifications in 64-bit mode; other assemblers don't
00344   // perform them because they make the code larger.
00345   if (Printer.getSubtarget().is64Bit())
00346     return;
00347 
00348   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
00349   unsigned AddrBase = IsStore;
00350   unsigned RegOp = IsStore ? 0 : 5;
00351   unsigned AddrOp = AddrBase + 3;
00352   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
00353          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
00354          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
00355          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
00356          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
00357          (Inst.getOperand(AddrOp).isExpr() ||
00358           Inst.getOperand(AddrOp).isImm()) &&
00359          "Unexpected instruction!");
00360 
00361   // Check whether the destination register can be fixed.
00362   unsigned Reg = Inst.getOperand(RegOp).getReg();
00363   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00364     return;
00365 
00366   // Check whether this is an absolute address.
00367   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
00368   // to do this here.
00369   bool Absolute = true;
00370   if (Inst.getOperand(AddrOp).isExpr()) {
00371     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
00372     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
00373       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
00374         Absolute = false;
00375   }
00376 
00377   if (Absolute &&
00378       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
00379        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
00380        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
00381     return;
00382 
00383   // If so, rewrite the instruction.
00384   MCOperand Saved = Inst.getOperand(AddrOp);
00385   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
00386   Inst = MCInst();
00387   Inst.setOpcode(Opcode);
00388   Inst.addOperand(Saved);
00389   Inst.addOperand(Seg);
00390 }
00391 
00392 static unsigned getRetOpcode(const X86Subtarget &Subtarget)
00393 {
00394   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
00395 }
00396 
00397 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
00398   OutMI.setOpcode(MI->getOpcode());
00399 
00400   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00401     const MachineOperand &MO = MI->getOperand(i);
00402 
00403     MCOperand MCOp;
00404     switch (MO.getType()) {
00405     default:
00406       MI->dump();
00407       llvm_unreachable("unknown operand type");
00408     case MachineOperand::MO_Register:
00409       // Ignore all implicit register operands.
00410       if (MO.isImplicit()) continue;
00411       MCOp = MCOperand::CreateReg(MO.getReg());
00412       break;
00413     case MachineOperand::MO_Immediate:
00414       MCOp = MCOperand::CreateImm(MO.getImm());
00415       break;
00416     case MachineOperand::MO_MachineBasicBlock:
00417     case MachineOperand::MO_GlobalAddress:
00418     case MachineOperand::MO_ExternalSymbol:
00419       MCOp = LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
00420       break;
00421     case MachineOperand::MO_JumpTableIndex:
00422       MCOp = LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
00423       break;
00424     case MachineOperand::MO_ConstantPoolIndex:
00425       MCOp = LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
00426       break;
00427     case MachineOperand::MO_BlockAddress:
00428       MCOp = LowerSymbolOperand(MO,
00429                      AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
00430       break;
00431     case MachineOperand::MO_RegisterMask:
00432       // Ignore call clobbers.
00433       continue;
00434     }
00435 
00436     OutMI.addOperand(MCOp);
00437   }
00438 
00439   // Handle a few special cases to eliminate operand modifiers.
00440 ReSimplify:
00441   switch (OutMI.getOpcode()) {
00442   case X86::LEA64_32r:
00443   case X86::LEA64r:
00444   case X86::LEA16r:
00445   case X86::LEA32r:
00446     // LEA should have a segment register, but it must be empty.
00447     assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
00448            "Unexpected # of LEA operands");
00449     assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
00450            "LEA has segment specified!");
00451     break;
00452 
00453   case X86::MOV32ri64:
00454     OutMI.setOpcode(X86::MOV32ri);
00455     break;
00456 
00457   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
00458   // if one of the registers is extended, but other isn't.
00459   case X86::VMOVAPDrr:
00460   case X86::VMOVAPDYrr:
00461   case X86::VMOVAPSrr:
00462   case X86::VMOVAPSYrr:
00463   case X86::VMOVDQArr:
00464   case X86::VMOVDQAYrr:
00465   case X86::VMOVDQUrr:
00466   case X86::VMOVDQUYrr:
00467   case X86::VMOVUPDrr:
00468   case X86::VMOVUPDYrr:
00469   case X86::VMOVUPSrr:
00470   case X86::VMOVUPSYrr: {
00471     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00472         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
00473       unsigned NewOpc;
00474       switch (OutMI.getOpcode()) {
00475       default: llvm_unreachable("Invalid opcode");
00476       case X86::VMOVAPDrr:  NewOpc = X86::VMOVAPDrr_REV;  break;
00477       case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
00478       case X86::VMOVAPSrr:  NewOpc = X86::VMOVAPSrr_REV;  break;
00479       case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
00480       case X86::VMOVDQArr:  NewOpc = X86::VMOVDQArr_REV;  break;
00481       case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
00482       case X86::VMOVDQUrr:  NewOpc = X86::VMOVDQUrr_REV;  break;
00483       case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
00484       case X86::VMOVUPDrr:  NewOpc = X86::VMOVUPDrr_REV;  break;
00485       case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
00486       case X86::VMOVUPSrr:  NewOpc = X86::VMOVUPSrr_REV;  break;
00487       case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
00488       }
00489       OutMI.setOpcode(NewOpc);
00490     }
00491     break;
00492   }
00493   case X86::VMOVSDrr:
00494   case X86::VMOVSSrr: {
00495     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00496         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
00497       unsigned NewOpc;
00498       switch (OutMI.getOpcode()) {
00499       default: llvm_unreachable("Invalid opcode");
00500       case X86::VMOVSDrr:   NewOpc = X86::VMOVSDrr_REV;   break;
00501       case X86::VMOVSSrr:   NewOpc = X86::VMOVSSrr_REV;   break;
00502       }
00503       OutMI.setOpcode(NewOpc);
00504     }
00505     break;
00506   }
00507 
00508   // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
00509   // inputs modeled as normal uses instead of implicit uses.  As such, truncate
00510   // off all but the first operand (the callee).  FIXME: Change isel.
00511   case X86::TAILJMPr64:
00512   case X86::CALL64r:
00513   case X86::CALL64pcrel32: {
00514     unsigned Opcode = OutMI.getOpcode();
00515     MCOperand Saved = OutMI.getOperand(0);
00516     OutMI = MCInst();
00517     OutMI.setOpcode(Opcode);
00518     OutMI.addOperand(Saved);
00519     break;
00520   }
00521 
00522   case X86::EH_RETURN:
00523   case X86::EH_RETURN64: {
00524     OutMI = MCInst();
00525     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
00526     break;
00527   }
00528 
00529   // TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
00530   case X86::TAILJMPr:
00531   case X86::TAILJMPd:
00532   case X86::TAILJMPd64: {
00533     unsigned Opcode;
00534     switch (OutMI.getOpcode()) {
00535     default: llvm_unreachable("Invalid opcode");
00536     case X86::TAILJMPr: Opcode = X86::JMP32r; break;
00537     case X86::TAILJMPd:
00538     case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
00539     }
00540 
00541     MCOperand Saved = OutMI.getOperand(0);
00542     OutMI = MCInst();
00543     OutMI.setOpcode(Opcode);
00544     OutMI.addOperand(Saved);
00545     break;
00546   }
00547 
00548   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
00549   // this with an ugly goto in case the resultant OR uses EAX and needs the
00550   // short form.
00551   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
00552   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
00553   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
00554   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
00555   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
00556   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
00557   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
00558   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
00559   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
00560 
00561   // The assembler backend wants to see branches in their small form and relax
00562   // them to their large form.  The JIT can only handle the large form because
00563   // it does not do relaxation.  For now, translate the large form to the
00564   // small one here.
00565   case X86::JMP_4: OutMI.setOpcode(X86::JMP_1); break;
00566   case X86::JO_4:  OutMI.setOpcode(X86::JO_1); break;
00567   case X86::JNO_4: OutMI.setOpcode(X86::JNO_1); break;
00568   case X86::JB_4:  OutMI.setOpcode(X86::JB_1); break;
00569   case X86::JAE_4: OutMI.setOpcode(X86::JAE_1); break;
00570   case X86::JE_4:  OutMI.setOpcode(X86::JE_1); break;
00571   case X86::JNE_4: OutMI.setOpcode(X86::JNE_1); break;
00572   case X86::JBE_4: OutMI.setOpcode(X86::JBE_1); break;
00573   case X86::JA_4:  OutMI.setOpcode(X86::JA_1); break;
00574   case X86::JS_4:  OutMI.setOpcode(X86::JS_1); break;
00575   case X86::JNS_4: OutMI.setOpcode(X86::JNS_1); break;
00576   case X86::JP_4:  OutMI.setOpcode(X86::JP_1); break;
00577   case X86::JNP_4: OutMI.setOpcode(X86::JNP_1); break;
00578   case X86::JL_4:  OutMI.setOpcode(X86::JL_1); break;
00579   case X86::JGE_4: OutMI.setOpcode(X86::JGE_1); break;
00580   case X86::JLE_4: OutMI.setOpcode(X86::JLE_1); break;
00581   case X86::JG_4:  OutMI.setOpcode(X86::JG_1); break;
00582 
00583   // Atomic load and store require a separate pseudo-inst because Acquire
00584   // implies mayStore and Release implies mayLoad; fix these to regular MOV
00585   // instructions here
00586   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
00587   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
00588   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
00589   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
00590   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
00591   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
00592   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
00593   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
00594   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
00595   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
00596   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
00597   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
00598   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
00599   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
00600   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
00601   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
00602   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
00603   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
00604   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
00605   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
00606   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
00607   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
00608   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
00609   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
00610   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
00611   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
00612   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
00613   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
00614   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
00615   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
00616   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
00617   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
00618 
00619   // We don't currently select the correct instruction form for instructions
00620   // which have a short %eax, etc. form. Handle this by custom lowering, for
00621   // now.
00622   //
00623   // Note, we are currently not handling the following instructions:
00624   // MOV64ao8, MOV64o8a
00625   // XCHG16ar, XCHG32ar, XCHG64ar
00626   case X86::MOV8mr_NOREX:
00627   case X86::MOV8mr:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao8); break;
00628   case X86::MOV8rm_NOREX:
00629   case X86::MOV8rm:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o8a); break;
00630   case X86::MOV16mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao16); break;
00631   case X86::MOV16rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o16a); break;
00632   case X86::MOV32mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
00633   case X86::MOV32rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
00634 
00635   case X86::ADC8ri:     SimplifyShortImmForm(OutMI, X86::ADC8i8);    break;
00636   case X86::ADC16ri:    SimplifyShortImmForm(OutMI, X86::ADC16i16);  break;
00637   case X86::ADC32ri:    SimplifyShortImmForm(OutMI, X86::ADC32i32);  break;
00638   case X86::ADC64ri32:  SimplifyShortImmForm(OutMI, X86::ADC64i32);  break;
00639   case X86::ADD8ri:     SimplifyShortImmForm(OutMI, X86::ADD8i8);    break;
00640   case X86::ADD16ri:    SimplifyShortImmForm(OutMI, X86::ADD16i16);  break;
00641   case X86::ADD32ri:    SimplifyShortImmForm(OutMI, X86::ADD32i32);  break;
00642   case X86::ADD64ri32:  SimplifyShortImmForm(OutMI, X86::ADD64i32);  break;
00643   case X86::AND8ri:     SimplifyShortImmForm(OutMI, X86::AND8i8);    break;
00644   case X86::AND16ri:    SimplifyShortImmForm(OutMI, X86::AND16i16);  break;
00645   case X86::AND32ri:    SimplifyShortImmForm(OutMI, X86::AND32i32);  break;
00646   case X86::AND64ri32:  SimplifyShortImmForm(OutMI, X86::AND64i32);  break;
00647   case X86::CMP8ri:     SimplifyShortImmForm(OutMI, X86::CMP8i8);    break;
00648   case X86::CMP16ri:    SimplifyShortImmForm(OutMI, X86::CMP16i16);  break;
00649   case X86::CMP32ri:    SimplifyShortImmForm(OutMI, X86::CMP32i32);  break;
00650   case X86::CMP64ri32:  SimplifyShortImmForm(OutMI, X86::CMP64i32);  break;
00651   case X86::OR8ri:      SimplifyShortImmForm(OutMI, X86::OR8i8);     break;
00652   case X86::OR16ri:     SimplifyShortImmForm(OutMI, X86::OR16i16);   break;
00653   case X86::OR32ri:     SimplifyShortImmForm(OutMI, X86::OR32i32);   break;
00654   case X86::OR64ri32:   SimplifyShortImmForm(OutMI, X86::OR64i32);   break;
00655   case X86::SBB8ri:     SimplifyShortImmForm(OutMI, X86::SBB8i8);    break;
00656   case X86::SBB16ri:    SimplifyShortImmForm(OutMI, X86::SBB16i16);  break;
00657   case X86::SBB32ri:    SimplifyShortImmForm(OutMI, X86::SBB32i32);  break;
00658   case X86::SBB64ri32:  SimplifyShortImmForm(OutMI, X86::SBB64i32);  break;
00659   case X86::SUB8ri:     SimplifyShortImmForm(OutMI, X86::SUB8i8);    break;
00660   case X86::SUB16ri:    SimplifyShortImmForm(OutMI, X86::SUB16i16);  break;
00661   case X86::SUB32ri:    SimplifyShortImmForm(OutMI, X86::SUB32i32);  break;
00662   case X86::SUB64ri32:  SimplifyShortImmForm(OutMI, X86::SUB64i32);  break;
00663   case X86::TEST8ri:    SimplifyShortImmForm(OutMI, X86::TEST8i8);   break;
00664   case X86::TEST16ri:   SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
00665   case X86::TEST32ri:   SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
00666   case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
00667   case X86::XOR8ri:     SimplifyShortImmForm(OutMI, X86::XOR8i8);    break;
00668   case X86::XOR16ri:    SimplifyShortImmForm(OutMI, X86::XOR16i16);  break;
00669   case X86::XOR32ri:    SimplifyShortImmForm(OutMI, X86::XOR32i32);  break;
00670   case X86::XOR64ri32:  SimplifyShortImmForm(OutMI, X86::XOR64i32);  break;
00671 
00672   // Try to shrink some forms of movsx.
00673   case X86::MOVSX16rr8:
00674   case X86::MOVSX32rr16:
00675   case X86::MOVSX64rr32:
00676     SimplifyMOVSX(OutMI);
00677     break;
00678   }
00679 }
00680 
00681 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
00682                                  const MachineInstr &MI) {
00683 
00684   bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
00685                   MI.getOpcode() == X86::TLS_base_addr64;
00686 
00687   bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
00688 
00689   MCContext &context = OutStreamer.getContext();
00690 
00691   if (needsPadding)
00692     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00693 
00694   MCSymbolRefExpr::VariantKind SRVK;
00695   switch (MI.getOpcode()) {
00696     case X86::TLS_addr32:
00697     case X86::TLS_addr64:
00698       SRVK = MCSymbolRefExpr::VK_TLSGD;
00699       break;
00700     case X86::TLS_base_addr32:
00701       SRVK = MCSymbolRefExpr::VK_TLSLDM;
00702       break;
00703     case X86::TLS_base_addr64:
00704       SRVK = MCSymbolRefExpr::VK_TLSLD;
00705       break;
00706     default:
00707       llvm_unreachable("unexpected opcode");
00708   }
00709 
00710   MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
00711   const MCSymbolRefExpr *symRef = MCSymbolRefExpr::Create(sym, SRVK, context);
00712 
00713   MCInst LEA;
00714   if (is64Bits) {
00715     LEA.setOpcode(X86::LEA64r);
00716     LEA.addOperand(MCOperand::CreateReg(X86::RDI)); // dest
00717     LEA.addOperand(MCOperand::CreateReg(X86::RIP)); // base
00718     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00719     LEA.addOperand(MCOperand::CreateReg(0));        // index
00720     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00721     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00722   } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
00723     LEA.setOpcode(X86::LEA32r);
00724     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00725     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // base
00726     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00727     LEA.addOperand(MCOperand::CreateReg(0));        // index
00728     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00729     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00730   } else {
00731     LEA.setOpcode(X86::LEA32r);
00732     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00733     LEA.addOperand(MCOperand::CreateReg(0));        // base
00734     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00735     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // index
00736     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00737     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00738   }
00739   EmitAndCountInstruction(LEA);
00740 
00741   if (needsPadding) {
00742     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00743     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00744     EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
00745   }
00746 
00747   StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
00748   MCSymbol *tlsGetAddr = context.GetOrCreateSymbol(name);
00749   const MCSymbolRefExpr *tlsRef =
00750     MCSymbolRefExpr::Create(tlsGetAddr,
00751                             MCSymbolRefExpr::VK_PLT,
00752                             context);
00753 
00754   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
00755                                                  : X86::CALLpcrel32)
00756                             .addExpr(tlsRef));
00757 }
00758 
00759 /// \brief Emit the optimal amount of multi-byte nops on X86.
00760 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
00761   // This works only for 64bit. For 32bit we have to do additional checking if
00762   // the CPU supports multi-byte nops.
00763   assert(Is64Bit && "EmitNops only supports X86-64");
00764   while (NumBytes) {
00765     unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
00766     Opc = IndexReg = Displacement = SegmentReg = 0;
00767     BaseReg = X86::RAX; ScaleVal = 1;
00768     switch (NumBytes) {
00769     case  0: llvm_unreachable("Zero nops?"); break;
00770     case  1: NumBytes -=  1; Opc = X86::NOOP; break;
00771     case  2: NumBytes -=  2; Opc = X86::XCHG16ar; break;
00772     case  3: NumBytes -=  3; Opc = X86::NOOPL; break;
00773     case  4: NumBytes -=  4; Opc = X86::NOOPL; Displacement = 8; break;
00774     case  5: NumBytes -=  5; Opc = X86::NOOPL; Displacement = 8;
00775              IndexReg = X86::RAX; break;
00776     case  6: NumBytes -=  6; Opc = X86::NOOPW; Displacement = 8;
00777              IndexReg = X86::RAX; break;
00778     case  7: NumBytes -=  7; Opc = X86::NOOPL; Displacement = 512; break;
00779     case  8: NumBytes -=  8; Opc = X86::NOOPL; Displacement = 512;
00780              IndexReg = X86::RAX; break;
00781     case  9: NumBytes -=  9; Opc = X86::NOOPW; Displacement = 512;
00782              IndexReg = X86::RAX; break;
00783     default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
00784              IndexReg = X86::RAX; SegmentReg = X86::CS; break;
00785     }
00786 
00787     unsigned NumPrefixes = std::min(NumBytes, 5U);
00788     NumBytes -= NumPrefixes;
00789     for (unsigned i = 0; i != NumPrefixes; ++i)
00790       OS.EmitBytes("\x66");
00791 
00792     switch (Opc) {
00793     default: llvm_unreachable("Unexpected opcode"); break;
00794     case X86::NOOP:
00795       OS.EmitInstruction(MCInstBuilder(Opc), STI);
00796       break;
00797     case X86::XCHG16ar:
00798       OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
00799       break;
00800     case X86::NOOPL:
00801     case X86::NOOPW:
00802       OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
00803                          .addImm(ScaleVal).addReg(IndexReg)
00804                          .addImm(Displacement).addReg(SegmentReg), STI);
00805       break;
00806     }
00807   } // while (NumBytes)
00808 }
00809 
00810 // Lower a stackmap of the form:
00811 // <id>, <shadowBytes>, ...
00812 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
00813   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00814   SM.recordStackMap(MI);
00815   unsigned NumShadowBytes = MI.getOperand(1).getImm();
00816   SMShadowTracker.reset(NumShadowBytes);
00817 }
00818 
00819 // Lower a patchpoint of the form:
00820 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
00821 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI) {
00822   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
00823 
00824   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00825 
00826   SM.recordPatchPoint(MI);
00827 
00828   PatchPointOpers opers(&MI);
00829   unsigned ScratchIdx = opers.getNextScratchIdx();
00830   unsigned EncodedBytes = 0;
00831   int64_t CallTarget = opers.getMetaOper(PatchPointOpers::TargetPos).getImm();
00832   if (CallTarget) {
00833     // Emit MOV to materialize the target address and the CALL to target.
00834     // This is encoded with 12-13 bytes, depending on which register is used.
00835     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
00836     if (X86II::isX86_64ExtendedReg(ScratchReg))
00837       EncodedBytes = 13;
00838     else
00839       EncodedBytes = 12;
00840     EmitAndCountInstruction(MCInstBuilder(X86::MOV64ri).addReg(ScratchReg)
00841                                                        .addImm(CallTarget));
00842     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
00843   }
00844   // Emit padding.
00845   unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
00846   assert(NumBytes >= EncodedBytes &&
00847          "Patchpoint can't request size less than the length of a call.");
00848 
00849   EmitNops(OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
00850            getSubtargetInfo());
00851 }
00852 
00853 // Returns instruction preceding MBBI in MachineFunction.
00854 // If MBBI is the first instruction of the first basic block, returns null.
00855 static MachineBasicBlock::const_iterator
00856 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
00857   const MachineBasicBlock *MBB = MBBI->getParent();
00858   while (MBBI == MBB->begin()) {
00859     if (MBB == MBB->getParent()->begin())
00860       return nullptr;
00861     MBB = MBB->getPrevNode();
00862     MBBI = MBB->end();
00863   }
00864   return --MBBI;
00865 }
00866 
00867 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
00868   X86MCInstLower MCInstLowering(*MF, *this);
00869   const X86RegisterInfo *RI = static_cast<const X86RegisterInfo *>(
00870       TM.getSubtargetImpl()->getRegisterInfo());
00871 
00872   switch (MI->getOpcode()) {
00873   case TargetOpcode::DBG_VALUE:
00874     llvm_unreachable("Should be handled target independently");
00875 
00876   // Emit nothing here but a comment if we can.
00877   case X86::Int_MemBarrier:
00878     OutStreamer.emitRawComment("MEMBARRIER");
00879     return;
00880 
00881 
00882   case X86::EH_RETURN:
00883   case X86::EH_RETURN64: {
00884     // Lower these as normal, but add some comments.
00885     unsigned Reg = MI->getOperand(0).getReg();
00886     OutStreamer.AddComment(StringRef("eh_return, addr: %") +
00887                            X86ATTInstPrinter::getRegisterName(Reg));
00888     break;
00889   }
00890   case X86::TAILJMPr:
00891   case X86::TAILJMPd:
00892   case X86::TAILJMPd64:
00893     // Lower these as normal, but add some comments.
00894     OutStreamer.AddComment("TAILCALL");
00895     break;
00896 
00897   case X86::TLS_addr32:
00898   case X86::TLS_addr64:
00899   case X86::TLS_base_addr32:
00900   case X86::TLS_base_addr64:
00901     return LowerTlsAddr(MCInstLowering, *MI);
00902 
00903   case X86::MOVPC32r: {
00904     // This is a pseudo op for a two instruction sequence with a label, which
00905     // looks like:
00906     //     call "L1$pb"
00907     // "L1$pb":
00908     //     popl %esi
00909 
00910     // Emit the call.
00911     MCSymbol *PICBase = MF->getPICBaseSymbol();
00912     // FIXME: We would like an efficient form for this, so we don't have to do a
00913     // lot of extra uniquing.
00914     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
00915       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
00916 
00917     // Emit the label.
00918     OutStreamer.EmitLabel(PICBase);
00919 
00920     // popl $reg
00921     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
00922                             .addReg(MI->getOperand(0).getReg()));
00923     return;
00924   }
00925 
00926   case X86::ADD32ri: {
00927     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
00928     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
00929       break;
00930 
00931     // Okay, we have something like:
00932     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
00933 
00934     // For this, we want to print something like:
00935     //   MYGLOBAL + (. - PICBASE)
00936     // However, we can't generate a ".", so just emit a new label here and refer
00937     // to it.
00938     MCSymbol *DotSym = OutContext.CreateTempSymbol();
00939     OutStreamer.EmitLabel(DotSym);
00940 
00941     // Now that we have emitted the label, lower the complex operand expression.
00942     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
00943 
00944     const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
00945     const MCExpr *PICBase =
00946       MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), OutContext);
00947     DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
00948 
00949     DotExpr = MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(OpSym,OutContext),
00950                                       DotExpr, OutContext);
00951 
00952     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
00953       .addReg(MI->getOperand(0).getReg())
00954       .addReg(MI->getOperand(1).getReg())
00955       .addExpr(DotExpr));
00956     return;
00957   }
00958 
00959   case TargetOpcode::STACKMAP:
00960     return LowerSTACKMAP(*MI);
00961 
00962   case TargetOpcode::PATCHPOINT:
00963     return LowerPATCHPOINT(*MI);
00964 
00965   case X86::MORESTACK_RET:
00966     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
00967     return;
00968 
00969   case X86::MORESTACK_RET_RESTORE_R10:
00970     // Return, then restore R10.
00971     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
00972     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
00973                             .addReg(X86::R10)
00974                             .addReg(X86::RAX));
00975     return;
00976 
00977   case X86::SEH_PushReg:
00978     OutStreamer.EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
00979     return;
00980 
00981   case X86::SEH_SaveReg:
00982     OutStreamer.EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
00983                                   MI->getOperand(1).getImm());
00984     return;
00985 
00986   case X86::SEH_SaveXMM:
00987     OutStreamer.EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
00988                                   MI->getOperand(1).getImm());
00989     return;
00990 
00991   case X86::SEH_StackAlloc:
00992     OutStreamer.EmitWinCFIAllocStack(MI->getOperand(0).getImm());
00993     return;
00994 
00995   case X86::SEH_SetFrame:
00996     OutStreamer.EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
00997                                    MI->getOperand(1).getImm());
00998     return;
00999 
01000   case X86::SEH_PushFrame:
01001     OutStreamer.EmitWinCFIPushFrame(MI->getOperand(0).getImm());
01002     return;
01003 
01004   case X86::SEH_EndPrologue:
01005     OutStreamer.EmitWinCFIEndProlog();
01006     return;
01007 
01008   case X86::SEH_Epilogue: {
01009     MachineBasicBlock::const_iterator MBBI(MI);
01010     // Check if preceded by a call and emit nop if so.
01011     for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
01012       // Conservatively assume that pseudo instructions don't emit code and keep
01013       // looking for a call. We may emit an unnecessary nop in some cases.
01014       if (!MBBI->isPseudo()) {
01015         if (MBBI->isCall())
01016           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
01017         break;
01018       }
01019     }
01020     return;
01021   }
01022 
01023   case X86::PSHUFBrm:
01024   case X86::VPSHUFBrm:
01025     // Lower PSHUFB normally but add a comment if we can find a constant
01026     // shuffle mask. We won't be able to do this at the MC layer because the
01027     // mask isn't an immediate.
01028     std::string Comment;
01029     raw_string_ostream CS(Comment);
01030     SmallVector<int, 16> Mask;
01031 
01032     assert(MI->getNumOperands() >= 6 &&
01033            "Wrong number of operands for PSHUFBrm or VPSHUFBrm");
01034     const MachineOperand &DstOp = MI->getOperand(0);
01035     const MachineOperand &SrcOp = MI->getOperand(1);
01036     const MachineOperand &MaskOp = MI->getOperand(5);
01037 
01038     // Compute the name for a register. This is really goofy because we have
01039     // multiple instruction printers that could (in theory) use different
01040     // names. Fortunately most people use the ATT style (outside of Windows)
01041     // and they actually agree on register naming here. Ultimately, this is
01042     // a comment, and so its OK if it isn't perfect.
01043     auto GetRegisterName = [](unsigned RegNum) -> StringRef {
01044       return X86ATTInstPrinter::getRegisterName(RegNum);
01045     };
01046 
01047     StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
01048     StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
01049     CS << DstName << " = ";
01050 
01051     if (MaskOp.isCPI()) {
01052       ArrayRef<MachineConstantPoolEntry> Constants =
01053           MI->getParent()->getParent()->getConstantPool()->getConstants();
01054       const MachineConstantPoolEntry &MaskConstantEntry =
01055           Constants[MaskOp.getIndex()];
01056       Type *MaskTy = MaskConstantEntry.getType();
01057       (void)MaskTy;
01058       if (!MaskConstantEntry.isMachineConstantPoolEntry())
01059         if (auto *C = dyn_cast<ConstantDataSequential>(
01060                 MaskConstantEntry.Val.ConstVal)) {
01061           assert(MaskTy == C->getType() &&
01062                  "Expected a constant of the same type!");
01063 
01064           DecodePSHUFBMask(C, Mask);
01065           assert(Mask.size() == MaskTy->getVectorNumElements() &&
01066                  "Shuffle mask has a different size than its type!");
01067         }
01068     }
01069 
01070     if (!Mask.empty()) {
01071       bool NeedComma = false;
01072       bool InSrc = false;
01073       for (int M : Mask) {
01074         // Wrap up any prior entry...
01075         if (M == SM_SentinelZero && InSrc) {
01076           InSrc = false;
01077           CS << "]";
01078         }
01079         if (NeedComma)
01080           CS << ",";
01081         else
01082           NeedComma = true;
01083 
01084         // Print this shuffle...
01085         if (M == SM_SentinelZero) {
01086           CS << "zero";
01087         } else {
01088           if (!InSrc) {
01089             InSrc = true;
01090             CS << SrcName << "[";
01091           }
01092           CS << M;
01093         }
01094       }
01095       if (InSrc)
01096         CS << "]";
01097 
01098       OutStreamer.AddComment(CS.str());
01099     }
01100     break;
01101   }
01102 
01103   MCInst TmpInst;
01104   MCInstLowering.Lower(MI, TmpInst);
01105   EmitAndCountInstruction(TmpInst);
01106 }