1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code to lower X86 MachineInstrs to their corresponding
13 //===----------------------------------------------------------------------===//
15 #include "X86AsmPrinter.h"
16 #include "X86RegisterInfo.h"
17 #include "X86ShuffleDecodeConstantPool.h"
18 #include "InstPrinter/X86ATTInstPrinter.h"
19 #include "MCTargetDesc/X86BaseInfo.h"
20 #include "Utils/X86ShuffleDecode.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
27 #include "llvm/CodeGen/StackMaps.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCCodeEmitter.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/MC/MCExpr.h"
35 #include "llvm/MC/MCFixup.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCInstBuilder.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/TargetRegistry.h"
45 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
46 class X86MCInstLower {
48 const MachineFunction &MF;
49 const TargetMachine &TM;
51 X86AsmPrinter &AsmPrinter;
53 X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
55 Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
56 const MachineOperand &MO) const;
57 void Lower(const MachineInstr *MI, MCInst &OutMI) const;
59 MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
60 MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
63 MachineModuleInfoMachO &getMachOMMI() const;
64 Mangler *getMang() const {
65 return AsmPrinter.Mang;
69 } // end anonymous namespace
71 // Emit a minimal sequence of nops spanning NumBytes bytes.
72 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
73 const MCSubtargetInfo &STI);
76 X86AsmPrinter::StackMapShadowTracker::StackMapShadowTracker(TargetMachine &TM)
77 : TM(TM), InShadow(false), RequiredShadowSize(0), CurrentShadowSize(0) {}
79 X86AsmPrinter::StackMapShadowTracker::~StackMapShadowTracker() {}
82 X86AsmPrinter::StackMapShadowTracker::startFunction(MachineFunction &F) {
84 CodeEmitter.reset(TM.getTarget().createMCCodeEmitter(
85 *MF->getSubtarget().getInstrInfo(),
86 *MF->getSubtarget().getRegisterInfo(), MF->getContext()));
89 void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
90 const MCSubtargetInfo &STI) {
92 SmallString<256> Code;
93 SmallVector<MCFixup, 4> Fixups;
94 raw_svector_ostream VecOS(Code);
95 CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
96 CurrentShadowSize += Code.size();
97 if (CurrentShadowSize >= RequiredShadowSize)
98 InShadow = false; // The shadow is big enough. Stop counting.
102 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
103 MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
104 if (InShadow && CurrentShadowSize < RequiredShadowSize) {
106 EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
107 MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
111 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
112 OutStreamer->EmitInstruction(Inst, getSubtargetInfo());
113 SMShadowTracker.count(Inst, getSubtargetInfo());
115 } // end llvm namespace
117 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
118 X86AsmPrinter &asmprinter)
119 : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
120 AsmPrinter(asmprinter) {}
122 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
123 return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
127 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
128 /// operand to an MCSymbol.
129 MCSymbol *X86MCInstLower::
130 GetSymbolFromOperand(const MachineOperand &MO) const {
131 const DataLayout &DL = MF.getDataLayout();
132 assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) && "Isn't a symbol reference");
134 MCSymbol *Sym = nullptr;
135 SmallString<128> Name;
138 switch (MO.getTargetFlags()) {
139 case X86II::MO_DLLIMPORT:
140 // Handle dllimport linkage.
143 case X86II::MO_DARWIN_STUB:
146 case X86II::MO_DARWIN_NONLAZY:
147 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
148 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
149 Suffix = "$non_lazy_ptr";
154 Name += DL.getPrivateGlobalPrefix();
156 unsigned PrefixLen = Name.size();
159 const GlobalValue *GV = MO.getGlobal();
160 AsmPrinter.getNameWithPrefix(Name, GV);
161 } else if (MO.isSymbol()) {
162 Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
163 } else if (MO.isMBB()) {
164 assert(Suffix.empty());
165 Sym = MO.getMBB()->getSymbol();
167 unsigned OrigLen = Name.size() - PrefixLen;
171 Sym = Ctx.getOrCreateSymbol(Name);
173 StringRef OrigName = StringRef(Name).substr(PrefixLen, OrigLen);
175 // If the target flags on the operand changes the name of the symbol, do that
176 // before we return the symbol.
177 switch (MO.getTargetFlags()) {
179 case X86II::MO_DARWIN_NONLAZY:
180 case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
181 MachineModuleInfoImpl::StubValueTy &StubSym =
182 getMachOMMI().getGVStubEntry(Sym);
183 if (!StubSym.getPointer()) {
184 assert(MO.isGlobal() && "Extern symbol not handled yet");
186 MachineModuleInfoImpl::
187 StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
188 !MO.getGlobal()->hasInternalLinkage());
192 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE: {
193 MachineModuleInfoImpl::StubValueTy &StubSym =
194 getMachOMMI().getHiddenGVStubEntry(Sym);
195 if (!StubSym.getPointer()) {
196 assert(MO.isGlobal() && "Extern symbol not handled yet");
198 MachineModuleInfoImpl::
199 StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
200 !MO.getGlobal()->hasInternalLinkage());
204 case X86II::MO_DARWIN_STUB: {
205 MachineModuleInfoImpl::StubValueTy &StubSym =
206 getMachOMMI().getFnStubEntry(Sym);
207 if (StubSym.getPointer())
212 MachineModuleInfoImpl::
213 StubValueTy(AsmPrinter.getSymbol(MO.getGlobal()),
214 !MO.getGlobal()->hasInternalLinkage());
217 MachineModuleInfoImpl::
218 StubValueTy(Ctx.getOrCreateSymbol(OrigName), false);
227 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
228 MCSymbol *Sym) const {
229 // FIXME: We would like an efficient form for this, so we don't have to do a
230 // lot of extra uniquing.
231 const MCExpr *Expr = nullptr;
232 MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
234 switch (MO.getTargetFlags()) {
235 default: llvm_unreachable("Unknown target flag on GV operand");
236 case X86II::MO_NO_FLAG: // No flag.
237 // These affect the name of the symbol, not any suffix.
238 case X86II::MO_DARWIN_NONLAZY:
239 case X86II::MO_DLLIMPORT:
240 case X86II::MO_DARWIN_STUB:
243 case X86II::MO_TLVP: RefKind = MCSymbolRefExpr::VK_TLVP; break;
244 case X86II::MO_TLVP_PIC_BASE:
245 Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
246 // Subtract the pic base.
247 Expr = MCBinaryExpr::createSub(Expr,
248 MCSymbolRefExpr::create(MF.getPICBaseSymbol(),
252 case X86II::MO_SECREL: RefKind = MCSymbolRefExpr::VK_SECREL; break;
253 case X86II::MO_TLSGD: RefKind = MCSymbolRefExpr::VK_TLSGD; break;
254 case X86II::MO_TLSLD: RefKind = MCSymbolRefExpr::VK_TLSLD; break;
255 case X86II::MO_TLSLDM: RefKind = MCSymbolRefExpr::VK_TLSLDM; break;
256 case X86II::MO_GOTTPOFF: RefKind = MCSymbolRefExpr::VK_GOTTPOFF; break;
257 case X86II::MO_INDNTPOFF: RefKind = MCSymbolRefExpr::VK_INDNTPOFF; break;
258 case X86II::MO_TPOFF: RefKind = MCSymbolRefExpr::VK_TPOFF; break;
259 case X86II::MO_DTPOFF: RefKind = MCSymbolRefExpr::VK_DTPOFF; break;
260 case X86II::MO_NTPOFF: RefKind = MCSymbolRefExpr::VK_NTPOFF; break;
261 case X86II::MO_GOTNTPOFF: RefKind = MCSymbolRefExpr::VK_GOTNTPOFF; break;
262 case X86II::MO_GOTPCREL: RefKind = MCSymbolRefExpr::VK_GOTPCREL; break;
263 case X86II::MO_GOT: RefKind = MCSymbolRefExpr::VK_GOT; break;
264 case X86II::MO_GOTOFF: RefKind = MCSymbolRefExpr::VK_GOTOFF; break;
265 case X86II::MO_PLT: RefKind = MCSymbolRefExpr::VK_PLT; break;
266 case X86II::MO_PIC_BASE_OFFSET:
267 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
268 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
269 Expr = MCSymbolRefExpr::create(Sym, Ctx);
270 // Subtract the pic base.
271 Expr = MCBinaryExpr::createSub(Expr,
272 MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx),
275 assert(MAI.doesSetDirectiveSuppressesReloc());
276 // If .set directive is supported, use it to reduce the number of
277 // relocations the assembler will generate for differences between
278 // local labels. This is only safe when the symbols are in the same
279 // section so we are restricting it to jumptable references.
280 MCSymbol *Label = Ctx.createTempSymbol();
281 AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
282 Expr = MCSymbolRefExpr::create(Label, Ctx);
288 Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
290 if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
291 Expr = MCBinaryExpr::createAdd(Expr,
292 MCConstantExpr::create(MO.getOffset(), Ctx),
294 return MCOperand::createExpr(Expr);
298 /// \brief Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
299 /// a short fixed-register form.
300 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
301 unsigned ImmOp = Inst.getNumOperands() - 1;
302 assert(Inst.getOperand(0).isReg() &&
303 (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
304 ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
305 Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
306 Inst.getNumOperands() == 2) && "Unexpected instruction!");
308 // Check whether the destination register can be fixed.
309 unsigned Reg = Inst.getOperand(0).getReg();
310 if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
313 // If so, rewrite the instruction.
314 MCOperand Saved = Inst.getOperand(ImmOp);
316 Inst.setOpcode(Opcode);
317 Inst.addOperand(Saved);
320 /// \brief If a movsx instruction has a shorter encoding for the used register
321 /// simplify the instruction to use it instead.
322 static void SimplifyMOVSX(MCInst &Inst) {
323 unsigned NewOpcode = 0;
324 unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
325 switch (Inst.getOpcode()) {
327 llvm_unreachable("Unexpected instruction!");
328 case X86::MOVSX16rr8: // movsbw %al, %ax --> cbtw
329 if (Op0 == X86::AX && Op1 == X86::AL)
330 NewOpcode = X86::CBW;
332 case X86::MOVSX32rr16: // movswl %ax, %eax --> cwtl
333 if (Op0 == X86::EAX && Op1 == X86::AX)
334 NewOpcode = X86::CWDE;
336 case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
337 if (Op0 == X86::RAX && Op1 == X86::EAX)
338 NewOpcode = X86::CDQE;
342 if (NewOpcode != 0) {
344 Inst.setOpcode(NewOpcode);
348 /// \brief Simplify things like MOV32rm to MOV32o32a.
349 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
351 // Don't make these simplifications in 64-bit mode; other assemblers don't
352 // perform them because they make the code larger.
353 if (Printer.getSubtarget().is64Bit())
356 bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
357 unsigned AddrBase = IsStore;
358 unsigned RegOp = IsStore ? 0 : 5;
359 unsigned AddrOp = AddrBase + 3;
360 assert(Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
361 Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
362 Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
363 Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
364 Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
365 (Inst.getOperand(AddrOp).isExpr() ||
366 Inst.getOperand(AddrOp).isImm()) &&
367 "Unexpected instruction!");
369 // Check whether the destination register can be fixed.
370 unsigned Reg = Inst.getOperand(RegOp).getReg();
371 if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
374 // Check whether this is an absolute address.
375 // FIXME: We know TLVP symbol refs aren't, but there should be a better way
377 bool Absolute = true;
378 if (Inst.getOperand(AddrOp).isExpr()) {
379 const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
380 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
381 if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
386 (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
387 Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
388 Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
391 // If so, rewrite the instruction.
392 MCOperand Saved = Inst.getOperand(AddrOp);
393 MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
395 Inst.setOpcode(Opcode);
396 Inst.addOperand(Saved);
397 Inst.addOperand(Seg);
400 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
401 return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
405 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
406 const MachineOperand &MO) const {
407 switch (MO.getType()) {
410 llvm_unreachable("unknown operand type");
411 case MachineOperand::MO_Register:
412 // Ignore all implicit register operands.
415 return MCOperand::createReg(MO.getReg());
416 case MachineOperand::MO_Immediate:
417 return MCOperand::createImm(MO.getImm());
418 case MachineOperand::MO_MachineBasicBlock:
419 case MachineOperand::MO_GlobalAddress:
420 case MachineOperand::MO_ExternalSymbol:
421 return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
422 case MachineOperand::MO_MCSymbol:
423 return LowerSymbolOperand(MO, MO.getMCSymbol());
424 case MachineOperand::MO_JumpTableIndex:
425 return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
426 case MachineOperand::MO_ConstantPoolIndex:
427 return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
428 case MachineOperand::MO_BlockAddress:
429 return LowerSymbolOperand(
430 MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
431 case MachineOperand::MO_RegisterMask:
432 // Ignore call clobbers.
437 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
438 OutMI.setOpcode(MI->getOpcode());
440 for (const MachineOperand &MO : MI->operands())
441 if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
442 OutMI.addOperand(MaybeMCOp.getValue());
444 // Handle a few special cases to eliminate operand modifiers.
446 switch (OutMI.getOpcode()) {
451 // LEA should have a segment register, but it must be empty.
452 assert(OutMI.getNumOperands() == 1+X86::AddrNumOperands &&
453 "Unexpected # of LEA operands");
454 assert(OutMI.getOperand(1+X86::AddrSegmentReg).getReg() == 0 &&
455 "LEA has segment specified!");
458 // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
459 // if one of the registers is extended, but other isn't.
460 case X86::VMOVZPQILo2PQIrr:
462 case X86::VMOVAPDYrr:
464 case X86::VMOVAPSYrr:
466 case X86::VMOVDQAYrr:
468 case X86::VMOVDQUYrr:
470 case X86::VMOVUPDYrr:
472 case X86::VMOVUPSYrr: {
473 if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
474 X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
476 switch (OutMI.getOpcode()) {
477 default: llvm_unreachable("Invalid opcode");
478 case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break;
479 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
480 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
481 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
482 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
483 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
484 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
485 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
486 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
487 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
488 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
489 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
490 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
492 OutMI.setOpcode(NewOpc);
497 case X86::VMOVSSrr: {
498 if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
499 X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
501 switch (OutMI.getOpcode()) {
502 default: llvm_unreachable("Invalid opcode");
503 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
504 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
506 OutMI.setOpcode(NewOpc);
511 // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
512 // inputs modeled as normal uses instead of implicit uses. As such, truncate
513 // off all but the first operand (the callee). FIXME: Change isel.
514 case X86::TAILJMPr64:
515 case X86::TAILJMPr64_REX:
517 case X86::CALL64pcrel32: {
518 unsigned Opcode = OutMI.getOpcode();
519 MCOperand Saved = OutMI.getOperand(0);
521 OutMI.setOpcode(Opcode);
522 OutMI.addOperand(Saved);
527 case X86::EH_RETURN64: {
529 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
533 case X86::CLEANUPRET: {
534 // Replace CATCHRET with the appropriate RET.
536 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
540 case X86::CATCHRET: {
541 // Replace CATCHRET with the appropriate RET.
542 const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
543 unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
545 OutMI.setOpcode(getRetOpcode(Subtarget));
546 OutMI.addOperand(MCOperand::createReg(ReturnReg));
550 // TAILJMPd, TAILJMPd64 - Lower to the correct jump instructions.
553 case X86::TAILJMPd64: {
555 switch (OutMI.getOpcode()) {
556 default: llvm_unreachable("Invalid opcode");
557 case X86::TAILJMPr: Opcode = X86::JMP32r; break;
559 case X86::TAILJMPd64: Opcode = X86::JMP_1; break;
562 MCOperand Saved = OutMI.getOperand(0);
564 OutMI.setOpcode(Opcode);
565 OutMI.addOperand(Saved);
573 // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
574 if (!AsmPrinter.getSubtarget().is64Bit()) {
576 switch (OutMI.getOpcode()) {
577 default: llvm_unreachable("Invalid opcode");
578 case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
579 case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
580 case X86::INC16r: Opcode = X86::INC16r_alt; break;
581 case X86::INC32r: Opcode = X86::INC32r_alt; break;
583 OutMI.setOpcode(Opcode);
587 // These are pseudo-ops for OR to help with the OR->ADD transformation. We do
588 // this with an ugly goto in case the resultant OR uses EAX and needs the
590 case X86::ADD16rr_DB: OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
591 case X86::ADD32rr_DB: OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
592 case X86::ADD64rr_DB: OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
593 case X86::ADD16ri_DB: OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
594 case X86::ADD32ri_DB: OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
595 case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
596 case X86::ADD16ri8_DB: OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
597 case X86::ADD32ri8_DB: OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
598 case X86::ADD64ri8_DB: OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
600 // Atomic load and store require a separate pseudo-inst because Acquire
601 // implies mayStore and Release implies mayLoad; fix these to regular MOV
603 case X86::ACQUIRE_MOV8rm: OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
604 case X86::ACQUIRE_MOV16rm: OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
605 case X86::ACQUIRE_MOV32rm: OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
606 case X86::ACQUIRE_MOV64rm: OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
607 case X86::RELEASE_MOV8mr: OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
608 case X86::RELEASE_MOV16mr: OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
609 case X86::RELEASE_MOV32mr: OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
610 case X86::RELEASE_MOV64mr: OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
611 case X86::RELEASE_MOV8mi: OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
612 case X86::RELEASE_MOV16mi: OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
613 case X86::RELEASE_MOV32mi: OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
614 case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
615 case X86::RELEASE_ADD8mi: OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
616 case X86::RELEASE_ADD8mr: OutMI.setOpcode(X86::ADD8mr); goto ReSimplify;
617 case X86::RELEASE_ADD32mi: OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
618 case X86::RELEASE_ADD32mr: OutMI.setOpcode(X86::ADD32mr); goto ReSimplify;
619 case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
620 case X86::RELEASE_ADD64mr: OutMI.setOpcode(X86::ADD64mr); goto ReSimplify;
621 case X86::RELEASE_AND8mi: OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
622 case X86::RELEASE_AND8mr: OutMI.setOpcode(X86::AND8mr); goto ReSimplify;
623 case X86::RELEASE_AND32mi: OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
624 case X86::RELEASE_AND32mr: OutMI.setOpcode(X86::AND32mr); goto ReSimplify;
625 case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
626 case X86::RELEASE_AND64mr: OutMI.setOpcode(X86::AND64mr); goto ReSimplify;
627 case X86::RELEASE_OR8mi: OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
628 case X86::RELEASE_OR8mr: OutMI.setOpcode(X86::OR8mr); goto ReSimplify;
629 case X86::RELEASE_OR32mi: OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
630 case X86::RELEASE_OR32mr: OutMI.setOpcode(X86::OR32mr); goto ReSimplify;
631 case X86::RELEASE_OR64mi32: OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
632 case X86::RELEASE_OR64mr: OutMI.setOpcode(X86::OR64mr); goto ReSimplify;
633 case X86::RELEASE_XOR8mi: OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
634 case X86::RELEASE_XOR8mr: OutMI.setOpcode(X86::XOR8mr); goto ReSimplify;
635 case X86::RELEASE_XOR32mi: OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
636 case X86::RELEASE_XOR32mr: OutMI.setOpcode(X86::XOR32mr); goto ReSimplify;
637 case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
638 case X86::RELEASE_XOR64mr: OutMI.setOpcode(X86::XOR64mr); goto ReSimplify;
639 case X86::RELEASE_INC8m: OutMI.setOpcode(X86::INC8m); goto ReSimplify;
640 case X86::RELEASE_INC16m: OutMI.setOpcode(X86::INC16m); goto ReSimplify;
641 case X86::RELEASE_INC32m: OutMI.setOpcode(X86::INC32m); goto ReSimplify;
642 case X86::RELEASE_INC64m: OutMI.setOpcode(X86::INC64m); goto ReSimplify;
643 case X86::RELEASE_DEC8m: OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
644 case X86::RELEASE_DEC16m: OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
645 case X86::RELEASE_DEC32m: OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
646 case X86::RELEASE_DEC64m: OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
648 // We don't currently select the correct instruction form for instructions
649 // which have a short %eax, etc. form. Handle this by custom lowering, for
652 // Note, we are currently not handling the following instructions:
653 // MOV64ao8, MOV64o8a
654 // XCHG16ar, XCHG32ar, XCHG64ar
655 case X86::MOV8mr_NOREX:
656 case X86::MOV8mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8o32a); break;
657 case X86::MOV8rm_NOREX:
658 case X86::MOV8rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV8ao32); break;
659 case X86::MOV16mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16o32a); break;
660 case X86::MOV16rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV16ao32); break;
661 case X86::MOV32mr: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32o32a); break;
662 case X86::MOV32rm: SimplifyShortMoveForm(AsmPrinter, OutMI, X86::MOV32ao32); break;
664 case X86::ADC8ri: SimplifyShortImmForm(OutMI, X86::ADC8i8); break;
665 case X86::ADC16ri: SimplifyShortImmForm(OutMI, X86::ADC16i16); break;
666 case X86::ADC32ri: SimplifyShortImmForm(OutMI, X86::ADC32i32); break;
667 case X86::ADC64ri32: SimplifyShortImmForm(OutMI, X86::ADC64i32); break;
668 case X86::ADD8ri: SimplifyShortImmForm(OutMI, X86::ADD8i8); break;
669 case X86::ADD16ri: SimplifyShortImmForm(OutMI, X86::ADD16i16); break;
670 case X86::ADD32ri: SimplifyShortImmForm(OutMI, X86::ADD32i32); break;
671 case X86::ADD64ri32: SimplifyShortImmForm(OutMI, X86::ADD64i32); break;
672 case X86::AND8ri: SimplifyShortImmForm(OutMI, X86::AND8i8); break;
673 case X86::AND16ri: SimplifyShortImmForm(OutMI, X86::AND16i16); break;
674 case X86::AND32ri: SimplifyShortImmForm(OutMI, X86::AND32i32); break;
675 case X86::AND64ri32: SimplifyShortImmForm(OutMI, X86::AND64i32); break;
676 case X86::CMP8ri: SimplifyShortImmForm(OutMI, X86::CMP8i8); break;
677 case X86::CMP16ri: SimplifyShortImmForm(OutMI, X86::CMP16i16); break;
678 case X86::CMP32ri: SimplifyShortImmForm(OutMI, X86::CMP32i32); break;
679 case X86::CMP64ri32: SimplifyShortImmForm(OutMI, X86::CMP64i32); break;
680 case X86::OR8ri: SimplifyShortImmForm(OutMI, X86::OR8i8); break;
681 case X86::OR16ri: SimplifyShortImmForm(OutMI, X86::OR16i16); break;
682 case X86::OR32ri: SimplifyShortImmForm(OutMI, X86::OR32i32); break;
683 case X86::OR64ri32: SimplifyShortImmForm(OutMI, X86::OR64i32); break;
684 case X86::SBB8ri: SimplifyShortImmForm(OutMI, X86::SBB8i8); break;
685 case X86::SBB16ri: SimplifyShortImmForm(OutMI, X86::SBB16i16); break;
686 case X86::SBB32ri: SimplifyShortImmForm(OutMI, X86::SBB32i32); break;
687 case X86::SBB64ri32: SimplifyShortImmForm(OutMI, X86::SBB64i32); break;
688 case X86::SUB8ri: SimplifyShortImmForm(OutMI, X86::SUB8i8); break;
689 case X86::SUB16ri: SimplifyShortImmForm(OutMI, X86::SUB16i16); break;
690 case X86::SUB32ri: SimplifyShortImmForm(OutMI, X86::SUB32i32); break;
691 case X86::SUB64ri32: SimplifyShortImmForm(OutMI, X86::SUB64i32); break;
692 case X86::TEST8ri: SimplifyShortImmForm(OutMI, X86::TEST8i8); break;
693 case X86::TEST16ri: SimplifyShortImmForm(OutMI, X86::TEST16i16); break;
694 case X86::TEST32ri: SimplifyShortImmForm(OutMI, X86::TEST32i32); break;
695 case X86::TEST64ri32: SimplifyShortImmForm(OutMI, X86::TEST64i32); break;
696 case X86::XOR8ri: SimplifyShortImmForm(OutMI, X86::XOR8i8); break;
697 case X86::XOR16ri: SimplifyShortImmForm(OutMI, X86::XOR16i16); break;
698 case X86::XOR32ri: SimplifyShortImmForm(OutMI, X86::XOR32i32); break;
699 case X86::XOR64ri32: SimplifyShortImmForm(OutMI, X86::XOR64i32); break;
701 // Try to shrink some forms of movsx.
702 case X86::MOVSX16rr8:
703 case X86::MOVSX32rr16:
704 case X86::MOVSX64rr32:
705 SimplifyMOVSX(OutMI);
710 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
711 const MachineInstr &MI) {
713 bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
714 MI.getOpcode() == X86::TLS_base_addr64;
716 bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
718 MCContext &context = OutStreamer->getContext();
721 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
723 MCSymbolRefExpr::VariantKind SRVK;
724 switch (MI.getOpcode()) {
725 case X86::TLS_addr32:
726 case X86::TLS_addr64:
727 SRVK = MCSymbolRefExpr::VK_TLSGD;
729 case X86::TLS_base_addr32:
730 SRVK = MCSymbolRefExpr::VK_TLSLDM;
732 case X86::TLS_base_addr64:
733 SRVK = MCSymbolRefExpr::VK_TLSLD;
736 llvm_unreachable("unexpected opcode");
739 MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
740 const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
744 LEA.setOpcode(X86::LEA64r);
745 LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
746 LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
747 LEA.addOperand(MCOperand::createImm(1)); // scale
748 LEA.addOperand(MCOperand::createReg(0)); // index
749 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
750 LEA.addOperand(MCOperand::createReg(0)); // seg
751 } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
752 LEA.setOpcode(X86::LEA32r);
753 LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
754 LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
755 LEA.addOperand(MCOperand::createImm(1)); // scale
756 LEA.addOperand(MCOperand::createReg(0)); // index
757 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
758 LEA.addOperand(MCOperand::createReg(0)); // seg
760 LEA.setOpcode(X86::LEA32r);
761 LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
762 LEA.addOperand(MCOperand::createReg(0)); // base
763 LEA.addOperand(MCOperand::createImm(1)); // scale
764 LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
765 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
766 LEA.addOperand(MCOperand::createReg(0)); // seg
768 EmitAndCountInstruction(LEA);
771 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
772 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
773 EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
776 StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
777 MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
778 const MCSymbolRefExpr *tlsRef =
779 MCSymbolRefExpr::create(tlsGetAddr,
780 MCSymbolRefExpr::VK_PLT,
783 EmitAndCountInstruction(MCInstBuilder(is64Bits ? X86::CALL64pcrel32
788 /// \brief Emit the optimal amount of multi-byte nops on X86.
789 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit, const MCSubtargetInfo &STI) {
790 // This works only for 64bit. For 32bit we have to do additional checking if
791 // the CPU supports multi-byte nops.
792 assert(Is64Bit && "EmitNops only supports X86-64");
794 unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
795 Opc = IndexReg = Displacement = SegmentReg = 0;
796 BaseReg = X86::RAX; ScaleVal = 1;
798 case 0: llvm_unreachable("Zero nops?"); break;
799 case 1: NumBytes -= 1; Opc = X86::NOOP; break;
800 case 2: NumBytes -= 2; Opc = X86::XCHG16ar; break;
801 case 3: NumBytes -= 3; Opc = X86::NOOPL; break;
802 case 4: NumBytes -= 4; Opc = X86::NOOPL; Displacement = 8; break;
803 case 5: NumBytes -= 5; Opc = X86::NOOPL; Displacement = 8;
804 IndexReg = X86::RAX; break;
805 case 6: NumBytes -= 6; Opc = X86::NOOPW; Displacement = 8;
806 IndexReg = X86::RAX; break;
807 case 7: NumBytes -= 7; Opc = X86::NOOPL; Displacement = 512; break;
808 case 8: NumBytes -= 8; Opc = X86::NOOPL; Displacement = 512;
809 IndexReg = X86::RAX; break;
810 case 9: NumBytes -= 9; Opc = X86::NOOPW; Displacement = 512;
811 IndexReg = X86::RAX; break;
812 default: NumBytes -= 10; Opc = X86::NOOPW; Displacement = 512;
813 IndexReg = X86::RAX; SegmentReg = X86::CS; break;
816 unsigned NumPrefixes = std::min(NumBytes, 5U);
817 NumBytes -= NumPrefixes;
818 for (unsigned i = 0; i != NumPrefixes; ++i)
819 OS.EmitBytes("\x66");
822 default: llvm_unreachable("Unexpected opcode"); break;
824 OS.EmitInstruction(MCInstBuilder(Opc), STI);
827 OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX), STI);
831 OS.EmitInstruction(MCInstBuilder(Opc).addReg(BaseReg)
832 .addImm(ScaleVal).addReg(IndexReg)
833 .addImm(Displacement).addReg(SegmentReg), STI);
836 } // while (NumBytes)
839 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
840 X86MCInstLower &MCIL) {
841 assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
843 StatepointOpers SOpers(&MI);
844 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
845 EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
848 // Lower call target and choose correct opcode
849 const MachineOperand &CallTarget = SOpers.getCallTarget();
850 MCOperand CallTargetMCOp;
852 switch (CallTarget.getType()) {
853 case MachineOperand::MO_GlobalAddress:
854 case MachineOperand::MO_ExternalSymbol:
855 CallTargetMCOp = MCIL.LowerSymbolOperand(
856 CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
857 CallOpcode = X86::CALL64pcrel32;
858 // Currently, we only support relative addressing with statepoints.
859 // Otherwise, we'll need a scratch register to hold the target
860 // address. You'll fail asserts during load & relocation if this
861 // symbol is to far away. (TODO: support non-relative addressing)
863 case MachineOperand::MO_Immediate:
864 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
865 CallOpcode = X86::CALL64pcrel32;
866 // Currently, we only support relative addressing with statepoints.
867 // Otherwise, we'll need a scratch register to hold the target
868 // immediate. You'll fail asserts during load & relocation if this
869 // address is to far away. (TODO: support non-relative addressing)
871 case MachineOperand::MO_Register:
872 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
873 CallOpcode = X86::CALL64r;
876 llvm_unreachable("Unsupported operand type in statepoint call target");
882 CallInst.setOpcode(CallOpcode);
883 CallInst.addOperand(CallTargetMCOp);
884 OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
887 // Record our statepoint node in the same section used by STACKMAP
889 SM.recordStatepoint(MI);
892 void X86AsmPrinter::LowerFAULTING_LOAD_OP(const MachineInstr &MI,
893 X86MCInstLower &MCIL) {
894 // FAULTING_LOAD_OP <def>, <handler label>, <load opcode>, <load operands>
896 unsigned LoadDefRegister = MI.getOperand(0).getReg();
897 MCSymbol *HandlerLabel = MI.getOperand(1).getMCSymbol();
898 unsigned LoadOpcode = MI.getOperand(2).getImm();
899 unsigned LoadOperandsBeginIdx = 3;
901 FM.recordFaultingOp(FaultMaps::FaultingLoad, HandlerLabel);
904 LoadMI.setOpcode(LoadOpcode);
906 if (LoadDefRegister != X86::NoRegister)
907 LoadMI.addOperand(MCOperand::createReg(LoadDefRegister));
909 for (auto I = MI.operands_begin() + LoadOperandsBeginIdx,
910 E = MI.operands_end();
912 if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, *I))
913 LoadMI.addOperand(MaybeOperand.getValue());
915 OutStreamer->EmitInstruction(LoadMI, getSubtargetInfo());
918 // Lower a stackmap of the form:
919 // <id>, <shadowBytes>, ...
920 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
921 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
922 SM.recordStackMap(MI);
923 unsigned NumShadowBytes = MI.getOperand(1).getImm();
924 SMShadowTracker.reset(NumShadowBytes);
927 // Lower a patchpoint of the form:
928 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
929 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
930 X86MCInstLower &MCIL) {
931 assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
933 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
935 SM.recordPatchPoint(MI);
937 PatchPointOpers opers(&MI);
938 unsigned ScratchIdx = opers.getNextScratchIdx();
939 unsigned EncodedBytes = 0;
940 const MachineOperand &CalleeMO =
941 opers.getMetaOper(PatchPointOpers::TargetPos);
943 // Check for null target. If target is non-null (i.e. is non-zero or is
944 // symbolic) then emit a call.
945 if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
946 MCOperand CalleeMCOp;
947 switch (CalleeMO.getType()) {
949 /// FIXME: Add a verifier check for bad callee types.
950 llvm_unreachable("Unrecognized callee operand type.");
951 case MachineOperand::MO_Immediate:
952 if (CalleeMO.getImm())
953 CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
955 case MachineOperand::MO_ExternalSymbol:
956 case MachineOperand::MO_GlobalAddress:
958 MCIL.LowerSymbolOperand(CalleeMO,
959 MCIL.GetSymbolFromOperand(CalleeMO));
963 // Emit MOV to materialize the target address and the CALL to target.
964 // This is encoded with 12-13 bytes, depending on which register is used.
965 unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
966 if (X86II::isX86_64ExtendedReg(ScratchReg))
971 EmitAndCountInstruction(
972 MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
973 EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
977 unsigned NumBytes = opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
978 assert(NumBytes >= EncodedBytes &&
979 "Patchpoint can't request size less than the length of a call.");
981 EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
985 // Returns instruction preceding MBBI in MachineFunction.
986 // If MBBI is the first instruction of the first basic block, returns null.
987 static MachineBasicBlock::const_iterator
988 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
989 const MachineBasicBlock *MBB = MBBI->getParent();
990 while (MBBI == MBB->begin()) {
991 if (MBB == MBB->getParent()->begin())
993 MBB = MBB->getPrevNode();
999 static const Constant *getConstantFromPool(const MachineInstr &MI,
1000 const MachineOperand &Op) {
1004 ArrayRef<MachineConstantPoolEntry> Constants =
1005 MI.getParent()->getParent()->getConstantPool()->getConstants();
1006 const MachineConstantPoolEntry &ConstantEntry =
1007 Constants[Op.getIndex()];
1009 // Bail if this is a machine constant pool entry, we won't be able to dig out
1011 if (ConstantEntry.isMachineConstantPoolEntry())
1014 auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
1015 assert((!C || ConstantEntry.getType() == C->getType()) &&
1016 "Expected a constant of the same type!");
1020 static std::string getShuffleComment(const MachineOperand &DstOp,
1021 const MachineOperand &SrcOp,
1022 ArrayRef<int> Mask) {
1023 std::string Comment;
1025 // Compute the name for a register. This is really goofy because we have
1026 // multiple instruction printers that could (in theory) use different
1027 // names. Fortunately most people use the ATT style (outside of Windows)
1028 // and they actually agree on register naming here. Ultimately, this is
1029 // a comment, and so its OK if it isn't perfect.
1030 auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1031 return X86ATTInstPrinter::getRegisterName(RegNum);
1034 StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1035 StringRef SrcName = SrcOp.isReg() ? GetRegisterName(SrcOp.getReg()) : "mem";
1037 raw_string_ostream CS(Comment);
1038 CS << DstName << " = ";
1039 bool NeedComma = false;
1041 for (int M : Mask) {
1042 // Wrap up any prior entry...
1043 if (M == SM_SentinelZero && InSrc) {
1052 // Print this shuffle...
1053 if (M == SM_SentinelZero) {
1058 CS << SrcName << "[";
1060 if (M == SM_SentinelUndef)
1073 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
1074 X86MCInstLower MCInstLowering(*MF, *this);
1075 const X86RegisterInfo *RI = MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1077 switch (MI->getOpcode()) {
1078 case TargetOpcode::DBG_VALUE:
1079 llvm_unreachable("Should be handled target independently");
1081 // Emit nothing here but a comment if we can.
1082 case X86::Int_MemBarrier:
1083 OutStreamer->emitRawComment("MEMBARRIER");
1087 case X86::EH_RETURN:
1088 case X86::EH_RETURN64: {
1089 // Lower these as normal, but add some comments.
1090 unsigned Reg = MI->getOperand(0).getReg();
1091 OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1092 X86ATTInstPrinter::getRegisterName(Reg));
1095 case X86::CLEANUPRET: {
1096 // Lower these as normal, but add some comments.
1097 OutStreamer->AddComment("CLEANUPRET");
1101 case X86::CATCHRET: {
1102 // Lower these as normal, but add some comments.
1103 OutStreamer->AddComment("CATCHRET");
1110 case X86::TAILJMPr64:
1111 case X86::TAILJMPm64:
1112 case X86::TAILJMPd64:
1113 case X86::TAILJMPr64_REX:
1114 case X86::TAILJMPm64_REX:
1115 case X86::TAILJMPd64_REX:
1116 // Lower these as normal, but add some comments.
1117 OutStreamer->AddComment("TAILCALL");
1120 case X86::TLS_addr32:
1121 case X86::TLS_addr64:
1122 case X86::TLS_base_addr32:
1123 case X86::TLS_base_addr64:
1124 return LowerTlsAddr(MCInstLowering, *MI);
1126 case X86::MOVPC32r: {
1127 // This is a pseudo op for a two instruction sequence with a label, which
1134 MCSymbol *PICBase = MF->getPICBaseSymbol();
1135 // FIXME: We would like an efficient form for this, so we don't have to do a
1136 // lot of extra uniquing.
1137 EmitAndCountInstruction(MCInstBuilder(X86::CALLpcrel32)
1138 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1140 const X86FrameLowering* FrameLowering =
1141 MF->getSubtarget<X86Subtarget>().getFrameLowering();
1142 bool hasFP = FrameLowering->hasFP(*MF);
1144 // TODO: This is needed only if we require precise CFA.
1145 bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1146 !OutStreamer->getDwarfFrameInfos().back().End;
1148 int stackGrowth = -RI->getSlotSize();
1150 if (HasActiveDwarfFrame && !hasFP) {
1151 OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1155 OutStreamer->EmitLabel(PICBase);
1158 EmitAndCountInstruction(MCInstBuilder(X86::POP32r)
1159 .addReg(MI->getOperand(0).getReg()));
1161 if (HasActiveDwarfFrame && !hasFP) {
1162 OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1167 case X86::ADD32ri: {
1168 // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
1169 if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
1172 // Okay, we have something like:
1173 // EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
1175 // For this, we want to print something like:
1176 // MYGLOBAL + (. - PICBASE)
1177 // However, we can't generate a ".", so just emit a new label here and refer
1179 MCSymbol *DotSym = OutContext.createTempSymbol();
1180 OutStreamer->EmitLabel(DotSym);
1182 // Now that we have emitted the label, lower the complex operand expression.
1183 MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1185 const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1186 const MCExpr *PICBase =
1187 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
1188 DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
1190 DotExpr = MCBinaryExpr::createAdd(MCSymbolRefExpr::create(OpSym,OutContext),
1191 DotExpr, OutContext);
1193 EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
1194 .addReg(MI->getOperand(0).getReg())
1195 .addReg(MI->getOperand(1).getReg())
1199 case TargetOpcode::STATEPOINT:
1200 return LowerSTATEPOINT(*MI, MCInstLowering);
1202 case TargetOpcode::FAULTING_LOAD_OP:
1203 return LowerFAULTING_LOAD_OP(*MI, MCInstLowering);
1205 case TargetOpcode::STACKMAP:
1206 return LowerSTACKMAP(*MI);
1208 case TargetOpcode::PATCHPOINT:
1209 return LowerPATCHPOINT(*MI, MCInstLowering);
1211 case X86::MORESTACK_RET:
1212 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1215 case X86::MORESTACK_RET_RESTORE_R10:
1216 // Return, then restore R10.
1217 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1218 EmitAndCountInstruction(MCInstBuilder(X86::MOV64rr)
1223 case X86::SEH_PushReg:
1224 OutStreamer->EmitWinCFIPushReg(RI->getSEHRegNum(MI->getOperand(0).getImm()));
1227 case X86::SEH_SaveReg:
1228 OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1229 MI->getOperand(1).getImm());
1232 case X86::SEH_SaveXMM:
1233 OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1234 MI->getOperand(1).getImm());
1237 case X86::SEH_StackAlloc:
1238 OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1241 case X86::SEH_SetFrame:
1242 OutStreamer->EmitWinCFISetFrame(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1243 MI->getOperand(1).getImm());
1246 case X86::SEH_PushFrame:
1247 OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1250 case X86::SEH_EndPrologue:
1251 OutStreamer->EmitWinCFIEndProlog();
1254 case X86::SEH_Epilogue: {
1255 MachineBasicBlock::const_iterator MBBI(MI);
1256 // Check if preceded by a call and emit nop if so.
1257 for (MBBI = PrevCrossBBInst(MBBI); MBBI; MBBI = PrevCrossBBInst(MBBI)) {
1258 // Conservatively assume that pseudo instructions don't emit code and keep
1259 // looking for a call. We may emit an unnecessary nop in some cases.
1260 if (!MBBI->isPseudo()) {
1262 EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
1269 // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1270 // a constant shuffle mask. We won't be able to do this at the MC layer
1271 // because the mask isn't an immediate.
1273 case X86::VPSHUFBrm:
1274 case X86::VPSHUFBYrm:
1275 case X86::VPSHUFBZ128rm:
1276 case X86::VPSHUFBZ128rmk:
1277 case X86::VPSHUFBZ128rmkz:
1278 case X86::VPSHUFBZ256rm:
1279 case X86::VPSHUFBZ256rmk:
1280 case X86::VPSHUFBZ256rmkz:
1281 case X86::VPSHUFBZrm:
1282 case X86::VPSHUFBZrmk:
1283 case X86::VPSHUFBZrmkz: {
1284 if (!OutStreamer->isVerboseAsm())
1286 unsigned SrcIdx, MaskIdx;
1287 switch (MI->getOpcode()) {
1288 default: llvm_unreachable("Invalid opcode");
1290 case X86::VPSHUFBrm:
1291 case X86::VPSHUFBYrm:
1292 case X86::VPSHUFBZ128rm:
1293 case X86::VPSHUFBZ256rm:
1294 case X86::VPSHUFBZrm:
1295 SrcIdx = 1; MaskIdx = 5; break;
1296 case X86::VPSHUFBZ128rmkz:
1297 case X86::VPSHUFBZ256rmkz:
1298 case X86::VPSHUFBZrmkz:
1299 SrcIdx = 2; MaskIdx = 6; break;
1300 case X86::VPSHUFBZ128rmk:
1301 case X86::VPSHUFBZ256rmk:
1302 case X86::VPSHUFBZrmk:
1303 SrcIdx = 3; MaskIdx = 7; break;
1306 assert(MI->getNumOperands() >= 6 &&
1307 "We should always have at least 6 operands!");
1308 const MachineOperand &DstOp = MI->getOperand(0);
1309 const MachineOperand &SrcOp = MI->getOperand(SrcIdx);
1310 const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1312 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1313 SmallVector<int, 16> Mask;
1314 DecodePSHUFBMask(C, Mask);
1316 OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
1320 case X86::VPERMILPSrm:
1321 case X86::VPERMILPDrm:
1322 case X86::VPERMILPSYrm:
1323 case X86::VPERMILPDYrm: {
1324 if (!OutStreamer->isVerboseAsm())
1326 assert(MI->getNumOperands() > 5 &&
1327 "We should always have at least 5 operands!");
1328 const MachineOperand &DstOp = MI->getOperand(0);
1329 const MachineOperand &SrcOp = MI->getOperand(1);
1330 const MachineOperand &MaskOp = MI->getOperand(5);
1333 switch (MI->getOpcode()) {
1334 default: llvm_unreachable("Invalid opcode");
1335 case X86::VPERMILPSrm: case X86::VPERMILPSYrm: ElSize = 32; break;
1336 case X86::VPERMILPDrm: case X86::VPERMILPDYrm: ElSize = 64; break;
1339 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1340 SmallVector<int, 16> Mask;
1341 DecodeVPERMILPMask(C, ElSize, Mask);
1343 OutStreamer->AddComment(getShuffleComment(DstOp, SrcOp, Mask));
1348 #define MOV_CASE(Prefix, Suffix) \
1349 case X86::Prefix##MOVAPD##Suffix##rm: \
1350 case X86::Prefix##MOVAPS##Suffix##rm: \
1351 case X86::Prefix##MOVUPD##Suffix##rm: \
1352 case X86::Prefix##MOVUPS##Suffix##rm: \
1353 case X86::Prefix##MOVDQA##Suffix##rm: \
1354 case X86::Prefix##MOVDQU##Suffix##rm:
1356 #define MOV_AVX512_CASE(Suffix) \
1357 case X86::VMOVDQA64##Suffix##rm: \
1358 case X86::VMOVDQA32##Suffix##rm: \
1359 case X86::VMOVDQU64##Suffix##rm: \
1360 case X86::VMOVDQU32##Suffix##rm: \
1361 case X86::VMOVDQU16##Suffix##rm: \
1362 case X86::VMOVDQU8##Suffix##rm: \
1363 case X86::VMOVAPS##Suffix##rm: \
1364 case X86::VMOVAPD##Suffix##rm: \
1365 case X86::VMOVUPS##Suffix##rm: \
1366 case X86::VMOVUPD##Suffix##rm:
1368 #define CASE_ALL_MOV_RM() \
1369 MOV_CASE(, ) /* SSE */ \
1370 MOV_CASE(V, ) /* AVX-128 */ \
1371 MOV_CASE(V, Y) /* AVX-256 */ \
1372 MOV_AVX512_CASE(Z) \
1373 MOV_AVX512_CASE(Z256) \
1374 MOV_AVX512_CASE(Z128)
1376 // For loads from a constant pool to a vector register, print the constant
1379 if (!OutStreamer->isVerboseAsm())
1381 if (MI->getNumOperands() > 4)
1382 if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
1383 std::string Comment;
1384 raw_string_ostream CS(Comment);
1385 const MachineOperand &DstOp = MI->getOperand(0);
1386 CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
1387 if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
1389 for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements; ++i) {
1392 if (CDS->getElementType()->isIntegerTy())
1393 CS << CDS->getElementAsInteger(i);
1394 else if (CDS->getElementType()->isFloatTy())
1395 CS << CDS->getElementAsFloat(i);
1396 else if (CDS->getElementType()->isDoubleTy())
1397 CS << CDS->getElementAsDouble(i);
1402 OutStreamer->AddComment(CS.str());
1403 } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
1405 for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands; ++i) {
1408 Constant *COp = CV->getOperand(i);
1409 if (isa<UndefValue>(COp)) {
1411 } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1412 if (CI->getBitWidth() <= 64) {
1413 CS << CI->getZExtValue();
1415 // print multi-word constant as (w0,w1)
1416 auto Val = CI->getValue();
1418 for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1421 CS << Val.getRawData()[i];
1425 } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1426 SmallString<32> Str;
1427 CF->getValueAPF().toString(Str);
1434 OutStreamer->AddComment(CS.str());
1441 MCInstLowering.Lower(MI, TmpInst);
1443 // Stackmap shadows cannot include branch targets, so we can count the bytes
1444 // in a call towards the shadow, but must ensure that the no thread returns
1445 // in to the stackmap shadow. The only way to achieve this is if the call
1446 // is at the end of the shadow.
1448 // Count then size of the call towards the shadow
1449 SMShadowTracker.count(TmpInst, getSubtargetInfo());
1450 // Then flush the shadow so that we fill with nops before the call, not
1452 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1453 // Then emit the call
1454 OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
1458 EmitAndCountInstruction(TmpInst);