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/Optional.h"
00021 #include "llvm/ADT/SmallString.h"
00022 #include "llvm/CodeGen/MachineFunction.h"
00023 #include "llvm/CodeGen/MachineConstantPool.h"
00024 #include "llvm/CodeGen/MachineOperand.h"
00025 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00026 #include "llvm/CodeGen/StackMaps.h"
00027 #include "llvm/IR/DataLayout.h"
00028 #include "llvm/IR/GlobalValue.h"
00029 #include "llvm/IR/Mangler.h"
00030 #include "llvm/MC/MCAsmInfo.h"
00031 #include "llvm/MC/MCCodeEmitter.h"
00032 #include "llvm/MC/MCContext.h"
00033 #include "llvm/MC/MCExpr.h"
00034 #include "llvm/MC/MCFixup.h"
00035 #include "llvm/MC/MCInst.h"
00036 #include "llvm/MC/MCInstBuilder.h"
00037 #include "llvm/MC/MCStreamer.h"
00038 #include "llvm/MC/MCSymbol.h"
00039 #include "llvm/Support/TargetRegistry.h"
00040 using namespace llvm;
00041 
00042 namespace {
00043 
00044 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
00045 class X86MCInstLower {
00046   MCContext &Ctx;
00047   const MachineFunction &MF;
00048   const TargetMachine &TM;
00049   const MCAsmInfo &MAI;
00050   X86AsmPrinter &AsmPrinter;
00051 public:
00052   X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
00053 
00054   Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
00055                                           const MachineOperand &MO) const;
00056   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
00057 
00058   MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
00059   MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
00060 
00061 private:
00062   MachineModuleInfoMachO &getMachOMMI() const;
00063   Mangler *getMang() const {
00064     return AsmPrinter.Mang;
00065   }
00066 };
00067 
00068 } // end anonymous namespace
00069 
00070 // Emit a minimal sequence of nops spanning NumBytes bytes.
00071 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
00072                      const MCSubtargetInfo &STI);
00073 
00074 namespace llvm {
00075    X86AsmPrinter::StackMapShadowTracker::StackMapShadowTracker(TargetMachine &TM)
00076      : TM(TM), InShadow(false), RequiredShadowSize(0), CurrentShadowSize(0) {}
00077 
00078   X86AsmPrinter::StackMapShadowTracker::~StackMapShadowTracker() {}
00079 
00080   void
00081   X86AsmPrinter::StackMapShadowTracker::startFunction(MachineFunction &F) {
00082     MF = &F;
00083     CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
00084         *MF->getSubtarget().getInstrInfo(),
00085         *MF->getSubtarget().getRegisterInfo(), MF->getContext()));
00086   }
00087 
00088   void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
00089                                                    const MCSubtargetInfo &STI) {
00090     if (InShadow) {
00091       SmallString<256> Code;
00092       SmallVector<MCFixup, 4> Fixups;
00093       raw_svector_ostream VecOS(Code);
00094       CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
00095       VecOS.flush();
00096       CurrentShadowSize += Code.size();
00097       if (CurrentShadowSize >= RequiredShadowSize)
00098         InShadow = false; // The shadow is big enough. Stop counting.
00099     }
00100   }
00101 
00102   void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
00103     MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
00104     if (InShadow && CurrentShadowSize < RequiredShadowSize) {
00105       InShadow = false;
00106       EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
00107                MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
00108     }
00109   }
00110 
00111   void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
00112     OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
00113     SMShadowTracker.count(Inst, getSubtargetInfo());
00114   }
00115 } // end llvm namespace
00116 
00117 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
00118                                X86AsmPrinter &asmprinter)
00119     : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
00120       AsmPrinter(asmprinter) {}
00121 
00122 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
00123   return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
00124 }
00125 
00126 
00127 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
00128 /// operand to an MCSymbol.
00129 MCSymbol *X86MCInstLower::
00130 GetSymbolFromOperand(const MachineOperand &MO) const {
00131   const DataLayout *DL = TM.getDataLayout();
00132   assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
00133 
00134   MCSymbol *Sym = nullptr;
00135   SmallString<128> Name;
00136   StringRef Suffix;
00137 
00138   switch (MO.getTargetFlags()) {
00139   case X86II::MO_DLLIMPORT:
00140     // Handle dllimport linkage.
00141     Name += "__imp_";
00142     break;
00143   case X86II::MO_DARWIN_STUB:
00144     Suffix = "$stub";
00145     break;
00146   case X86II::MO_DARWIN_NONLAZY:
00147   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00148   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00149     Suffix = "$non_lazy_ptr";
00150     break;
00151   }
00152 
00153   if (!Suffix.empty())
00154     Name += DL->getPrivateGlobalPrefix();
00155 
00156   unsigned PrefixLen = Name.size();
00157 
00158   if (MO.isGlobal()) {
00159     const GlobalValue *GV = MO.getGlobal();
00160     AsmPrinter.getNameWithPrefix(Name, GV);
00161   } else if (MO.isSymbol()) {
00162     Mangler::getNameWithPrefix(Name, MO.getSymbolName(), *DL);
00163   } else if (MO.isMBB()) {
00164     assert(Suffix.empty());
00165     Sym = MO.getMBB()->getSymbol();
00166   }
00167   unsigned OrigLen = Name.size() - PrefixLen;
00168 
00169   Name += Suffix;
00170   if (!Sym)
00171     Sym = Ctx.getOrCreateSymbol(Name);
00172 
00173   StringRef OrigName = StringRef(Name).substr(PrefixLen, OrigLen);
00174 
00175   // If the target flags on the operand changes the name of the symbol, do that
00176   // before we return the symbol.
00177   switch (MO.getTargetFlags()) {
00178   default: break;
00179   case X86II::MO_DARWIN_NONLAZY:
00180   case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
00181     MachineModuleInfoImpl::StubValueTy &StubSym =
00182       getMachOMMI().getGVStubEntry(Sym);
00183     if (!StubSym.getPointer()) {
00184       assert(MO.isGlobal() && "Extern symbol not handled yet");
00185       StubSym =
00186         MachineModuleInfoImpl::
00187         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00188                     !MO.getGlobal()->hasInternalLinkage());
00189     }
00190     break;
00191   }
00192   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE: {
00193     MachineModuleInfoImpl::StubValueTy &StubSym =
00194       getMachOMMI().getHiddenGVStubEntry(Sym);
00195     if (!StubSym.getPointer()) {
00196       assert(MO.isGlobal() && "Extern symbol not handled yet");
00197       StubSym =
00198         MachineModuleInfoImpl::
00199         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00200                     !MO.getGlobal()->hasInternalLinkage());
00201     }
00202     break;
00203   }
00204   case X86II::MO_DARWIN_STUB: {
00205     MachineModuleInfoImpl::StubValueTy &StubSym =
00206       getMachOMMI().getFnStubEntry(Sym);
00207     if (StubSym.getPointer())
00208       return Sym;
00209 
00210     if (MO.isGlobal()) {
00211       StubSym =
00212         MachineModuleInfoImpl::
00213         StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
00214                     !MO.getGlobal()->hasInternalLinkage());
00215     } else {
00216       StubSym =
00217         MachineModuleInfoImpl::
00218         StubValueTy(Ctx.getOrCreateSymbol(OrigName), false);
00219     }
00220     break;
00221   }
00222   }
00223 
00224   return Sym;
00225 }
00226 
00227 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
00228                                              MCSymbol *Sym) const {
00229   // FIXME: We would like an efficient form for this, so we don't have to do a
00230   // lot of extra uniquing.
00231   const MCExpr *Expr = nullptr;
00232   MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
00233 
00234   switch (MO.getTargetFlags()) {
00235   default: llvm_unreachable("Unknown target flag on GV operand");
00236   case X86II::MO_NO_FLAG:    // No flag.
00237   // These affect the name of the symbol, not any suffix.
00238   case X86II::MO_DARWIN_NONLAZY:
00239   case X86II::MO_DLLIMPORT:
00240   case X86II::MO_DARWIN_STUB:
00241     break;
00242 
00243   case X86II::MO_TLVP:      RefKind = MCSymbolRefExpr::VK_TLVP; break;
00244   case X86II::MO_TLVP_PIC_BASE:
00245     Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
00246     // Subtract the pic base.
00247     Expr = MCBinaryExpr::createSub(Expr,
00248                                   MCSymbolRefExpr::create(MF.getPICBaseSymbol(),
00249                                                            Ctx),
00250                                    Ctx);
00251     break;
00252   case X86II::MO_SECREL:    RefKind = MCSymbolRefExpr::VK_SECREL; break;
00253   case X86II::MO_TLSGD:     RefKind = MCSymbolRefExpr::VK_TLSGD; break;
00254   case X86II::MO_TLSLD:     RefKind = MCSymbolRefExpr::VK_TLSLD; break;
00255   case X86II::MO_TLSLDM:    RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
00256   case X86II::MO_GOTTPOFF:  RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
00257   case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
00258   case X86II::MO_TPOFF:     RefKind = MCSymbolRefExpr::VK_TPOFF; break;
00259   case X86II::MO_DTPOFF:    RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
00260   case X86II::MO_NTPOFF:    RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
00261   case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
00262   case X86II::MO_GOTPCREL:  RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
00263   case X86II::MO_GOT:       RefKind = MCSymbolRefExpr::VK_GOT; break;
00264   case X86II::MO_GOTOFF:    RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
00265   case X86II::MO_PLT:       RefKind = MCSymbolRefExpr::VK_PLT; break;
00266   case X86II::MO_PIC_BASE_OFFSET:
00267   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
00268   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
00269     Expr = MCSymbolRefExpr::create(Sym, Ctx);
00270     // Subtract the pic base.
00271     Expr = MCBinaryExpr::createSub(Expr,
00272                             MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx),
00273                                    Ctx);
00274     if (MO.isJTI()) {
00275       assert(MAI.doesSetDirectiveSuppressesReloc());
00276       // If .set directive is supported, use it to reduce the number of
00277       // relocations the assembler will generate for differences between
00278       // local labels. This is only safe when the symbols are in the same
00279       // section so we are restricting it to jumptable references.
00280       MCSymbol *Label = Ctx.createTempSymbol();
00281       AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
00282       Expr = MCSymbolRefExpr::create(Label, Ctx);
00283     }
00284     break;
00285   }
00286 
00287   if (!Expr)
00288     Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
00289 
00290   if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
00291     Expr = MCBinaryExpr::createAdd(Expr,
00292                                    MCConstantExpr::create(MO.getOffset(), Ctx),
00293                                    Ctx);
00294   return MCOperand::createExpr(Expr);
00295 }
00296 
00297 
00298 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
00299 /// a short fixed-register form.
00300 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
00301   unsigned ImmOp = Inst.getNumOperands() - 1;
00302   assert(Inst.getOperand(0).isReg() &&
00303          (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
00304          ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
00305            Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
00306           Inst.getNumOperands() == 2) && "Unexpected instruction!");
00307 
00308   // Check whether the destination register can be fixed.
00309   unsigned Reg = Inst.getOperand(0).getReg();
00310   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00311     return;
00312 
00313   // If so, rewrite the instruction.
00314   MCOperand Saved = Inst.getOperand(ImmOp);
00315   Inst = MCInst();
00316   Inst.setOpcode(Opcode);
00317   Inst.addOperand(Saved);
00318 }
00319 
00320 /// \brief If a movsx instruction has a shorter encoding for the used register
00321 /// simplify the instruction to use it instead.
00322 static void SimplifyMOVSX(MCInst &Inst) {
00323   unsigned NewOpcode = 0;
00324   unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
00325   switch (Inst.getOpcode()) {
00326   default:
00327     llvm_unreachable("Unexpected instruction!");
00328   case X86::MOVSX16rr8:  // movsbw %al, %ax   --> cbtw
00329     if (Op0 == X86::AX && Op1 == X86::AL)
00330       NewOpcode = X86::CBW;
00331     break;
00332   case X86::MOVSX32rr16: // movswl %ax, %eax  --> cwtl
00333     if (Op0 == X86::EAX && Op1 == X86::AX)
00334       NewOpcode = X86::CWDE;
00335     break;
00336   case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
00337     if (Op0 == X86::RAX && Op1 == X86::EAX)
00338       NewOpcode = X86::CDQE;
00339     break;
00340   }
00341 
00342   if (NewOpcode != 0) {
00343     Inst = MCInst();
00344     Inst.setOpcode(NewOpcode);
00345   }
00346 }
00347 
00348 /// \brief Simplify things like MOV32rm to MOV32o32a.
00349 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
00350                                   unsigned Opcode) {
00351   // Don't make these simplifications in 64-bit mode; other assemblers don't
00352   // perform them because they make the code larger.
00353   if (Printer.getSubtarget().is64Bit())
00354     return;
00355 
00356   bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
00357   unsigned AddrBase = IsStore;
00358   unsigned RegOp = IsStore ? 0 : 5;
00359   unsigned AddrOp = AddrBase + 3;
00360   assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
00361          Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
00362          Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
00363          Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
00364          Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
00365          (Inst.getOperand(AddrOp).isExpr() ||
00366           Inst.getOperand(AddrOp).isImm()) &&
00367          "Unexpected instruction!");
00368 
00369   // Check whether the destination register can be fixed.
00370   unsigned Reg = Inst.getOperand(RegOp).getReg();
00371   if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
00372     return;
00373 
00374   // Check whether this is an absolute address.
00375   // FIXME: We know TLVP symbol refs aren't, but there should be a better way
00376   // to do this here.
00377   bool Absolute = true;
00378   if (Inst.getOperand(AddrOp).isExpr()) {
00379     const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
00380     if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
00381       if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
00382         Absolute = false;
00383   }
00384 
00385   if (Absolute &&
00386       (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
00387        Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
00388        Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
00389     return;
00390 
00391   // If so, rewrite the instruction.
00392   MCOperand Saved = Inst.getOperand(AddrOp);
00393   MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
00394   Inst = MCInst();
00395   Inst.setOpcode(Opcode);
00396   Inst.addOperand(Saved);
00397   Inst.addOperand(Seg);
00398 }
00399 
00400 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
00401   return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
00402 }
00403 
00404 Optional<MCOperand>
00405 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
00406                                     const MachineOperand &MO) const {
00407   switch (MO.getType()) {
00408   default:
00409     MI->dump();
00410     llvm_unreachable("unknown operand type");
00411   case MachineOperand::MO_Register:
00412     // Ignore all implicit register operands.
00413     if (MO.isImplicit())
00414       return None;
00415     return MCOperand::createReg(MO.getReg());
00416   case MachineOperand::MO_Immediate:
00417     return MCOperand::createImm(MO.getImm());
00418   case MachineOperand::MO_MachineBasicBlock:
00419   case MachineOperand::MO_GlobalAddress:
00420   case MachineOperand::MO_ExternalSymbol:
00421     return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
00422   case MachineOperand::MO_MCSymbol:
00423     return LowerSymbolOperand(MO, MO.getMCSymbol());
00424   case MachineOperand::MO_JumpTableIndex:
00425     return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
00426   case MachineOperand::MO_ConstantPoolIndex:
00427     return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
00428   case MachineOperand::MO_BlockAddress:
00429     return LowerSymbolOperand(
00430         MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
00431   case MachineOperand::MO_RegisterMask:
00432     // Ignore call clobbers.
00433     return None;
00434   }
00435 }
00436 
00437 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
00438   OutMI.setOpcode(MI->getOpcode());
00439 
00440   for (const MachineOperand &MO : MI->operands())
00441     if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
00442       OutMI.addOperand(MaybeMCOp.getValue());
00443 
00444   // Handle a few special cases to eliminate operand modifiers.
00445 ReSimplify:
00446   switch (OutMI.getOpcode()) {
00447   case X86::LEA64_32r:
00448   case X86::LEA64r:
00449   case X86::LEA16r:
00450   case X86::LEA32r:
00451     // LEA should have a segment register, but it must be empty.
00452     assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
00453            "Unexpected # of LEA operands");
00454     assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
00455            "LEA has segment specified!");
00456     break;
00457 
00458   case X86::MOV32ri64:
00459     OutMI.setOpcode(X86::MOV32ri);
00460     break;
00461 
00462   // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
00463   // if one of the registers is extended, but other isn't.
00464   case X86::VMOVAPDrr:
00465   case X86::VMOVAPDYrr:
00466   case X86::VMOVAPSrr:
00467   case X86::VMOVAPSYrr:
00468   case X86::VMOVDQArr:
00469   case X86::VMOVDQAYrr:
00470   case X86::VMOVDQUrr:
00471   case X86::VMOVDQUYrr:
00472   case X86::VMOVUPDrr:
00473   case X86::VMOVUPDYrr:
00474   case X86::VMOVUPSrr:
00475   case X86::VMOVUPSYrr: {
00476     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00477         X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
00478       unsigned NewOpc;
00479       switch (OutMI.getOpcode()) {
00480       default: llvm_unreachable("Invalid opcode");
00481       case X86::VMOVAPDrr:  NewOpc = X86::VMOVAPDrr_REV;  break;
00482       case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
00483       case X86::VMOVAPSrr:  NewOpc = X86::VMOVAPSrr_REV;  break;
00484       case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
00485       case X86::VMOVDQArr:  NewOpc = X86::VMOVDQArr_REV;  break;
00486       case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
00487       case X86::VMOVDQUrr:  NewOpc = X86::VMOVDQUrr_REV;  break;
00488       case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
00489       case X86::VMOVUPDrr:  NewOpc = X86::VMOVUPDrr_REV;  break;
00490       case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
00491       case X86::VMOVUPSrr:  NewOpc = X86::VMOVUPSrr_REV;  break;
00492       case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
00493       }
00494       OutMI.setOpcode(NewOpc);
00495     }
00496     break;
00497   }
00498   case X86::VMOVSDrr:
00499   case X86::VMOVSSrr: {
00500     if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
00501         X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
00502       unsigned NewOpc;
00503       switch (OutMI.getOpcode()) {
00504       default: llvm_unreachable("Invalid opcode");
00505       case X86::VMOVSDrr:   NewOpc = X86::VMOVSDrr_REV;   break;
00506       case X86::VMOVSSrr:   NewOpc = X86::VMOVSSrr_REV;   break;
00507       }
00508       OutMI.setOpcode(NewOpc);
00509     }
00510     break;
00511   }
00512 
00513   // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
00514   // inputs modeled as normal uses instead of implicit uses.  As such, truncate
00515   // off all but the first operand (the callee).  FIXME: Change isel.
00516   case X86::TAILJMPr64:
00517   case X86::TAILJMPr64_REX:
00518   case X86::CALL64r:
00519   case X86::CALL64pcrel32: {
00520     unsigned Opcode = OutMI.getOpcode();
00521     MCOperand Saved = OutMI.getOperand(0);
00522     OutMI = MCInst();
00523     OutMI.setOpcode(Opcode);
00524     OutMI.addOperand(Saved);
00525     break;
00526   }
00527 
00528   case X86::EH_RETURN:
00529   case X86::EH_RETURN64: {
00530     OutMI = MCInst();
00531     OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
00532     break;
00533   }
00534 
00535   // TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
00536   case X86::TAILJMPr:
00537   case X86::TAILJMPd:
00538   case X86::TAILJMPd64: {
00539     unsigned Opcode;
00540     switch (OutMI.getOpcode()) {
00541     default: llvm_unreachable("Invalid opcode");
00542     case X86::TAILJMPr: Opcode = X86::JMP32r; break;
00543     case X86::TAILJMPd:
00544     case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
00545     }
00546 
00547     MCOperand Saved = OutMI.getOperand(0);
00548     OutMI = MCInst();
00549     OutMI.setOpcode(Opcode);
00550     OutMI.addOperand(Saved);
00551     break;
00552   }
00553 
00554   case X86::DEC16r:
00555   case X86::DEC32r:
00556   case X86::INC16r:
00557   case X86::INC32r:
00558     // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
00559     if (!AsmPrinter.getSubtarget().is64Bit()) {
00560       unsigned Opcode;
00561       switch (OutMI.getOpcode()) {
00562       default: llvm_unreachable("Invalid opcode");
00563       case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
00564       case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
00565       case X86::INC16r: Opcode = X86::INC16r_alt; break;
00566       case X86::INC32r: Opcode = X86::INC32r_alt; break;
00567       }
00568       OutMI.setOpcode(Opcode);
00569     }
00570     break;
00571 
00572   // These are pseudo-ops for OR to help with the OR->ADD transformation.  We do
00573   // this with an ugly goto in case the resultant OR uses EAX and needs the
00574   // short form.
00575   case X86::ADD16rr_DB:   OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
00576   case X86::ADD32rr_DB:   OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
00577   case X86::ADD64rr_DB:   OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
00578   case X86::ADD16ri_DB:   OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
00579   case X86::ADD32ri_DB:   OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
00580   case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
00581   case X86::ADD16ri8_DB:  OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
00582   case X86::ADD32ri8_DB:  OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
00583   case X86::ADD64ri8_DB:  OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
00584 
00585   // Atomic load and store require a separate pseudo-inst because Acquire
00586   // implies mayStore and Release implies mayLoad; fix these to regular MOV
00587   // instructions here
00588   case X86::ACQUIRE_MOV8rm:    OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
00589   case X86::ACQUIRE_MOV16rm:   OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
00590   case X86::ACQUIRE_MOV32rm:   OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
00591   case X86::ACQUIRE_MOV64rm:   OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
00592   case X86::RELEASE_MOV8mr:    OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
00593   case X86::RELEASE_MOV16mr:   OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
00594   case X86::RELEASE_MOV32mr:   OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
00595   case X86::RELEASE_MOV64mr:   OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
00596   case X86::RELEASE_MOV8mi:    OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
00597   case X86::RELEASE_MOV16mi:   OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
00598   case X86::RELEASE_MOV32mi:   OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
00599   case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
00600   case X86::RELEASE_ADD8mi:    OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
00601   case X86::RELEASE_ADD32mi:   OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
00602   case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
00603   case X86::RELEASE_AND8mi:    OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
00604   case X86::RELEASE_AND32mi:   OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
00605   case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
00606   case X86::RELEASE_OR8mi:     OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
00607   case X86::RELEASE_OR32mi:    OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
00608   case X86::RELEASE_OR64mi32:  OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
00609   case X86::RELEASE_XOR8mi:    OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
00610   case X86::RELEASE_XOR32mi:   OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
00611   case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
00612   case X86::RELEASE_INC8m:     OutMI.setOpcode(X86::INC8m); goto ReSimplify;
00613   case X86::RELEASE_INC16m:    OutMI.setOpcode(X86::INC16m); goto ReSimplify;
00614   case X86::RELEASE_INC32m:    OutMI.setOpcode(X86::INC32m); goto ReSimplify;
00615   case X86::RELEASE_INC64m:    OutMI.setOpcode(X86::INC64m); goto ReSimplify;
00616   case X86::RELEASE_DEC8m:     OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
00617   case X86::RELEASE_DEC16m:    OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
00618   case X86::RELEASE_DEC32m:    OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
00619   case X86::RELEASE_DEC64m:    OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
00620 
00621   // We don't currently select the correct instruction form for instructions
00622   // which have a short %eax, etc. form. Handle this by custom lowering, for
00623   // now.
00624   //
00625   // Note, we are currently not handling the following instructions:
00626   // MOV64ao8, MOV64o8a
00627   // XCHG16ar, XCHG32ar, XCHG64ar
00628   case X86::MOV8mr_NOREX:
00629   case X86::MOV8mr:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o32a); break;
00630   case X86::MOV8rm_NOREX:
00631   case X86::MOV8rm:     SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao32); break;
00632   case X86::MOV16mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o32a); break;
00633   case X86::MOV16rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao32); break;
00634   case X86::MOV32mr:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
00635   case X86::MOV32rm:    SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
00636 
00637   case X86::ADC8ri:     SimplifyShortImmForm(OutMI, X86::ADC8i8);    break;
00638   case X86::ADC16ri:    SimplifyShortImmForm(OutMI, X86::ADC16i16);  break;
00639   case X86::ADC32ri:    SimplifyShortImmForm(OutMI, X86::ADC32i32);  break;
00640   case X86::ADC64ri32:  SimplifyShortImmForm(OutMI, X86::ADC64i32);  break;
00641   case X86::ADD8ri:     SimplifyShortImmForm(OutMI, X86::ADD8i8);    break;
00642   case X86::ADD16ri:    SimplifyShortImmForm(OutMI, X86::ADD16i16);  break;
00643   case X86::ADD32ri:    SimplifyShortImmForm(OutMI, X86::ADD32i32);  break;
00644   case X86::ADD64ri32:  SimplifyShortImmForm(OutMI, X86::ADD64i32);  break;
00645   case X86::AND8ri:     SimplifyShortImmForm(OutMI, X86::AND8i8);    break;
00646   case X86::AND16ri:    SimplifyShortImmForm(OutMI, X86::AND16i16);  break;
00647   case X86::AND32ri:    SimplifyShortImmForm(OutMI, X86::AND32i32);  break;
00648   case X86::AND64ri32:  SimplifyShortImmForm(OutMI, X86::AND64i32);  break;
00649   case X86::CMP8ri:     SimplifyShortImmForm(OutMI, X86::CMP8i8);    break;
00650   case X86::CMP16ri:    SimplifyShortImmForm(OutMI, X86::CMP16i16);  break;
00651   case X86::CMP32ri:    SimplifyShortImmForm(OutMI, X86::CMP32i32);  break;
00652   case X86::CMP64ri32:  SimplifyShortImmForm(OutMI, X86::CMP64i32);  break;
00653   case X86::OR8ri:      SimplifyShortImmForm(OutMI, X86::OR8i8);     break;
00654   case X86::OR16ri:     SimplifyShortImmForm(OutMI, X86::OR16i16);   break;
00655   case X86::OR32ri:     SimplifyShortImmForm(OutMI, X86::OR32i32);   break;
00656   case X86::OR64ri32:   SimplifyShortImmForm(OutMI, X86::OR64i32);   break;
00657   case X86::SBB8ri:     SimplifyShortImmForm(OutMI, X86::SBB8i8);    break;
00658   case X86::SBB16ri:    SimplifyShortImmForm(OutMI, X86::SBB16i16);  break;
00659   case X86::SBB32ri:    SimplifyShortImmForm(OutMI, X86::SBB32i32);  break;
00660   case X86::SBB64ri32:  SimplifyShortImmForm(OutMI, X86::SBB64i32);  break;
00661   case X86::SUB8ri:     SimplifyShortImmForm(OutMI, X86::SUB8i8);    break;
00662   case X86::SUB16ri:    SimplifyShortImmForm(OutMI, X86::SUB16i16);  break;
00663   case X86::SUB32ri:    SimplifyShortImmForm(OutMI, X86::SUB32i32);  break;
00664   case X86::SUB64ri32:  SimplifyShortImmForm(OutMI, X86::SUB64i32);  break;
00665   case X86::TEST8ri:    SimplifyShortImmForm(OutMI, X86::TEST8i8);   break;
00666   case X86::TEST16ri:   SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
00667   case X86::TEST32ri:   SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
00668   case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
00669   case X86::XOR8ri:     SimplifyShortImmForm(OutMI, X86::XOR8i8);    break;
00670   case X86::XOR16ri:    SimplifyShortImmForm(OutMI, X86::XOR16i16);  break;
00671   case X86::XOR32ri:    SimplifyShortImmForm(OutMI, X86::XOR32i32);  break;
00672   case X86::XOR64ri32:  SimplifyShortImmForm(OutMI, X86::XOR64i32);  break;
00673 
00674   // Try to shrink some forms of movsx.
00675   case X86::MOVSX16rr8:
00676   case X86::MOVSX32rr16:
00677   case X86::MOVSX64rr32:
00678     SimplifyMOVSX(OutMI);
00679     break;
00680   }
00681 }
00682 
00683 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
00684                                  const MachineInstr &MI) {
00685 
00686   bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
00687                   MI.getOpcode() == X86::TLS_base_addr64;
00688 
00689   bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
00690 
00691   MCContext &context = OutStreamer->getContext();
00692 
00693   if (needsPadding)
00694     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00695 
00696   MCSymbolRefExpr::VariantKind SRVK;
00697   switch (MI.getOpcode()) {
00698     case X86::TLS_addr32:
00699     case X86::TLS_addr64:
00700       SRVK = MCSymbolRefExpr::VK_TLSGD;
00701       break;
00702     case X86::TLS_base_addr32:
00703       SRVK = MCSymbolRefExpr::VK_TLSLDM;
00704       break;
00705     case X86::TLS_base_addr64:
00706       SRVK = MCSymbolRefExpr::VK_TLSLD;
00707       break;
00708     default:
00709       llvm_unreachable("unexpected opcode");
00710   }
00711 
00712   MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
00713   const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
00714 
00715   MCInst LEA;
00716   if (is64Bits) {
00717     LEA.setOpcode(X86::LEA64r);
00718     LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
00719     LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
00720     LEA.addOperand(MCOperand::createImm(1));        // scale
00721     LEA.addOperand(MCOperand::createReg(0));        // index
00722     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
00723     LEA.addOperand(MCOperand::createReg(0));        // seg
00724   } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
00725     LEA.setOpcode(X86::LEA32r);
00726     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
00727     LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
00728     LEA.addOperand(MCOperand::createImm(1));        // scale
00729     LEA.addOperand(MCOperand::createReg(0));        // index
00730     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
00731     LEA.addOperand(MCOperand::createReg(0));        // seg
00732   } else {
00733     LEA.setOpcode(X86::LEA32r);
00734     LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
00735     LEA.addOperand(MCOperand::createReg(0));        // base
00736     LEA.addOperand(MCOperand::createImm(1));        // scale
00737     LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
00738     LEA.addOperand(MCOperand::createExpr(symRef));  // disp
00739     LEA.addOperand(MCOperand::createReg(0));        // seg
00740   }
00741   EmitAndCountInstruction(LEA);
00742 
00743   if (needsPadding) {
00744     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00745     EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
00746     EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
00747   }
00748 
00749   StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
00750   MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
00751   const MCSymbolRefExpr *tlsRef =
00752     MCSymbolRefExpr::create(tlsGetAddr,
00753                             MCSymbolRefExpr::VK_PLT,
00754                             context);
00755 
00756   EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
00757                                                  : X86::CALLpcrel32)
00758                             .addExpr(tlsRef));
00759 }
00760 
00761 /// \brief Emit the optimal amount of multi-byte nops on X86.
00762 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
00763   // This works only for 64bit. For 32bit we have to do additional checking if
00764   // the CPU supports multi-byte nops.
00765   assert(Is64Bit && "EmitNops only supports X86-64");
00766   while (NumBytes) {
00767     unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
00768     Opc = IndexReg = Displacement = SegmentReg = 0;
00769     BaseReg = X86::RAX; ScaleVal = 1;
00770     switch (NumBytes) {
00771     case  0: llvm_unreachable("Zero nops?"); break;
00772     case  1: NumBytes -=  1; Opc = X86::NOOP; break;
00773     case  2: NumBytes -=  2; Opc = X86::XCHG16ar; break;
00774     case  3: NumBytes -=  3; Opc = X86::NOOPL; break;
00775     case  4: NumBytes -=  4; Opc = X86::NOOPL; Displacement = 8; break;
00776     case  5: NumBytes -=  5; Opc = X86::NOOPL; Displacement = 8;
00777              IndexReg = X86::RAX; break;
00778     case  6: NumBytes -=  6; Opc = X86::NOOPW; Displacement = 8;
00779              IndexReg = X86::RAX; break;
00780     case  7: NumBytes -=  7; Opc = X86::NOOPL; Displacement = 512; break;
00781     case  8: NumBytes -=  8; Opc = X86::NOOPL; Displacement = 512;
00782              IndexReg = X86::RAX; break;
00783     case  9: NumBytes -=  9; Opc = X86::NOOPW; Displacement = 512;
00784              IndexReg = X86::RAX; break;
00785     default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
00786              IndexReg = X86::RAX; SegmentReg = X86::CS; break;
00787     }
00788 
00789     unsigned NumPrefixes = std::min(NumBytes, 5U);
00790     NumBytes -= NumPrefixes;
00791     for (unsigned i = 0; i != NumPrefixes; ++i)
00792       OS.EmitBytes("\x66");
00793 
00794     switch (Opc) {
00795     default: llvm_unreachable("Unexpected opcode"); break;
00796     case X86::NOOP:
00797       OS.EmitInstruction(MCInstBuilder(Opc), STI);
00798       break;
00799     case X86::XCHG16ar:
00800       OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
00801       break;
00802     case X86::NOOPL:
00803     case X86::NOOPW:
00804       OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
00805                          .addImm(ScaleVal).addReg(IndexReg)
00806                          .addImm(Displacement).addReg(SegmentReg), STI);
00807       break;
00808     }
00809   } // while (NumBytes)
00810 }
00811 
00812 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
00813                                     X86MCInstLower &MCIL) {
00814   assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
00815 
00816   StatepointOpers SOpers(&MI);
00817   if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
00818     EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
00819              getSubtargetInfo());
00820   } else {
00821     // Lower call target and choose correct opcode
00822     const MachineOperand &CallTarget = SOpers.getCallTarget();
00823     MCOperand CallTargetMCOp;
00824     unsigned CallOpcode;
00825     switch (CallTarget.getType()) {
00826     case MachineOperand::MO_GlobalAddress:
00827     case MachineOperand::MO_ExternalSymbol:
00828       CallTargetMCOp = MCIL.LowerSymbolOperand(
00829           CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
00830       CallOpcode = X86::CALL64pcrel32;
00831       // Currently, we only support relative addressing with statepoints.
00832       // Otherwise, we'll need a scratch register to hold the target
00833       // address.  You'll fail asserts during load & relocation if this
00834       // symbol is to far away. (TODO: support non-relative addressing)
00835       break;
00836     case MachineOperand::MO_Immediate:
00837       CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
00838       CallOpcode = X86::CALL64pcrel32;
00839       // Currently, we only support relative addressing with statepoints.
00840       // Otherwise, we'll need a scratch register to hold the target
00841       // immediate.  You'll fail asserts during load & relocation if this
00842       // address is to far away. (TODO: support non-relative addressing)
00843       break;
00844     case MachineOperand::MO_Register:
00845       CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
00846       CallOpcode = X86::CALL64r;
00847       break;
00848     default:
00849       llvm_unreachable("Unsupported operand type in statepoint call target");
00850       break;
00851     }
00852 
00853     // Emit call
00854     MCInst CallInst;
00855     CallInst.setOpcode(CallOpcode);
00856     CallInst.addOperand(CallTargetMCOp);
00857     OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
00858   }
00859 
00860   // Record our statepoint node in the same section used by STACKMAP
00861   // and PATCHPOINT
00862   SM.recordStatepoint(MI);
00863 }
00864 
00865 void X86AsmPrinter::LowerFAULTING_LOAD_OP(const MachineInstr &MI,
00866                                        X86MCInstLower &MCIL) {
00867   // FAULTING_LOAD_OP <def>, <handler label>, <load opcode>, <load operands>
00868 
00869   unsigned LoadDefRegister = MI.getOperand(0).getReg();
00870   MCSymbol *HandlerLabel = MI.getOperand(1).getMCSymbol();
00871   unsigned LoadOpcode = MI.getOperand(2).getImm();
00872   unsigned LoadOperandsBeginIdx = 3;
00873 
00874   FM.recordFaultingOp(FaultMaps::FaultingLoad, HandlerLabel);
00875 
00876   MCInst LoadMI;
00877   LoadMI.setOpcode(LoadOpcode);
00878   LoadMI.addOperand(MCOperand::createReg(LoadDefRegister));
00879   for (auto I = MI.operands_begin() + LoadOperandsBeginIdx,
00880             E = MI.operands_end();
00881        I != E; ++I)
00882     if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, *I))
00883       LoadMI.addOperand(MaybeOperand.getValue());
00884 
00885   OutStreamer->EmitInstruction(LoadMI, getSubtargetInfo());
00886 }
00887 
00888 // Lower a stackmap of the form:
00889 // <id>, <shadowBytes>, ...
00890 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
00891   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
00892   SM.recordStackMap(MI);
00893   unsigned NumShadowBytes = MI.getOperand(1).getImm();
00894   SMShadowTracker.reset(NumShadowBytes);
00895 }
00896 
00897 // Lower a patchpoint of the form:
00898 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
00899 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
00900                                     X86MCInstLower &MCIL) {
00901   assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
00902 
00903   SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
00904 
00905   SM.recordPatchPoint(MI);
00906 
00907   PatchPointOpers opers(&MI);
00908   unsigned ScratchIdx = opers.getNextScratchIdx();
00909   unsigned EncodedBytes = 0;
00910   const MachineOperand &CalleeMO =
00911     opers.getMetaOper(PatchPointOpers::TargetPos);
00912 
00913   // Check for null target. If target is non-null (i.e. is non-zero or is
00914   // symbolic) then emit a call.
00915   if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
00916     MCOperand CalleeMCOp;
00917     switch (CalleeMO.getType()) {
00918     default:
00919       /// FIXME: Add a verifier check for bad callee types.
00920       llvm_unreachable("Unrecognized callee operand type.");
00921     case MachineOperand::MO_Immediate:
00922       if (CalleeMO.getImm())
00923         CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
00924       break;
00925     case MachineOperand::MO_ExternalSymbol:
00926     case MachineOperand::MO_GlobalAddress:
00927       CalleeMCOp =
00928         MCIL.LowerSymbolOperand(CalleeMO,
00929                                 MCIL.GetSymbolFromOperand(CalleeMO));
00930       break;
00931     }
00932 
00933     // Emit MOV to materialize the target address and the CALL to target.
00934     // This is encoded with 12-13 bytes, depending on which register is used.
00935     unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
00936     if (X86II::isX86_64ExtendedReg(ScratchReg))
00937       EncodedBytes = 13;
00938     else
00939       EncodedBytes = 12;
00940 
00941     EmitAndCountInstruction(
00942         MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
00943     EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
00944   }
00945 
00946   // Emit padding.
00947   unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
00948   assert(NumBytes >= EncodedBytes &&
00949          "Patchpoint can't request size less than the length of a call.");
00950 
00951   EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
00952            getSubtargetInfo());
00953 }
00954 
00955 // Returns instruction preceding MBBI in MachineFunction.
00956 // If MBBI is the first instruction of the first basic block, returns null.
00957 static MachineBasicBlock::const_iterator
00958 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
00959   const MachineBasicBlock *MBB = MBBI->getParent();
00960   while (MBBI == MBB->begin()) {
00961     if (MBB == MBB->getParent()->begin())
00962       return nullptr;
00963     MBB = MBB->getPrevNode();
00964     MBBI = MBB->end();
00965   }
00966   return --MBBI;
00967 }
00968 
00969 static const Constant *getConstantFromPool(const MachineInstr &MI,
00970                                            const MachineOperand &Op) {
00971   if (!Op.isCPI())
00972     return nullptr;
00973 
00974   ArrayRef<MachineConstantPoolEntry> Constants =
00975       MI.getParent()->getParent()->getConstantPool()->getConstants();
00976   const MachineConstantPoolEntry &ConstantEntry =
00977       Constants[Op.getIndex()];
00978 
00979   // Bail if this is a machine constant pool entry, we won't be able to dig out
00980   // anything useful.
00981   if (ConstantEntry.isMachineConstantPoolEntry())
00982     return nullptr;
00983 
00984   auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
00985   assert((!C || ConstantEntry.getType() == C->getType()) &&
00986          "Expected a constant of the same type!");
00987   return C;
00988 }
00989 
00990 static std::string getShuffleComment(const MachineOperand &DstOp,
00991                                      const MachineOperand &SrcOp,
00992                                      ArrayRef<int> Mask) {
00993   std::string Comment;
00994 
00995   // Compute the name for a register. This is really goofy because we have
00996   // multiple instruction printers that could (in theory) use different
00997   // names. Fortunately most people use the ATT style (outside of Windows)
00998   // and they actually agree on register naming here. Ultimately, this is
00999   // a comment, and so its OK if it isn't perfect.
01000   auto GetRegisterName = [](unsigned RegNum) -> StringRef {
01001     return X86ATTInstPrinter::getRegisterName(RegNum);
01002   };
01003 
01004   StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
01005   StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
01006 
01007   raw_string_ostream CS(Comment);
01008   CS << DstName << " = ";
01009   bool NeedComma = false;
01010   bool InSrc = false;
01011   for (int M : Mask) {
01012     // Wrap up any prior entry...
01013     if (M == SM_SentinelZero && InSrc) {
01014       InSrc = false;
01015       CS << "]";
01016     }
01017     if (NeedComma)
01018       CS << ",";
01019     else
01020       NeedComma = true;
01021 
01022     // Print this shuffle...
01023     if (M == SM_SentinelZero) {
01024       CS << "zero";
01025     } else {
01026       if (!InSrc) {
01027         InSrc = true;
01028         CS << SrcName << "[";
01029       }
01030       if (M == SM_SentinelUndef)
01031         CS << "u";
01032       else
01033         CS << M;
01034     }
01035   }
01036   if (InSrc)
01037     CS << "]";
01038   CS.flush();
01039 
01040   return Comment;
01041 }
01042 
01043 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
01044   X86MCInstLower MCInstLowering(*MF, *this);
01045   const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
01046 
01047   switch (MI->getOpcode()) {
01048   case TargetOpcode::DBG_VALUE:
01049     llvm_unreachable("Should be handled target independently");
01050 
01051   // Emit nothing here but a comment if we can.
01052   case X86::Int_MemBarrier:
01053     OutStreamer->emitRawComment("MEMBARRIER");
01054     return;
01055 
01056 
01057   case X86::EH_RETURN:
01058   case X86::EH_RETURN64: {
01059     // Lower these as normal, but add some comments.
01060     unsigned Reg = MI->getOperand(0).getReg();
01061     OutStreamer->AddComment(StringRef("eh_return, addr: %") +
01062                             X86ATTInstPrinter::getRegisterName(Reg));
01063     break;
01064   }
01065   case X86::TAILJMPr:
01066   case X86::TAILJMPm:
01067   case X86::TAILJMPd:
01068   case X86::TAILJMPr64:
01069   case X86::TAILJMPm64:
01070   case X86::TAILJMPd64:
01071   case X86::TAILJMPr64_REX:
01072   case X86::TAILJMPm64_REX:
01073   case X86::TAILJMPd64_REX:
01074     // Lower these as normal, but add some comments.
01075     OutStreamer->AddComment("TAILCALL");
01076     break;
01077 
01078   case X86::TLS_addr32:
01079   case X86::TLS_addr64:
01080   case X86::TLS_base_addr32:
01081   case X86::TLS_base_addr64:
01082     return LowerTlsAddr(MCInstLowering, *MI);
01083 
01084   case X86::MOVPC32r: {
01085     // This is a pseudo op for a two instruction sequence with a label, which
01086     // looks like:
01087     //     call "L1$pb"
01088     // "L1$pb":
01089     //     popl %esi
01090 
01091     // Emit the call.
01092     MCSymbol *PICBase = MF->getPICBaseSymbol();
01093     // FIXME: We would like an efficient form for this, so we don't have to do a
01094     // lot of extra uniquing.
01095     EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
01096       .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
01097 
01098     // Emit the label.
01099     OutStreamer->EmitLabel(PICBase);
01100 
01101     // popl $reg
01102     EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
01103                             .addReg(MI->getOperand(0).getReg()));
01104     return;
01105   }
01106 
01107   case X86::ADD32ri: {
01108     // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
01109     if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
01110       break;
01111 
01112     // Okay, we have something like:
01113     //  EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
01114 
01115     // For this, we want to print something like:
01116     //   MYGLOBAL + (. - PICBASE)
01117     // However, we can't generate a ".", so just emit a new label here and refer
01118     // to it.
01119     MCSymbol *DotSym = OutContext.createTempSymbol();
01120     OutStreamer->EmitLabel(DotSym);
01121 
01122     // Now that we have emitted the label, lower the complex operand expression.
01123     MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
01124 
01125     const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
01126     const MCExpr *PICBase =
01127       MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
01128     DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
01129 
01130     DotExpr = MCBinaryExpr::createAdd(MCSymbolRefExpr::create(OpSym,OutContext),
01131                                       DotExpr, OutContext);
01132 
01133     EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
01134       .addReg(MI->getOperand(0).getReg())
01135       .addReg(MI->getOperand(1).getReg())
01136       .addExpr(DotExpr));
01137     return;
01138   }
01139   case TargetOpcode::STATEPOINT:
01140     return LowerSTATEPOINT(*MI, MCInstLowering);
01141 
01142   case TargetOpcode::FAULTING_LOAD_OP:
01143     return LowerFAULTING_LOAD_OP(*MI, MCInstLowering);
01144 
01145   case TargetOpcode::STACKMAP:
01146     return LowerSTACKMAP(*MI);
01147 
01148   case TargetOpcode::PATCHPOINT:
01149     return LowerPATCHPOINT(*MI, MCInstLowering);
01150 
01151   case X86::MORESTACK_RET:
01152     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01153     return;
01154 
01155   case X86::MORESTACK_RET_RESTORE_R10:
01156     // Return, then restore R10.
01157     EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
01158     EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
01159                             .addReg(X86::R10)
01160                             .addReg(X86::RAX));
01161     return;
01162 
01163   case X86::SEH_PushReg:
01164     OutStreamer->EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
01165     return;
01166 
01167   case X86::SEH_SaveReg:
01168     OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01169                                    MI->getOperand(1).getImm());
01170     return;
01171 
01172   case X86::SEH_SaveXMM:
01173     OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01174                                    MI->getOperand(1).getImm());
01175     return;
01176 
01177   case X86::SEH_StackAlloc:
01178     OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
01179     return;
01180 
01181   case X86::SEH_SetFrame:
01182     OutStreamer->EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
01183                                     MI->getOperand(1).getImm());
01184     return;
01185 
01186   case X86::SEH_PushFrame:
01187     OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
01188     return;
01189 
01190   case X86::SEH_EndPrologue:
01191     OutStreamer->EmitWinCFIEndProlog();
01192     return;
01193 
01194   case X86::SEH_Epilogue: {
01195     MachineBasicBlock::const_iterator MBBI(MI);
01196     // Check if preceded by a call and emit nop if so.
01197     for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
01198       // Conservatively assume that pseudo instructions don't emit code and keep
01199       // looking for a call. We may emit an unnecessary nop in some cases.
01200       if (!MBBI->isPseudo()) {
01201         if (MBBI->isCall())
01202           EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
01203         break;
01204       }
01205     }
01206     return;
01207   }
01208 
01209     // Lower PSHUFB and VPERMILP normally but add a comment if we can find
01210     // a constant shuffle mask. We won't be able to do this at the MC layer
01211     // because the mask isn't an immediate.
01212   case X86::PSHUFBrm:
01213   case X86::VPSHUFBrm:
01214   case X86::VPSHUFBYrm: {
01215     if (!OutStreamer->isVerboseAsm())
01216       break;
01217     assert(MI->getNumOperands() > 5 &&
01218            "We should always have at least 5 operands!");
01219     const MachineOperand &DstOp = MI->getOperand(0);
01220     const MachineOperand &SrcOp = MI->getOperand(1);
01221     const MachineOperand &MaskOp = MI->getOperand(5);
01222 
01223     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01224       SmallVector<int, 16> Mask;
01225       DecodePSHUFBMask(C, Mask);
01226       if (!Mask.empty())
01227         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01228     }
01229     break;
01230   }
01231   case X86::VPERMILPSrm:
01232   case X86::VPERMILPDrm:
01233   case X86::VPERMILPSYrm:
01234   case X86::VPERMILPDYrm: {
01235     if (!OutStreamer->isVerboseAsm())
01236       break;
01237     assert(MI->getNumOperands() > 5 &&
01238            "We should always have at least 5 operands!");
01239     const MachineOperand &DstOp = MI->getOperand(0);
01240     const MachineOperand &SrcOp = MI->getOperand(1);
01241     const MachineOperand &MaskOp = MI->getOperand(5);
01242 
01243     if (auto *C = getConstantFromPool(*MI, MaskOp)) {
01244       SmallVector<int, 16> Mask;
01245       DecodeVPERMILPMask(C, Mask);
01246       if (!Mask.empty())
01247         OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
01248     }
01249     break;
01250   }
01251 
01252     // For loads from a constant pool to a vector register, print the constant
01253     // loaded.
01254   case X86::MOVAPDrm:
01255   case X86::VMOVAPDrm:
01256   case X86::VMOVAPDYrm:
01257   case X86::MOVUPDrm:
01258   case X86::VMOVUPDrm:
01259   case X86::VMOVUPDYrm:
01260   case X86::MOVAPSrm:
01261   case X86::VMOVAPSrm:
01262   case X86::VMOVAPSYrm:
01263   case X86::MOVUPSrm:
01264   case X86::VMOVUPSrm:
01265   case X86::VMOVUPSYrm:
01266   case X86::MOVDQArm:
01267   case X86::VMOVDQArm:
01268   case X86::VMOVDQAYrm:
01269   case X86::MOVDQUrm:
01270   case X86::VMOVDQUrm:
01271   case X86::VMOVDQUYrm:
01272     if (!OutStreamer->isVerboseAsm())
01273       break;
01274     if (MI->getNumOperands() > 4)
01275     if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
01276       std::string Comment;
01277       raw_string_ostream CS(Comment);
01278       const MachineOperand &DstOp = MI->getOperand(0);
01279       CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
01280       if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
01281         CS << "[";
01282         for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
01283           if (i != 0)
01284             CS << ",";
01285           if (CDS->getElementType()->isIntegerTy())
01286             CS << CDS->getElementAsInteger(i);
01287           else if (CDS->getElementType()->isFloatTy())
01288             CS << CDS->getElementAsFloat(i);
01289           else if (CDS->getElementType()->isDoubleTy())
01290             CS << CDS->getElementAsDouble(i);
01291           else
01292             CS << "?";
01293         }
01294         CS << "]";
01295         OutStreamer->AddComment(CS.str());
01296       } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
01297         CS << "<";
01298         for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
01299           if (i != 0)
01300             CS << ",";
01301           Constant *COp = CV->getOperand(i);
01302           if (isa<UndefValue>(COp)) {
01303             CS << "u";
01304           } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
01305             CS << CI->getZExtValue();
01306           } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
01307             SmallString<32> Str;
01308             CF->getValueAPF().toString(Str);
01309             CS << Str;
01310           } else {
01311             CS << "?";
01312           }
01313         }
01314         CS << ">";
01315         OutStreamer->AddComment(CS.str());
01316       }
01317     }
01318     break;
01319   }
01320 
01321   MCInst TmpInst;
01322   MCInstLowering.Lower(MI, TmpInst);
01323 
01324   // Stackmap shadows cannot include branch targets, so we can count the bytes
01325   // in a call towards the shadow, but must ensure that the no thread returns
01326   // in to the stackmap shadow.  The only way to achieve this is if the call
01327   // is at the end of the shadow.
01328   if (MI->isCall()) {
01329     // Count then size of the call towards the shadow
01330     SMShadowTracker.count(TmpInst, getSubtargetInfo());
01331     // Then flush the shadow so that we fill with nops before the call, not
01332     // after it.
01333     SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
01334     // Then emit the call
01335     OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
01336     return;
01337   }
01338 
01339   EmitAndCountInstruction(TmpInst);
01340 }