LLVM  mainline
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 &F) {
00078     MF = &F;
00079     CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
00080         *MF->getSubtarget().getInstrInfo(),
00081         *MF->getSubtarget().getRegisterInfo(), 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                MF->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()), MAI(*TM.getMCAsmInfo()),
00116       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.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::TAILJMPr64_REX:
00513   case X86::CALL64r:
00514   case X86::CALL64pcrel32: {
00515     unsigned Opcode = OutMI.getOpcode();
00516     MCOperand Saved = OutMI.getOperand(0);
00517     OutMI = MCInst();
00518     OutMI.setOpcode(Opcode);
00519     OutMI.addOperand(Saved);
00520     break;
00521   }
00522 
00523   case X86::EH_RETURN:
00524   case X86::EH_RETURN64: {
00525     OutMI = MCInst();
00526     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
00527     break;
00528   }
00529 
00530   // TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
00531   case X86::TAILJMPr:
00532   case X86::TAILJMPd:
00533   case X86::TAILJMPd64: {
00534     unsigned Opcode;
00535     switch (OutMI.getOpcode()) {
00536     default: llvm_unreachable("Invalid opcode");
00537     case X86::TAILJMPr: Opcode = X86::JMP32r; break;
00538     case X86::TAILJMPd:
00539     case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
00540     }
00541 
00542     MCOperand Saved = OutMI.getOperand(0);
00543     OutMI = MCInst();
00544     OutMI.setOpcode(Opcode);
00545     OutMI.addOperand(Saved);
00546     break;
00547   }
00548 
00549   case X86::DEC16r:
00550   case X86::DEC32r:
00551   case X86::INC16r:
00552   case X86::INC32r:
00553     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
00554     if (!AsmPrinter.getSubtarget().is64Bit()) {
00555       unsigned Opcode;
00556       switch (OutMI.getOpcode()) {
00557       default: llvm_unreachable("Invalid opcode");
00558       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
00559       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
00560       case X86::INC16r: Opcode = X86::INC16r_alt; break;
00561       case X86::INC32r: Opcode = X86::INC32r_alt; break;
00562       }
00563       OutMI.setOpcode(Opcode);
00564     }
00565     break;
00566 
00567   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
00568   // this with an ugly goto in case the resultant OR uses EAX and needs the
00569   // short form.
00570   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
00571   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
00572   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
00573   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
00574   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
00575   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
00576   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
00577   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
00578   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
00579 
00580   // Atomic load and store require a separate pseudo-inst because Acquire
00581   // implies mayStore and Release implies mayLoad; fix these to regular MOV
00582   // instructions here
00583   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
00584   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
00585   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
00586   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
00587   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
00588   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
00589   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
00590   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
00591   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
00592   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
00593   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
00594   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
00595   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
00596   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
00597   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
00598   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
00599   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
00600   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
00601   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
00602   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
00603   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
00604   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
00605   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
00606   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
00607   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
00608   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
00609   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
00610   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
00611   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
00612   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
00613   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
00614   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
00615 
00616   // We don't currently select the correct instruction form for instructions
00617   // which have a short %eax, etc. form. Handle this by custom lowering, for
00618   // now.
00619   //
00620   // Note, we are currently not handling the following instructions:
00621   // MOV64ao8, MOV64o8a
00622   // XCHG16ar, XCHG32ar, XCHG64ar
00623   case X86::MOV8mr_NOREX:
00624   case X86::MOV8mr:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o32a); break;
00625   case X86::MOV8rm_NOREX:
00626   case X86::MOV8rm:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao32); break;
00627   case X86::MOV16mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o32a); break;
00628   case X86::MOV16rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao32); break;
00629   case X86::MOV32mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
00630   case X86::MOV32rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
00631 
00632   case X86::ADC8ri:     SimplifyShortImmForm(OutMI, X86::ADC8i8);    break;
00633   case X86::ADC16ri:    SimplifyShortImmForm(OutMI, X86::ADC16i16);  break;
00634   case X86::ADC32ri:    SimplifyShortImmForm(OutMI, X86::ADC32i32);  break;
00635   case X86::ADC64ri32:  SimplifyShortImmForm(OutMI, X86::ADC64i32);  break;
00636   case X86::ADD8ri:     SimplifyShortImmForm(OutMI, X86::ADD8i8);    break;
00637   case X86::ADD16ri:    SimplifyShortImmForm(OutMI, X86::ADD16i16);  break;
00638   case X86::ADD32ri:    SimplifyShortImmForm(OutMI, X86::ADD32i32);  break;
00639   case X86::ADD64ri32:  SimplifyShortImmForm(OutMI, X86::ADD64i32);  break;
00640   case X86::AND8ri:     SimplifyShortImmForm(OutMI, X86::AND8i8);    break;
00641   case X86::AND16ri:    SimplifyShortImmForm(OutMI, X86::AND16i16);  break;
00642   case X86::AND32ri:    SimplifyShortImmForm(OutMI, X86::AND32i32);  break;
00643   case X86::AND64ri32:  SimplifyShortImmForm(OutMI, X86::AND64i32);  break;
00644   case X86::CMP8ri:     SimplifyShortImmForm(OutMI, X86::CMP8i8);    break;
00645   case X86::CMP16ri:    SimplifyShortImmForm(OutMI, X86::CMP16i16);  break;
00646   case X86::CMP32ri:    SimplifyShortImmForm(OutMI, X86::CMP32i32);  break;
00647   case X86::CMP64ri32:  SimplifyShortImmForm(OutMI, X86::CMP64i32);  break;
00648   case X86::OR8ri:      SimplifyShortImmForm(OutMI, X86::OR8i8);     break;
00649   case X86::OR16ri:     SimplifyShortImmForm(OutMI, X86::OR16i16);   break;
00650   case X86::OR32ri:     SimplifyShortImmForm(OutMI, X86::OR32i32);   break;
00651   case X86::OR64ri32:   SimplifyShortImmForm(OutMI, X86::OR64i32);   break;
00652   case X86::SBB8ri:     SimplifyShortImmForm(OutMI, X86::SBB8i8);    break;
00653   case X86::SBB16ri:    SimplifyShortImmForm(OutMI, X86::SBB16i16);  break;
00654   case X86::SBB32ri:    SimplifyShortImmForm(OutMI, X86::SBB32i32);  break;
00655   case X86::SBB64ri32:  SimplifyShortImmForm(OutMI, X86::SBB64i32);  break;
00656   case X86::SUB8ri:     SimplifyShortImmForm(OutMI, X86::SUB8i8);    break;
00657   case X86::SUB16ri:    SimplifyShortImmForm(OutMI, X86::SUB16i16);  break;
00658   case X86::SUB32ri:    SimplifyShortImmForm(OutMI, X86::SUB32i32);  break;
00659   case X86::SUB64ri32:  SimplifyShortImmForm(OutMI, X86::SUB64i32);  break;
00660   case X86::TEST8ri:    SimplifyShortImmForm(OutMI, X86::TEST8i8);   break;
00661   case X86::TEST16ri:   SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
00662   case X86::TEST32ri:   SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
00663   case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
00664   case X86::XOR8ri:     SimplifyShortImmForm(OutMI, X86::XOR8i8);    break;
00665   case X86::XOR16ri:    SimplifyShortImmForm(OutMI, X86::XOR16i16);  break;
00666   case X86::XOR32ri:    SimplifyShortImmForm(OutMI, X86::XOR32i32);  break;
00667   case X86::XOR64ri32:  SimplifyShortImmForm(OutMI, X86::XOR64i32);  break;
00668 
00669   // Try to shrink some forms of movsx.
00670   case X86::MOVSX16rr8:
00671   case X86::MOVSX32rr16:
00672   case X86::MOVSX64rr32:
00673     SimplifyMOVSX(OutMI);
00674     break;
00675   }
00676 }
00677 
00678 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
00679                                  const MachineInstr &MI) {
00680 
00681   bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
00682                   MI.getOpcode() == X86::TLS_base_addr64;
00683 
00684   bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
00685 
00686   MCContext &context = OutStreamer.getContext();
00687 
00688   if (needsPadding)
00689     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00690 
00691   MCSymbolRefExpr::VariantKind SRVK;
00692   switch (MI.getOpcode()) {
00693     case X86::TLS_addr32:
00694     case X86::TLS_addr64:
00695       SRVK = MCSymbolRefExpr::VK_TLSGD;
00696       break;
00697     case X86::TLS_base_addr32:
00698       SRVK = MCSymbolRefExpr::VK_TLSLDM;
00699       break;
00700     case X86::TLS_base_addr64:
00701       SRVK = MCSymbolRefExpr::VK_TLSLD;
00702       break;
00703     default:
00704       llvm_unreachable("unexpected opcode");
00705   }
00706 
00707   MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
00708   const MCSymbolRefExpr *symRef = MCSymbolRefExpr::Create(sym, SRVK, context);
00709 
00710   MCInst LEA;
00711   if (is64Bits) {
00712     LEA.setOpcode(X86::LEA64r);
00713     LEA.addOperand(MCOperand::CreateReg(X86::RDI)); // dest
00714     LEA.addOperand(MCOperand::CreateReg(X86::RIP)); // base
00715     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00716     LEA.addOperand(MCOperand::CreateReg(0));        // index
00717     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00718     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00719   } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
00720     LEA.setOpcode(X86::LEA32r);
00721     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00722     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // base
00723     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00724     LEA.addOperand(MCOperand::CreateReg(0));        // index
00725     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00726     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00727   } else {
00728     LEA.setOpcode(X86::LEA32r);
00729     LEA.addOperand(MCOperand::CreateReg(X86::EAX)); // dest
00730     LEA.addOperand(MCOperand::CreateReg(0));        // base
00731     LEA.addOperand(MCOperand::CreateImm(1));        // scale
00732     LEA.addOperand(MCOperand::CreateReg(X86::EBX)); // index
00733     LEA.addOperand(MCOperand::CreateExpr(symRef));  // disp
00734     LEA.addOperand(MCOperand::CreateReg(0));        // seg
00735   }
00736   EmitAndCountInstruction(LEA);
00737 
00738   if (needsPadding) {
00739     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00740     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00741     EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
00742   }
00743 
00744   StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
00745   MCSymbol *tlsGetAddr = context.GetOrCreateSymbol(name);
00746   const MCSymbolRefExpr *tlsRef =
00747     MCSymbolRefExpr::Create(tlsGetAddr,
00748                             MCSymbolRefExpr::VK_PLT,
00749                             context);
00750 
00751   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
00752                                                  : X86::CALLpcrel32)
00753                             .addExpr(tlsRef));
00754 }
00755 
00756 /// \brief Emit the optimal amount of multi-byte nops on X86.
00757 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
00758   // This works only for 64bit. For 32bit we have to do additional checking if
00759   // the CPU supports multi-byte nops.
00760   assert(Is64Bit && "EmitNops only supports X86-64");
00761   while (NumBytes) {
00762     unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
00763     Opc = IndexReg = Displacement = SegmentReg = 0;
00764     BaseReg = X86::RAX; ScaleVal = 1;
00765     switch (NumBytes) {
00766     case  0: llvm_unreachable("Zero nops?"); break;
00767     case  1: NumBytes -=  1; Opc = X86::NOOP; break;
00768     case  2: NumBytes -=  2; Opc = X86::XCHG16ar; break;
00769     case  3: NumBytes -=  3; Opc = X86::NOOPL; break;
00770     case  4: NumBytes -=  4; Opc = X86::NOOPL; Displacement = 8; break;
00771     case  5: NumBytes -=  5; Opc = X86::NOOPL; Displacement = 8;
00772              IndexReg = X86::RAX; break;
00773     case  6: NumBytes -=  6; Opc = X86::NOOPW; Displacement = 8;
00774              IndexReg = X86::RAX; break;
00775     case  7: NumBytes -=  7; Opc = X86::NOOPL; Displacement = 512; break;
00776     case  8: NumBytes -=  8; Opc = X86::NOOPL; Displacement = 512;
00777              IndexReg = X86::RAX; break;
00778     case  9: NumBytes -=  9; Opc = X86::NOOPW; Displacement = 512;
00779              IndexReg = X86::RAX; break;
00780     default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
00781              IndexReg = X86::RAX; SegmentReg = X86::CS; break;
00782     }
00783 
00784     unsigned NumPrefixes = std::min(NumBytes, 5U);
00785     NumBytes -= NumPrefixes;
00786     for (unsigned i = 0; i != NumPrefixes; ++i)
00787       OS.EmitBytes("\x66");
00788 
00789     switch (Opc) {
00790     default: llvm_unreachable("Unexpected opcode"); break;
00791     case X86::NOOP:
00792       OS.EmitInstruction(MCInstBuilder(Opc), STI);
00793       break;
00794     case X86::XCHG16ar:
00795       OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
00796       break;
00797     case X86::NOOPL:
00798     case X86::NOOPW:
00799       OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
00800                          .addImm(ScaleVal).addReg(IndexReg)
00801                          .addImm(Displacement).addReg(SegmentReg), STI);
00802       break;
00803     }
00804   } // while (NumBytes)
00805 }
00806 
00807 static void LowerSTATEPOINT(MCStreamer &OS, StackMaps &SM,
00808                             const MachineInstr &MI, bool Is64Bit,
00809                             const TargetMachine& TM,
00810                             const MCSubtargetInfo& STI,
00811                             X86MCInstLower &MCInstLowering) {
00812   assert(Is64Bit && "Statepoint currently only supports X86-64");
00813 
00814   // Lower call target and choose correct opcode
00815   const MachineOperand &call_target = StatepointOpers(&MI).getCallTarget();
00816   MCOperand call_target_mcop;
00817   unsigned call_opcode;
00818   switch (call_target.getType()) {
00819   case MachineOperand::MO_GlobalAddress:
00820   case MachineOperand::MO_ExternalSymbol:
00821     call_target_mcop = MCInstLowering.LowerSymbolOperand(
00822       call_target,
00823       MCInstLowering.GetSymbolFromOperand(call_target));
00824     call_opcode = X86::CALL64pcrel32;
00825     // Currently, we only support relative addressing with statepoints.
00826     // Otherwise, we'll need a scratch register to hold the target
00827     // address.  You'll fail asserts during load & relocation if this
00828     // symbol is to far away. (TODO: support non-relative addressing)
00829     break;
00830   case MachineOperand::MO_Immediate:
00831     call_target_mcop = MCOperand::CreateImm(call_target.getImm());
00832     call_opcode = X86::CALL64pcrel32;
00833     // Currently, we only support relative addressing with statepoints.
00834     // Otherwise, we'll need a scratch register to hold the target
00835     // immediate.  You'll fail asserts during load & relocation if this
00836     // address is to far away. (TODO: support non-relative addressing)
00837     break;
00838   case MachineOperand::MO_Register:
00839     call_target_mcop = MCOperand::CreateReg(call_target.getReg());
00840     call_opcode = X86::CALL64r;
00841     break;
00842   default:
00843     llvm_unreachable("Unsupported operand type in statepoint call target");
00844     break;
00845   }
00846 
00847   // Emit call
00848   MCInst call_inst;
00849   call_inst.setOpcode(call_opcode);
00850   call_inst.addOperand(call_target_mcop);
00851   OS.EmitInstruction(call_inst, STI);
00852 
00853   // Record our statepoint node in the same section used by STACKMAP
00854   // and PATCHPOINT
00855   SM.recordStatepoint(MI);
00856 }
00857 
00858 
00859 // Lower a stackmap of the form:
00860 // <id>, <shadowBytes>, ...
00861 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
00862   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00863   SM.recordStackMap(MI);
00864   unsigned NumShadowBytes = MI.getOperand(1).getImm();
00865   SMShadowTracker.reset(NumShadowBytes);
00866 }
00867 
00868 // Lower a patchpoint of the form:
00869 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
00870 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
00871                                     X86MCInstLower &MCIL) {
00872   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
00873 
00874   SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
00875 
00876   SM.recordPatchPoint(MI);
00877 
00878   PatchPointOpers opers(&MI);
00879   unsigned ScratchIdx = opers.getNextScratchIdx();
00880   unsigned EncodedBytes = 0;
00881   const MachineOperand &CalleeMO =
00882     opers.getMetaOper(PatchPointOpers::TargetPos);
00883 
00884   // Check for null target. If target is non-null (i.e. is non-zero or is
00885   // symbolic) then emit a call.
00886   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
00887     MCOperand CalleeMCOp;
00888     switch (CalleeMO.getType()) {
00889     default:
00890       /// FIXME: Add a verifier check for bad callee types.
00891       llvm_unreachable("Unrecognized callee operand type.");
00892     case MachineOperand::MO_Immediate:
00893       if (CalleeMO.getImm())
00894         CalleeMCOp = MCOperand::CreateImm(CalleeMO.getImm());
00895       break;
00896     case MachineOperand::MO_ExternalSymbol:
00897     case MachineOperand::MO_GlobalAddress:
00898       CalleeMCOp =
00899         MCIL.LowerSymbolOperand(CalleeMO,
00900                                 MCIL.GetSymbolFromOperand(CalleeMO));
00901       break;
00902     }
00903 
00904     // Emit MOV to materialize the target address and the CALL to target.
00905     // This is encoded with 12-13 bytes, depending on which register is used.
00906     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
00907     if (X86II::isX86_64ExtendedReg(ScratchReg))
00908       EncodedBytes = 13;
00909     else
00910       EncodedBytes = 12;
00911 
00912     EmitAndCountInstruction(
00913         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
00914     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
00915   }
00916 
00917   // Emit padding.
00918   unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
00919   assert(NumBytes >= EncodedBytes &&
00920          "Patchpoint can't request size less than the length of a call.");
00921 
00922   EmitNops(OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
00923            getSubtargetInfo());
00924 }
00925 
00926 // Returns instruction preceding MBBI in MachineFunction.
00927 // If MBBI is the first instruction of the first basic block, returns null.
00928 static MachineBasicBlock::const_iterator
00929 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
00930   const MachineBasicBlock *MBB = MBBI->getParent();
00931   while (MBBI == MBB->begin()) {
00932     if (MBB == MBB->getParent()->begin())
00933       return nullptr;
00934     MBB = MBB->getPrevNode();
00935     MBBI = MBB->end();
00936   }
00937   return --MBBI;
00938 }
00939 
00940 static const Constant *getConstantFromPool(const MachineInstr &MI,
00941                                            const MachineOperand &Op) {
00942   if (!Op.isCPI())
00943     return nullptr;
00944 
00945   ArrayRef<MachineConstantPoolEntry> Constants =
00946       MI.getParent()->getParent()->getConstantPool()->getConstants();
00947   const MachineConstantPoolEntry &ConstantEntry =
00948       Constants[Op.getIndex()];
00949 
00950   // Bail if this is a machine constant pool entry, we won't be able to dig out
00951   // anything useful.
00952   if (ConstantEntry.isMachineConstantPoolEntry())
00953     return nullptr;
00954 
00955   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
00956   assert((!C || ConstantEntry.getType() == C->getType()) &&
00957          "Expected a constant of the same type!");
00958   return C;
00959 }
00960 
00961 static std::string getShuffleComment(const MachineOperand &DstOp,
00962                                      const MachineOperand &SrcOp,
00963                                      ArrayRef<int> Mask) {
00964   std::string Comment;
00965 
00966   // Compute the name for a register. This is really goofy because we have
00967   // multiple instruction printers that could (in theory) use different
00968   // names. Fortunately most people use the ATT style (outside of Windows)
00969   // and they actually agree on register naming here. Ultimately, this is
00970   // a comment, and so its OK if it isn't perfect.
00971   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
00972     return X86ATTInstPrinter::getRegisterName(RegNum);
00973   };
00974 
00975   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
00976   StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
00977 
00978   raw_string_ostream CS(Comment);
00979   CS << DstName << " = ";
00980   bool NeedComma = false;
00981   bool InSrc = false;
00982   for (int M : Mask) {
00983     // Wrap up any prior entry...
00984     if (M == SM_SentinelZero && InSrc) {
00985       InSrc = false;
00986       CS << "]";
00987     }
00988     if (NeedComma)
00989       CS << ",";
00990     else
00991       NeedComma = true;
00992 
00993     // Print this shuffle...
00994     if (M == SM_SentinelZero) {
00995       CS << "zero";
00996     } else {
00997       if (!InSrc) {
00998         InSrc = true;
00999         CS << SrcName << "[";
01000       }
01001       if (M == SM_SentinelUndef)
01002         CS << "u";
01003       else
01004         CS << M;
01005     }
01006   }
01007   if (InSrc)
01008     CS << "]";
01009   CS.flush();
01010 
01011   return Comment;
01012 }
01013 
01014 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
01015   X86MCInstLower MCInstLowering(*MF, *this);
01016   const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
01017 
01018   switch (MI->getOpcode()) {
01019   case TargetOpcode::DBG_VALUE:
01020     llvm_unreachable("Should be handled target independently");
01021 
01022   // Emit nothing here but a comment if we can.
01023   case X86::Int_MemBarrier:
01024     OutStreamer.emitRawComment("MEMBARRIER");
01025     return;
01026 
01027 
01028   case X86::EH_RETURN:
01029   case X86::EH_RETURN64: {
01030     // Lower these as normal, but add some comments.
01031     unsigned Reg = MI->getOperand(0).getReg();
01032     OutStreamer.AddComment(StringRef("eh_return, addr: %") +
01033                            X86ATTInstPrinter::getRegisterName(Reg));
01034     break;
01035   }
01036   case X86::TAILJMPr:
01037   case X86::TAILJMPm:
01038   case X86::TAILJMPd:
01039   case X86::TAILJMPr64:
01040   case X86::TAILJMPm64:
01041   case X86::TAILJMPd64:
01042   case X86::TAILJMPr64_REX:
01043   case X86::TAILJMPm64_REX:
01044   case X86::TAILJMPd64_REX:
01045     // Lower these as normal, but add some comments.
01046     OutStreamer.AddComment("TAILCALL");
01047     break;
01048 
01049   case X86::TLS_addr32:
01050   case X86::TLS_addr64:
01051   case X86::TLS_base_addr32:
01052   case X86::TLS_base_addr64:
01053     return LowerTlsAddr(MCInstLowering, *MI);
01054 
01055   case X86::MOVPC32r: {
01056     // This is a pseudo op for a two instruction sequence with a label, which
01057     // looks like:
01058     //     call "L1$pb"
01059     // "L1$pb":
01060     //     popl %esi
01061 
01062     // Emit the call.
01063     MCSymbol *PICBase = MF->getPICBaseSymbol();
01064     // FIXME: We would like an efficient form for this, so we don't have to do a
01065     // lot of extra uniquing.
01066     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
01067       .addExpr(MCSymbolRefExpr::Create(PICBase, OutContext)));
01068 
01069     // Emit the label.
01070     OutStreamer.EmitLabel(PICBase);
01071 
01072     // popl $reg
01073     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
01074                             .addReg(MI->getOperand(0).getReg()));
01075     return;
01076   }
01077 
01078   case X86::ADD32ri: {
01079     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
01080     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
01081       break;
01082 
01083     // Okay, we have something like:
01084     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
01085 
01086     // For this, we want to print something like:
01087     //   MYGLOBAL + (. - PICBASE)
01088     // However, we can't generate a ".", so just emit a new label here and refer
01089     // to it.
01090     MCSymbol *DotSym = OutContext.CreateTempSymbol();
01091     OutStreamer.EmitLabel(DotSym);
01092 
01093     // Now that we have emitted the label, lower the complex operand expression.
01094     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
01095 
01096     const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
01097     const MCExpr *PICBase =
01098       MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), OutContext);
01099     DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
01100 
01101     DotExpr = MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(OpSym,OutContext),
01102                                       DotExpr, OutContext);
01103 
01104     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
01105       .addReg(MI->getOperand(0).getReg())
01106       .addReg(MI->getOperand(1).getReg())
01107       .addExpr(DotExpr));
01108     return;
01109   }
01110   case TargetOpcode::STATEPOINT:
01111     return LowerSTATEPOINT(OutStreamer, SM, *MI, Subtarget->is64Bit(), TM,
01112                            getSubtargetInfo(), MCInstLowering);
01113 
01114   case TargetOpcode::STACKMAP:
01115     return LowerSTACKMAP(*MI);
01116 
01117   case TargetOpcode::PATCHPOINT:
01118     return LowerPATCHPOINT(*MI, MCInstLowering);
01119 
01120   case X86::MORESTACK_RET:
01121     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01122     return;
01123 
01124   case X86::MORESTACK_RET_RESTORE_R10:
01125     // Return, then restore R10.
01126     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01127     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
01128                             .addReg(X86::R10)
01129                             .addReg(X86::RAX));
01130     return;
01131 
01132   case X86::SEH_PushReg:
01133     OutStreamer.EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
01134     return;
01135 
01136   case X86::SEH_SaveReg:
01137     OutStreamer.EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01138                                   MI->getOperand(1).getImm());
01139     return;
01140 
01141   case X86::SEH_SaveXMM:
01142     OutStreamer.EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01143                                   MI->getOperand(1).getImm());
01144     return;
01145 
01146   case X86::SEH_StackAlloc:
01147     OutStreamer.EmitWinCFIAllocStack(MI->getOperand(0).getImm());
01148     return;
01149 
01150   case X86::SEH_SetFrame:
01151     OutStreamer.EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01152                                    MI->getOperand(1).getImm());
01153     return;
01154 
01155   case X86::SEH_PushFrame:
01156     OutStreamer.EmitWinCFIPushFrame(MI->getOperand(0).getImm());
01157     return;
01158 
01159   case X86::SEH_EndPrologue:
01160     OutStreamer.EmitWinCFIEndProlog();
01161     return;
01162 
01163   case X86::SEH_Epilogue: {
01164     MachineBasicBlock::const_iterator MBBI(MI);
01165     // Check if preceded by a call and emit nop if so.
01166     for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
01167       // Conservatively assume that pseudo instructions don't emit code and keep
01168       // looking for a call. We may emit an unnecessary nop in some cases.
01169       if (!MBBI->isPseudo()) {
01170         if (MBBI->isCall())
01171           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
01172         break;
01173       }
01174     }
01175     return;
01176   }
01177 
01178     // Lower PSHUFB and VPERMILP normally but add a comment if we can find
01179     // a constant shuffle mask. We won't be able to do this at the MC layer
01180     // because the mask isn't an immediate.
01181   case X86::PSHUFBrm:
01182   case X86::VPSHUFBrm:
01183   case X86::VPSHUFBYrm: {
01184     if (!OutStreamer.isVerboseAsm())
01185       break;
01186     assert(MI->getNumOperands() > 5 &&
01187            "We should always have at least 5 operands!");
01188     const MachineOperand &DstOp = MI->getOperand(0);
01189     const MachineOperand &SrcOp = MI->getOperand(1);
01190     const MachineOperand &MaskOp = MI->getOperand(5);
01191 
01192     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01193       SmallVector<int, 16> Mask;
01194       DecodePSHUFBMask(C, Mask);
01195       if (!Mask.empty())
01196         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01197     }
01198     break;
01199   }
01200   case X86::VPERMILPSrm:
01201   case X86::VPERMILPDrm:
01202   case X86::VPERMILPSYrm:
01203   case X86::VPERMILPDYrm: {
01204     if (!OutStreamer.isVerboseAsm())
01205       break;
01206     assert(MI->getNumOperands() > 5 &&
01207            "We should always have at least 5 operands!");
01208     const MachineOperand &DstOp = MI->getOperand(0);
01209     const MachineOperand &SrcOp = MI->getOperand(1);
01210     const MachineOperand &MaskOp = MI->getOperand(5);
01211 
01212     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01213       SmallVector<int, 16> Mask;
01214       DecodeVPERMILPMask(C, Mask);
01215       if (!Mask.empty())
01216         OutStreamer.AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01217     }
01218     break;
01219   }
01220 
01221     // For loads from a constant pool to a vector register, print the constant
01222     // loaded.
01223   case X86::MOVAPDrm:
01224   case X86::VMOVAPDrm:
01225   case X86::VMOVAPDYrm:
01226   case X86::MOVUPDrm:
01227   case X86::VMOVUPDrm:
01228   case X86::VMOVUPDYrm:
01229   case X86::MOVAPSrm:
01230   case X86::VMOVAPSrm:
01231   case X86::VMOVAPSYrm:
01232   case X86::MOVUPSrm:
01233   case X86::VMOVUPSrm:
01234   case X86::VMOVUPSYrm:
01235   case X86::MOVDQArm:
01236   case X86::VMOVDQArm:
01237   case X86::VMOVDQAYrm:
01238   case X86::MOVDQUrm:
01239   case X86::VMOVDQUrm:
01240   case X86::VMOVDQUYrm:
01241     if (!OutStreamer.isVerboseAsm())
01242       break;
01243     if (MI->getNumOperands() > 4)
01244     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
01245       std::string Comment;
01246       raw_string_ostream CS(Comment);
01247       const MachineOperand &DstOp = MI->getOperand(0);
01248       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
01249       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
01250         CS << "[";
01251         for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
01252           if (i != 0)
01253             CS << ",";
01254           if (CDS->getElementType()->isIntegerTy())
01255             CS << CDS->getElementAsInteger(i);
01256           else if (CDS->getElementType()->isFloatTy())
01257             CS << CDS->getElementAsFloat(i);
01258           else if (CDS->getElementType()->isDoubleTy())
01259             CS << CDS->getElementAsDouble(i);
01260           else
01261             CS << "?";
01262         }
01263         CS << "]";
01264         OutStreamer.AddComment(CS.str());
01265       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
01266         CS << "<";
01267         for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
01268           if (i != 0)
01269             CS << ",";
01270           Constant *COp = CV->getOperand(i);
01271           if (isa<UndefValue>(COp)) {
01272             CS << "u";
01273           } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
01274             CS << CI->getZExtValue();
01275           } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
01276             SmallString<32> Str;
01277             CF->getValueAPF().toString(Str);
01278             CS << Str;
01279           } else {
01280             CS << "?";
01281           }
01282         }
01283         CS << ">";
01284         OutStreamer.AddComment(CS.str());
01285       }
01286     }
01287     break;
01288   }
01289 
01290   MCInst TmpInst;
01291   MCInstLowering.Lower(MI, TmpInst);
01292 
01293   // Stackmap shadows cannot include branch targets, so we can count the bytes
01294   // in a call towards the shadow, but must ensure that the no thread returns
01295   // in to the stackmap shadow.  The only way to achieve this is if the call
01296   // is at the end of the shadow.
01297   if (MI->isCall()) {
01298     // Count then size of the call towards the shadow
01299     SMShadowTracker.count(TmpInst, getSubtargetInfo());
01300     // Then flush the shadow so that we fill with nops before the call, not
01301     // after it.
01302     SMShadowTracker.emitShadowPadding(OutStreamer, getSubtargetInfo());
01303     // Then emit the call
01304     OutStreamer.EmitInstruction(TmpInst, getSubtargetInfo());
01305     return;
01306   }
01307 
01308   EmitAndCountInstruction(TmpInst);
01309 }