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()) {
00268       assert(MAI.doesSetDirectiveSuppressesReloc());
00269       // If .set directive is supported, use it to reduce the number of
00270       // relocations the assembler will generate for differences between
00271       // local labels. This is only safe when the symbols are in the same
00272       // section so we are restricting it to jumptable references.
00273       MCSymbol *Label = Ctx.CreateTempSymbol();
00274       AsmPrinter.OutStreamer.EmitAssignment(Label, Expr);
00275       Expr = MCSymbolRefExpr::Create(Label, Ctx);
00276     }
00277     break;
00278   }
00279 
00280   if (!Expr)
00281     Expr = MCSymbolRefExpr::Create(Sym, RefKind, Ctx);
00282 
00283   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
00284     Expr = MCBinaryExpr::CreateAdd(Expr,
00285                                    MCConstantExpr::Create(MO.getOffset(), Ctx),
00286                                    Ctx);
00287   return MCOperand::CreateExpr(Expr);
00288 }
00289 
00290 
00291 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
00292 /// a short fixed-register form.
00293 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
00294   unsigned ImmOp = Inst.getNumOperands() - 1;
00295   assert(Inst.getOperand(0).isReg() &&
00296          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
00297          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
00298            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
00299           Inst.getNumOperands() == 2) && "Unexpected instruction!");
00300 
00301   // Check whether the destination register can be fixed.
00302   unsigned Reg = Inst.getOperand(0).getReg();
00303   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00304     return;
00305 
00306   // If so, rewrite the instruction.
00307   MCOperand Saved = Inst.getOperand(ImmOp);
00308   Inst = MCInst();
00309   Inst.setOpcode(Opcode);
00310   Inst.addOperand(Saved);
00311 }
00312 
00313 /// \brief If a movsx instruction has a shorter encoding for the used register
00314 /// simplify the instruction to use it instead.
00315 static void SimplifyMOVSX(MCInst &Inst) {
00316   unsigned NewOpcode = 0;
00317   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
00318   switch (Inst.getOpcode()) {
00319   default:
00320     llvm_unreachable("Unexpected instruction!");
00321   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
00322     if (Op0 == X86::AX && Op1 == X86::AL)
00323       NewOpcode = X86::CBW;
00324     break;
00325   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
00326     if (Op0 == X86::EAX && Op1 == X86::AX)
00327       NewOpcode = X86::CWDE;
00328     break;
00329   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
00330     if (Op0 == X86::RAX && Op1 == X86::EAX)
00331       NewOpcode = X86::CDQE;
00332     break;
00333   }
00334 
00335   if (NewOpcode != 0) {
00336     Inst = MCInst();
00337     Inst.setOpcode(NewOpcode);
00338   }
00339 }
00340 
00341 /// \brief Simplify things like MOV32rm to MOV32o32a.
00342 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
00343                                   unsigned Opcode) {
00344   // Don't make these simplifications in 64-bit mode; other assemblers don't
00345   // perform them because they make the code larger.
00346   if (Printer.getSubtarget().is64Bit())
00347     return;
00348 
00349   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
00350   unsigned AddrBase = IsStore;
00351   unsigned RegOp = IsStore ? 0 : 5;
00352   unsigned AddrOp = AddrBase + 3;
00353   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
00354          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
00355          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
00356          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
00357          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
00358          (Inst.getOperand(AddrOp).isExpr() ||
00359           Inst.getOperand(AddrOp).isImm()) &&
00360          "Unexpected instruction!");
00361 
00362   // Check whether the destination register can be fixed.
00363   unsigned Reg = Inst.getOperand(RegOp).getReg();
00364   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00365     return;
00366 
00367   // Check whether this is an absolute address.
00368   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
00369   // to do this here.
00370   bool Absolute = true;
00371   if (Inst.getOperand(AddrOp).isExpr()) {
00372     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
00373     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
00374       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
00375         Absolute = false;
00376   }
00377 
00378   if (Absolute &&
00379       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
00380        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
00381        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
00382     return;
00383 
00384   // If so, rewrite the instruction.
00385   MCOperand Saved = Inst.getOperand(AddrOp);
00386   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
00387   Inst = MCInst();
00388   Inst.setOpcode(Opcode);
00389   Inst.addOperand(Saved);
00390   Inst.addOperand(Seg);
00391 }
00392 
00393 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
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 static void LowerSTATEPOINT(MCStreamer &OS, StackMaps &SM,
00811                             const MachineInstr &MI, bool Is64Bit,
00812                             const TargetMachine& TM,
00813                             const MCSubtargetInfo& STI,
00814                             X86MCInstLower &MCInstLowering) {
00815   assert(Is64Bit && "Statepoint currently only supports X86-64");
00816 
00817   // Lower call target and choose correct opcode
00818   const MachineOperand &call_target = StatepointOpers(&MI).getCallTarget();
00819   MCOperand call_target_mcop;
00820   unsigned call_opcode;
00821   switch (call_target.getType()) {
00822   case MachineOperand::MO_GlobalAddress:
00823   case MachineOperand::MO_ExternalSymbol:
00824     call_target_mcop = MCInstLowering.LowerSymbolOperand(
00825       call_target,
00826       MCInstLowering.GetSymbolFromOperand(call_target));
00827     call_opcode = X86::CALL64pcrel32;
00828     // Currently, we only support relative addressing with statepoints.
00829     // Otherwise, we'll need a scratch register to hold the target
00830     // address.  You'll fail asserts during load & relocation if this
00831     // symbol is to far away. (TODO: support non-relative addressing)
00832     break;
00833   case MachineOperand::MO_Immediate:
00834     call_target_mcop = MCOperand::CreateImm(call_target.getImm());
00835     call_opcode = X86::CALL64pcrel32;
00836     // Currently, we only support relative addressing with statepoints.
00837     // Otherwise, we'll need a scratch register to hold the target
00838     // immediate.  You'll fail asserts during load & relocation if this
00839     // address is to far away. (TODO: support non-relative addressing)
00840     break;
00841   case MachineOperand::MO_Register:
00842     call_target_mcop = MCOperand::CreateReg(call_target.getReg());
00843     call_opcode = X86::CALL64r;
00844     break;
00845   default:
00846     llvm_unreachable("Unsupported operand type in statepoint call target");
00847     break;
00848   }
00849 
00850   // Emit call
00851   MCInst call_inst;
00852   call_inst.setOpcode(call_opcode);
00853   call_inst.addOperand(call_target_mcop);
00854   OS.EmitInstruction(call_inst, STI);
00855 
00856   // Record our statepoint node in the same section used by STACKMAP
00857   // and PATCHPOINT
00858   SM.recordStatepoint(MI);
00859 }
00860 
00861 
00862 // Lower a stackmap of the form:
00863 // <id>, <shadowBytes>, ...
00864 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
00865   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00866   SM.recordStackMap(MI);
00867   unsigned NumShadowBytes = MI.getOperand(1).getImm();
00868   SMShadowTracker.reset(NumShadowBytes);
00869 }
00870 
00871 // Lower a patchpoint of the form:
00872 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
00873 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI) {
00874   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
00875 
00876   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00877 
00878   SM.recordPatchPoint(MI);
00879 
00880   PatchPointOpers opers(&MI);
00881   unsigned ScratchIdx = opers.getNextScratchIdx();
00882   unsigned EncodedBytes = 0;
00883   int64_t CallTarget = opers.getMetaOper(PatchPointOpers::TargetPos).getImm();
00884   if (CallTarget) {
00885     // Emit MOV to materialize the target address and the CALL to target.
00886     // This is encoded with 12-13 bytes, depending on which register is used.
00887     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
00888     if (X86II::isX86_64ExtendedReg(ScratchReg))
00889       EncodedBytes = 13;
00890     else
00891       EncodedBytes = 12;
00892     EmitAndCountInstruction(MCInstBuilder(X86::MOV64ri).addReg(ScratchReg)
00893                                                        .addImm(CallTarget));
00894     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
00895   }
00896   // Emit padding.
00897   unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
00898   assert(NumBytes >= EncodedBytes &&
00899          "Patchpoint can't request size less than the length of a call.");
00900 
00901   EmitNops(OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
00902            getSubtargetInfo());
00903 }
00904 
00905 // Returns instruction preceding MBBI in MachineFunction.
00906 // If MBBI is the first instruction of the first basic block, returns null.
00907 static MachineBasicBlock::const_iterator
00908 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
00909   const MachineBasicBlock *MBB = MBBI->getParent();
00910   while (MBBI == MBB->begin()) {
00911     if (MBB == MBB->getParent()->begin())
00912       return nullptr;
00913     MBB = MBB->getPrevNode();
00914     MBBI = MBB->end();
00915   }
00916   return --MBBI;
00917 }
00918 
00919 static const Constant *getConstantFromPool(const MachineInstr &MI,
00920                                            const MachineOperand &Op) {
00921   if (!Op.isCPI())
00922     return nullptr;
00923 
00924   ArrayRef<MachineConstantPoolEntry> Constants =
00925       MI.getParent()->getParent()->getConstantPool()->getConstants();
00926   const MachineConstantPoolEntry &ConstantEntry =
00927       Constants[Op.getIndex()];
00928 
00929   // Bail if this is a machine constant pool entry, we won't be able to dig out
00930   // anything useful.
00931   if (ConstantEntry.isMachineConstantPoolEntry())
00932     return nullptr;
00933 
00934   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
00935   assert((!C || ConstantEntry.getType() == C->getType()) &&
00936          "Expected a constant of the same type!");
00937   return C;
00938 }
00939 
00940 static std::string getShuffleComment(const MachineOperand &DstOp,
00941                                      const MachineOperand &SrcOp,
00942                                      ArrayRef<int> Mask) {
00943   std::string Comment;
00944 
00945   // Compute the name for a register. This is really goofy because we have
00946   // multiple instruction printers that could (in theory) use different
00947   // names. Fortunately most people use the ATT style (outside of Windows)
00948   // and they actually agree on register naming here. Ultimately, this is
00949   // a comment, and so its OK if it isn't perfect.
00950   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
00951     return X86ATTInstPrinter::getRegisterName(RegNum);
00952   };
00953 
00954   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
00955   StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
00956 
00957   raw_string_ostream CS(Comment);
00958   CS << DstName << " = ";
00959   bool NeedComma = false;
00960   bool InSrc = false;
00961   for (int M : Mask) {
00962     // Wrap up any prior entry...
00963     if (M == SM_SentinelZero && InSrc) {
00964       InSrc = false;
00965       CS << "]";
00966     }
00967     if (NeedComma)
00968       CS << ",";
00969     else
00970       NeedComma = true;
00971 
00972     // Print this shuffle...
00973     if (M == SM_SentinelZero) {
00974       CS << "zero";
00975     } else {
00976       if (!InSrc) {
00977         InSrc = true;
00978         CS << SrcName << "[";
00979       }
00980       if (M == SM_SentinelUndef)
00981         CS << "u";
00982       else
00983         CS << M;
00984     }
00985   }
00986   if (InSrc)
00987     CS << "]";
00988   CS.flush();
00989 
00990   return Comment;
00991 }
00992 
00993 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
00994   X86MCInstLower MCInstLowering(*MF, *this);
00995   const X86RegisterInfo *RI = static_cast<const X86RegisterInfo *>(
00996       TM.getSubtargetImpl()->getRegisterInfo());
00997 
00998   switch (MI->getOpcode()) {
00999   case TargetOpcode::DBG_VALUE:
01000     llvm_unreachable("Should be handled target independently");
01001 
01002   // Emit nothing here but a comment if we can.
01003   case X86::Int_MemBarrier:
01004     OutStreamer.emitRawComment("MEMBARRIER");
01005     return;
01006 
01007 
01008   case X86::EH_RETURN:
01009   case X86::EH_RETURN64: {
01010     // Lower these as normal, but add some comments.
01011     unsigned Reg = MI->getOperand(0).getReg();
01012     OutStreamer.AddComment(StringRef("eh_return, addr: %") +
01013                            X86ATTInstPrinter::getRegisterName(Reg));
01014     break;
01015   }
01016   case X86::TAILJMPr:
01017   case X86::TAILJMPd:
01018   case X86::TAILJMPd64:
01019     // Lower these as normal, but add some comments.
01020     OutStreamer.AddComment("TAILCALL");
01021     break;
01022 
01023   case X86::TLS_addr32:
01024   case X86::TLS_addr64:
01025   case X86::TLS_base_addr32:
01026   case X86::TLS_base_addr64:
01027     return LowerTlsAddr(MCInstLowering, *MI);
01028 
01029   case X86::MOVPC32r: {
01030     // This is a pseudo op for a two instruction sequence with a label, which
01031     // looks like:
01032     //     call "L1$pb"
01033     // "L1$pb":
01034     //     popl %esi
01035 
01036     // Emit the call.
01037     MCSymbol *PICBase = MF->getPICBaseSymbol();
01038     // FIXME: We would like an efficient form for this, so we don't have to do a
01039     // lot of extra uniquing.
01040     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
01041       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
01042 
01043     // Emit the label.
01044     OutStreamer.EmitLabel(PICBase);
01045 
01046     // popl $reg
01047     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
01048                             .addReg(MI->getOperand(0).getReg()));
01049     return;
01050   }
01051 
01052   case X86::ADD32ri: {
01053     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
01054     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
01055       break;
01056 
01057     // Okay, we have something like:
01058     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
01059 
01060     // For this, we want to print something like:
01061     //   MYGLOBAL + (. - PICBASE)
01062     // However, we can't generate a ".", so just emit a new label here and refer
01063     // to it.
01064     MCSymbol *DotSym = OutContext.CreateTempSymbol();
01065     OutStreamer.EmitLabel(DotSym);
01066 
01067     // Now that we have emitted the label, lower the complex operand expression.
01068     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
01069 
01070     const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
01071     const MCExpr *PICBase =
01072       MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), OutContext);
01073     DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
01074 
01075     DotExpr = MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(OpSym,OutContext),
01076                                       DotExpr, OutContext);
01077 
01078     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
01079       .addReg(MI->getOperand(0).getReg())
01080       .addReg(MI->getOperand(1).getReg())
01081       .addExpr(DotExpr));
01082     return;
01083   }
01084   case TargetOpcode::STATEPOINT:
01085     return LowerSTATEPOINT(OutStreamer, SM, *MI, Subtarget->is64Bit(), TM,
01086                            getSubtargetInfo(), MCInstLowering);
01087 
01088   case TargetOpcode::STACKMAP:
01089     return LowerSTACKMAP(*MI);
01090 
01091   case TargetOpcode::PATCHPOINT:
01092     return LowerPATCHPOINT(*MI);
01093 
01094   case X86::MORESTACK_RET:
01095     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01096     return;
01097 
01098   case X86::MORESTACK_RET_RESTORE_R10:
01099     // Return, then restore R10.
01100     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01101     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
01102                             .addReg(X86::R10)
01103                             .addReg(X86::RAX));
01104     return;
01105 
01106   case X86::SEH_PushReg:
01107     OutStreamer.EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
01108     return;
01109 
01110   case X86::SEH_SaveReg:
01111     OutStreamer.EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01112                                   MI->getOperand(1).getImm());
01113     return;
01114 
01115   case X86::SEH_SaveXMM:
01116     OutStreamer.EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01117                                   MI->getOperand(1).getImm());
01118     return;
01119 
01120   case X86::SEH_StackAlloc:
01121     OutStreamer.EmitWinCFIAllocStack(MI->getOperand(0).getImm());
01122     return;
01123 
01124   case X86::SEH_SetFrame:
01125     OutStreamer.EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01126                                    MI->getOperand(1).getImm());
01127     return;
01128 
01129   case X86::SEH_PushFrame:
01130     OutStreamer.EmitWinCFIPushFrame(MI->getOperand(0).getImm());
01131     return;
01132 
01133   case X86::SEH_EndPrologue:
01134     OutStreamer.EmitWinCFIEndProlog();
01135     return;
01136 
01137   case X86::SEH_Epilogue: {
01138     MachineBasicBlock::const_iterator MBBI(MI);
01139     // Check if preceded by a call and emit nop if so.
01140     for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
01141       // Conservatively assume that pseudo instructions don't emit code and keep
01142       // looking for a call. We may emit an unnecessary nop in some cases.
01143       if (!MBBI->isPseudo()) {
01144         if (MBBI->isCall())
01145           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
01146         break;
01147       }
01148     }
01149     return;
01150   }
01151 
01152     // Lower PSHUFB and VPERMILP normally but add a comment if we can find
01153     // a constant shuffle mask. We won't be able to do this at the MC layer
01154     // because the mask isn't an immediate.
01155   case X86::PSHUFBrm:
01156   case X86::VPSHUFBrm:
01157   case X86::VPSHUFBYrm: {
01158     if (!OutStreamer.isVerboseAsm())
01159       break;
01160     assert(MI->getNumOperands() > 5 &&
01161            "We should always have at least 5 operands!");
01162     const MachineOperand &DstOp = MI->getOperand(0);
01163     const MachineOperand &SrcOp = MI->getOperand(1);
01164     const MachineOperand &MaskOp = MI->getOperand(5);
01165 
01166     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01167       SmallVector<int, 16> Mask;
01168       DecodePSHUFBMask(C, Mask);
01169       if (!Mask.empty())
01170         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01171     }
01172     break;
01173   }
01174   case X86::VPERMILPSrm:
01175   case X86::VPERMILPDrm:
01176   case X86::VPERMILPSYrm:
01177   case X86::VPERMILPDYrm: {
01178     if (!OutStreamer.isVerboseAsm())
01179       break;
01180     assert(MI->getNumOperands() > 5 &&
01181            "We should always have at least 5 operands!");
01182     const MachineOperand &DstOp = MI->getOperand(0);
01183     const MachineOperand &SrcOp = MI->getOperand(1);
01184     const MachineOperand &MaskOp = MI->getOperand(5);
01185 
01186     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01187       SmallVector<int, 16> Mask;
01188       DecodeVPERMILPMask(C, Mask);
01189       if (!Mask.empty())
01190         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01191     }
01192     break;
01193   }
01194 
01195     // For loads from a constant pool to a vector register, print the constant
01196     // loaded.
01197   case X86::MOVAPDrm:
01198   case X86::VMOVAPDrm:
01199   case X86::VMOVAPDYrm:
01200   case X86::MOVUPDrm:
01201   case X86::VMOVUPDrm:
01202   case X86::VMOVUPDYrm:
01203   case X86::MOVAPSrm:
01204   case X86::VMOVAPSrm:
01205   case X86::VMOVAPSYrm:
01206   case X86::MOVUPSrm:
01207   case X86::VMOVUPSrm:
01208   case X86::VMOVUPSYrm:
01209   case X86::MOVDQArm:
01210   case X86::VMOVDQArm:
01211   case X86::VMOVDQAYrm:
01212   case X86::MOVDQUrm:
01213   case X86::VMOVDQUrm:
01214   case X86::VMOVDQUYrm:
01215     if (!OutStreamer.isVerboseAsm())
01216       break;
01217     if (MI->getNumOperands() > 4)
01218     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
01219       std::string Comment;
01220       raw_string_ostream CS(Comment);
01221       const MachineOperand &DstOp = MI->getOperand(0);
01222       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
01223       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
01224         CS << "[";
01225         for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
01226           if (i != 0)
01227             CS << ",";
01228           if (CDS->getElementType()->isIntegerTy())
01229             CS << CDS->getElementAsInteger(i);
01230           else if (CDS->getElementType()->isFloatTy())
01231             CS << CDS->getElementAsFloat(i);
01232           else if (CDS->getElementType()->isDoubleTy())
01233             CS << CDS->getElementAsDouble(i);
01234           else
01235             CS << "?";
01236         }
01237         CS << "]";
01238         OutStreamer.AddComment(CS.str());
01239       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
01240         CS << "<";
01241         for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
01242           if (i != 0)
01243             CS << ",";
01244           Constant *COp = CV->getOperand(i);
01245           if (isa<UndefValue>(COp)) {
01246             CS << "u";
01247           } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
01248             CS << CI->getZExtValue();
01249           } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
01250             SmallString<32> Str;
01251             CF->getValueAPF().toString(Str);
01252             CS << Str;
01253           } else {
01254             CS << "?";
01255           }
01256         }
01257         CS << ">";
01258         OutStreamer.AddComment(CS.str());
01259       }
01260     }
01261     break;
01262   }
01263 
01264   MCInst TmpInst;
01265   MCInstLowering.Lower(MI, TmpInst);
01266 
01267   // Stackmap shadows cannot include branch targets, so we can count the bytes
01268   // in a call towards the shadow, but must ensure that the no thread returns
01269   // in to the stackmap shadow.  The only way to achieve this is if the call
01270   // is at the end of the shadow.
01271   if (MI->isCall()) {
01272     // Count then size of the call towards the shadow
01273     SMShadowTracker.count(TmpInst, getSubtargetInfo());
01274     // Then flush the shadow so that we fill with nops before the call, not
01275     // after it.
01276     SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
01277     // Then emit the call
01278     OutStreamer.EmitInstruction(TmpInst, getSubtargetInfo());
01279     return;
01280   }
01281 
01282   EmitAndCountInstruction(TmpInst);
01283 }