1 //===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains code to lower X86 MachineInstrs to their corresponding
11 // MCInst records.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstPrinter/X86ATTInstPrinter.h"
16 #include "InstPrinter/X86InstComments.h"
17 #include "MCTargetDesc/X86BaseInfo.h"
18 #include "MCTargetDesc/X86TargetStreamer.h"
19 #include "Utils/X86ShuffleDecode.h"
20 #include "X86AsmPrinter.h"
21 #include "X86RegisterInfo.h"
22 #include "X86ShuffleDecodeConstantPool.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/StackMaps.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCCodeEmitter.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCFixup.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCSectionELF.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/MCSymbolELF.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47
48 using namespace llvm;
49
50 namespace {
51
52 /// X86MCInstLower - This class is used to lower an MachineInstr into an MCInst.
53 class X86MCInstLower {
54 MCContext &Ctx;
55 const MachineFunction &MF;
56 const TargetMachine &TM;
57 const MCAsmInfo &MAI;
58 X86AsmPrinter &AsmPrinter;
59
60 public:
61 X86MCInstLower(const MachineFunction &MF, X86AsmPrinter &asmprinter);
62
63 Optional<MCOperand> LowerMachineOperand(const MachineInstr *MI,
64 const MachineOperand &MO) const;
65 void Lower(const MachineInstr *MI, MCInst &OutMI) const;
66
67 MCSymbol *GetSymbolFromOperand(const MachineOperand &MO) const;
68 MCOperand LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const;
69
70 private:
71 MachineModuleInfoMachO &getMachOMMI() const;
72 };
73
74 } // end anonymous namespace
75
76 // Emit a minimal sequence of nops spanning NumBytes bytes.
77 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
78 const MCSubtargetInfo &STI);
79
count(MCInst & Inst,const MCSubtargetInfo & STI,MCCodeEmitter * CodeEmitter)80 void X86AsmPrinter::StackMapShadowTracker::count(MCInst &Inst,
81 const MCSubtargetInfo &STI,
82 MCCodeEmitter *CodeEmitter) {
83 if (InShadow) {
84 SmallString<256> Code;
85 SmallVector<MCFixup, 4> Fixups;
86 raw_svector_ostream VecOS(Code);
87 CodeEmitter->encodeInstruction(Inst, VecOS, Fixups, STI);
88 CurrentShadowSize += Code.size();
89 if (CurrentShadowSize >= RequiredShadowSize)
90 InShadow = false; // The shadow is big enough. Stop counting.
91 }
92 }
93
emitShadowPadding(MCStreamer & OutStreamer,const MCSubtargetInfo & STI)94 void X86AsmPrinter::StackMapShadowTracker::emitShadowPadding(
95 MCStreamer &OutStreamer, const MCSubtargetInfo &STI) {
96 if (InShadow && CurrentShadowSize < RequiredShadowSize) {
97 InShadow = false;
98 EmitNops(OutStreamer, RequiredShadowSize - CurrentShadowSize,
99 MF->getSubtarget<X86Subtarget>().is64Bit(), STI);
100 }
101 }
102
EmitAndCountInstruction(MCInst & Inst)103 void X86AsmPrinter::EmitAndCountInstruction(MCInst &Inst) {
104 OutStreamer->EmitInstruction(Inst, getSubtargetInfo(),
105 EnablePrintSchedInfo &&
106 !(Inst.getFlags() & X86::NO_SCHED_INFO));
107 SMShadowTracker.count(Inst, getSubtargetInfo(), CodeEmitter.get());
108 }
109
X86MCInstLower(const MachineFunction & mf,X86AsmPrinter & asmprinter)110 X86MCInstLower::X86MCInstLower(const MachineFunction &mf,
111 X86AsmPrinter &asmprinter)
112 : Ctx(mf.getContext()), MF(mf), TM(mf.getTarget()), MAI(*TM.getMCAsmInfo()),
113 AsmPrinter(asmprinter) {}
114
getMachOMMI() const115 MachineModuleInfoMachO &X86MCInstLower::getMachOMMI() const {
116 return MF.getMMI().getObjFileInfo<MachineModuleInfoMachO>();
117 }
118
119 /// GetSymbolFromOperand - Lower an MO_GlobalAddress or MO_ExternalSymbol
120 /// operand to an MCSymbol.
GetSymbolFromOperand(const MachineOperand & MO) const121 MCSymbol *X86MCInstLower::GetSymbolFromOperand(const MachineOperand &MO) const {
122 const DataLayout &DL = MF.getDataLayout();
123 assert((MO.isGlobal() || MO.isSymbol() || MO.isMBB()) &&
124 "Isn't a symbol reference");
125
126 MCSymbol *Sym = nullptr;
127 SmallString<128> Name;
128 StringRef Suffix;
129
130 switch (MO.getTargetFlags()) {
131 case X86II::MO_DLLIMPORT:
132 // Handle dllimport linkage.
133 Name += "__imp_";
134 break;
135 case X86II::MO_DARWIN_NONLAZY:
136 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
137 Suffix = "$non_lazy_ptr";
138 break;
139 }
140
141 if (!Suffix.empty())
142 Name += DL.getPrivateGlobalPrefix();
143
144 if (MO.isGlobal()) {
145 const GlobalValue *GV = MO.getGlobal();
146 AsmPrinter.getNameWithPrefix(Name, GV);
147 } else if (MO.isSymbol()) {
148 Mangler::getNameWithPrefix(Name, MO.getSymbolName(), DL);
149 } else if (MO.isMBB()) {
150 assert(Suffix.empty());
151 Sym = MO.getMBB()->getSymbol();
152 }
153
154 Name += Suffix;
155 if (!Sym)
156 Sym = Ctx.getOrCreateSymbol(Name);
157
158 // If the target flags on the operand changes the name of the symbol, do that
159 // before we return the symbol.
160 switch (MO.getTargetFlags()) {
161 default:
162 break;
163 case X86II::MO_DARWIN_NONLAZY:
164 case X86II::MO_DARWIN_NONLAZY_PIC_BASE: {
165 MachineModuleInfoImpl::StubValueTy &StubSym =
166 getMachOMMI().getGVStubEntry(Sym);
167 if (!StubSym.getPointer()) {
168 assert(MO.isGlobal() && "Extern symbol not handled yet");
169 StubSym = MachineModuleInfoImpl::StubValueTy(
170 AsmPrinter.getSymbol(MO.getGlobal()),
171 !MO.getGlobal()->hasInternalLinkage());
172 }
173 break;
174 }
175 }
176
177 return Sym;
178 }
179
LowerSymbolOperand(const MachineOperand & MO,MCSymbol * Sym) const180 MCOperand X86MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
181 MCSymbol *Sym) const {
182 // FIXME: We would like an efficient form for this, so we don't have to do a
183 // lot of extra uniquing.
184 const MCExpr *Expr = nullptr;
185 MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
186
187 switch (MO.getTargetFlags()) {
188 default:
189 llvm_unreachable("Unknown target flag on GV operand");
190 case X86II::MO_NO_FLAG: // No flag.
191 // These affect the name of the symbol, not any suffix.
192 case X86II::MO_DARWIN_NONLAZY:
193 case X86II::MO_DLLIMPORT:
194 break;
195
196 case X86II::MO_TLVP:
197 RefKind = MCSymbolRefExpr::VK_TLVP;
198 break;
199 case X86II::MO_TLVP_PIC_BASE:
200 Expr = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_TLVP, Ctx);
201 // Subtract the pic base.
202 Expr = MCBinaryExpr::createSub(
203 Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
204 break;
205 case X86II::MO_SECREL:
206 RefKind = MCSymbolRefExpr::VK_SECREL;
207 break;
208 case X86II::MO_TLSGD:
209 RefKind = MCSymbolRefExpr::VK_TLSGD;
210 break;
211 case X86II::MO_TLSLD:
212 RefKind = MCSymbolRefExpr::VK_TLSLD;
213 break;
214 case X86II::MO_TLSLDM:
215 RefKind = MCSymbolRefExpr::VK_TLSLDM;
216 break;
217 case X86II::MO_GOTTPOFF:
218 RefKind = MCSymbolRefExpr::VK_GOTTPOFF;
219 break;
220 case X86II::MO_INDNTPOFF:
221 RefKind = MCSymbolRefExpr::VK_INDNTPOFF;
222 break;
223 case X86II::MO_TPOFF:
224 RefKind = MCSymbolRefExpr::VK_TPOFF;
225 break;
226 case X86II::MO_DTPOFF:
227 RefKind = MCSymbolRefExpr::VK_DTPOFF;
228 break;
229 case X86II::MO_NTPOFF:
230 RefKind = MCSymbolRefExpr::VK_NTPOFF;
231 break;
232 case X86II::MO_GOTNTPOFF:
233 RefKind = MCSymbolRefExpr::VK_GOTNTPOFF;
234 break;
235 case X86II::MO_GOTPCREL:
236 RefKind = MCSymbolRefExpr::VK_GOTPCREL;
237 break;
238 case X86II::MO_GOT:
239 RefKind = MCSymbolRefExpr::VK_GOT;
240 break;
241 case X86II::MO_GOTOFF:
242 RefKind = MCSymbolRefExpr::VK_GOTOFF;
243 break;
244 case X86II::MO_PLT:
245 RefKind = MCSymbolRefExpr::VK_PLT;
246 break;
247 case X86II::MO_ABS8:
248 RefKind = MCSymbolRefExpr::VK_X86_ABS8;
249 break;
250 case X86II::MO_PIC_BASE_OFFSET:
251 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
252 Expr = MCSymbolRefExpr::create(Sym, Ctx);
253 // Subtract the pic base.
254 Expr = MCBinaryExpr::createSub(
255 Expr, MCSymbolRefExpr::create(MF.getPICBaseSymbol(), Ctx), Ctx);
256 if (MO.isJTI()) {
257 assert(MAI.doesSetDirectiveSuppressReloc());
258 // If .set directive is supported, use it to reduce the number of
259 // relocations the assembler will generate for differences between
260 // local labels. This is only safe when the symbols are in the same
261 // section so we are restricting it to jumptable references.
262 MCSymbol *Label = Ctx.createTempSymbol();
263 AsmPrinter.OutStreamer->EmitAssignment(Label, Expr);
264 Expr = MCSymbolRefExpr::create(Label, Ctx);
265 }
266 break;
267 }
268
269 if (!Expr)
270 Expr = MCSymbolRefExpr::create(Sym, RefKind, Ctx);
271
272 if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
273 Expr = MCBinaryExpr::createAdd(
274 Expr, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
275 return MCOperand::createExpr(Expr);
276 }
277
278 /// Simplify FOO $imm, %{al,ax,eax,rax} to FOO $imm, for instruction with
279 /// a short fixed-register form.
SimplifyShortImmForm(MCInst & Inst,unsigned Opcode)280 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
281 unsigned ImmOp = Inst.getNumOperands() - 1;
282 assert(Inst.getOperand(0).isReg() &&
283 (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr()) &&
284 ((Inst.getNumOperands() == 3 && Inst.getOperand(1).isReg() &&
285 Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) ||
286 Inst.getNumOperands() == 2) &&
287 "Unexpected instruction!");
288
289 // Check whether the destination register can be fixed.
290 unsigned Reg = Inst.getOperand(0).getReg();
291 if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
292 return;
293
294 // If so, rewrite the instruction.
295 MCOperand Saved = Inst.getOperand(ImmOp);
296 Inst = MCInst();
297 Inst.setOpcode(Opcode);
298 Inst.addOperand(Saved);
299 }
300
301 /// If a movsx instruction has a shorter encoding for the used register
302 /// simplify the instruction to use it instead.
SimplifyMOVSX(MCInst & Inst)303 static void SimplifyMOVSX(MCInst &Inst) {
304 unsigned NewOpcode = 0;
305 unsigned Op0 = Inst.getOperand(0).getReg(), Op1 = Inst.getOperand(1).getReg();
306 switch (Inst.getOpcode()) {
307 default:
308 llvm_unreachable("Unexpected instruction!");
309 case X86::MOVSX16rr8: // movsbw %al, %ax --> cbtw
310 if (Op0 == X86::AX && Op1 == X86::AL)
311 NewOpcode = X86::CBW;
312 break;
313 case X86::MOVSX32rr16: // movswl %ax, %eax --> cwtl
314 if (Op0 == X86::EAX && Op1 == X86::AX)
315 NewOpcode = X86::CWDE;
316 break;
317 case X86::MOVSX64rr32: // movslq %eax, %rax --> cltq
318 if (Op0 == X86::RAX && Op1 == X86::EAX)
319 NewOpcode = X86::CDQE;
320 break;
321 }
322
323 if (NewOpcode != 0) {
324 Inst = MCInst();
325 Inst.setOpcode(NewOpcode);
326 }
327 }
328
329 /// Simplify things like MOV32rm to MOV32o32a.
SimplifyShortMoveForm(X86AsmPrinter & Printer,MCInst & Inst,unsigned Opcode)330 static void SimplifyShortMoveForm(X86AsmPrinter &Printer, MCInst &Inst,
331 unsigned Opcode) {
332 // Don't make these simplifications in 64-bit mode; other assemblers don't
333 // perform them because they make the code larger.
334 if (Printer.getSubtarget().is64Bit())
335 return;
336
337 bool IsStore = Inst.getOperand(0).isReg() && Inst.getOperand(1).isReg();
338 unsigned AddrBase = IsStore;
339 unsigned RegOp = IsStore ? 0 : 5;
340 unsigned AddrOp = AddrBase + 3;
341 assert(
342 Inst.getNumOperands() == 6 && Inst.getOperand(RegOp).isReg() &&
343 Inst.getOperand(AddrBase + X86::AddrBaseReg).isReg() &&
344 Inst.getOperand(AddrBase + X86::AddrScaleAmt).isImm() &&
345 Inst.getOperand(AddrBase + X86::AddrIndexReg).isReg() &&
346 Inst.getOperand(AddrBase + X86::AddrSegmentReg).isReg() &&
347 (Inst.getOperand(AddrOp).isExpr() || Inst.getOperand(AddrOp).isImm()) &&
348 "Unexpected instruction!");
349
350 // Check whether the destination register can be fixed.
351 unsigned Reg = Inst.getOperand(RegOp).getReg();
352 if (Reg != X86::AL && Reg != X86::AX && Reg != X86::EAX && Reg != X86::RAX)
353 return;
354
355 // Check whether this is an absolute address.
356 // FIXME: We know TLVP symbol refs aren't, but there should be a better way
357 // to do this here.
358 bool Absolute = true;
359 if (Inst.getOperand(AddrOp).isExpr()) {
360 const MCExpr *MCE = Inst.getOperand(AddrOp).getExpr();
361 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(MCE))
362 if (SRE->getKind() == MCSymbolRefExpr::VK_TLVP)
363 Absolute = false;
364 }
365
366 if (Absolute &&
367 (Inst.getOperand(AddrBase + X86::AddrBaseReg).getReg() != 0 ||
368 Inst.getOperand(AddrBase + X86::AddrScaleAmt).getImm() != 1 ||
369 Inst.getOperand(AddrBase + X86::AddrIndexReg).getReg() != 0))
370 return;
371
372 // If so, rewrite the instruction.
373 MCOperand Saved = Inst.getOperand(AddrOp);
374 MCOperand Seg = Inst.getOperand(AddrBase + X86::AddrSegmentReg);
375 Inst = MCInst();
376 Inst.setOpcode(Opcode);
377 Inst.addOperand(Saved);
378 Inst.addOperand(Seg);
379 }
380
getRetOpcode(const X86Subtarget & Subtarget)381 static unsigned getRetOpcode(const X86Subtarget &Subtarget) {
382 return Subtarget.is64Bit() ? X86::RETQ : X86::RETL;
383 }
384
385 Optional<MCOperand>
LowerMachineOperand(const MachineInstr * MI,const MachineOperand & MO) const386 X86MCInstLower::LowerMachineOperand(const MachineInstr *MI,
387 const MachineOperand &MO) const {
388 switch (MO.getType()) {
389 default:
390 MI->print(errs());
391 llvm_unreachable("unknown operand type");
392 case MachineOperand::MO_Register:
393 // Ignore all implicit register operands.
394 if (MO.isImplicit())
395 return None;
396 return MCOperand::createReg(MO.getReg());
397 case MachineOperand::MO_Immediate:
398 return MCOperand::createImm(MO.getImm());
399 case MachineOperand::MO_MachineBasicBlock:
400 case MachineOperand::MO_GlobalAddress:
401 case MachineOperand::MO_ExternalSymbol:
402 return LowerSymbolOperand(MO, GetSymbolFromOperand(MO));
403 case MachineOperand::MO_MCSymbol:
404 return LowerSymbolOperand(MO, MO.getMCSymbol());
405 case MachineOperand::MO_JumpTableIndex:
406 return LowerSymbolOperand(MO, AsmPrinter.GetJTISymbol(MO.getIndex()));
407 case MachineOperand::MO_ConstantPoolIndex:
408 return LowerSymbolOperand(MO, AsmPrinter.GetCPISymbol(MO.getIndex()));
409 case MachineOperand::MO_BlockAddress:
410 return LowerSymbolOperand(
411 MO, AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()));
412 case MachineOperand::MO_RegisterMask:
413 // Ignore call clobbers.
414 return None;
415 }
416 }
417
Lower(const MachineInstr * MI,MCInst & OutMI) const418 void X86MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
419 OutMI.setOpcode(MI->getOpcode());
420
421 for (const MachineOperand &MO : MI->operands())
422 if (auto MaybeMCOp = LowerMachineOperand(MI, MO))
423 OutMI.addOperand(MaybeMCOp.getValue());
424
425 // Handle a few special cases to eliminate operand modifiers.
426 ReSimplify:
427 switch (OutMI.getOpcode()) {
428 case X86::LEA64_32r:
429 case X86::LEA64r:
430 case X86::LEA16r:
431 case X86::LEA32r:
432 // LEA should have a segment register, but it must be empty.
433 assert(OutMI.getNumOperands() == 1 + X86::AddrNumOperands &&
434 "Unexpected # of LEA operands");
435 assert(OutMI.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
436 "LEA has segment specified!");
437 break;
438
439 // Commute operands to get a smaller encoding by using VEX.R instead of VEX.B
440 // if one of the registers is extended, but other isn't.
441 case X86::VMOVZPQILo2PQIrr:
442 case X86::VMOVAPDrr:
443 case X86::VMOVAPDYrr:
444 case X86::VMOVAPSrr:
445 case X86::VMOVAPSYrr:
446 case X86::VMOVDQArr:
447 case X86::VMOVDQAYrr:
448 case X86::VMOVDQUrr:
449 case X86::VMOVDQUYrr:
450 case X86::VMOVUPDrr:
451 case X86::VMOVUPDYrr:
452 case X86::VMOVUPSrr:
453 case X86::VMOVUPSYrr: {
454 if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
455 X86II::isX86_64ExtendedReg(OutMI.getOperand(1).getReg())) {
456 unsigned NewOpc;
457 switch (OutMI.getOpcode()) {
458 default: llvm_unreachable("Invalid opcode");
459 case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break;
460 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
461 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
462 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
463 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
464 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
465 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
466 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
467 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
468 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
469 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
470 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
471 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
472 }
473 OutMI.setOpcode(NewOpc);
474 }
475 break;
476 }
477 case X86::VMOVSDrr:
478 case X86::VMOVSSrr: {
479 if (!X86II::isX86_64ExtendedReg(OutMI.getOperand(0).getReg()) &&
480 X86II::isX86_64ExtendedReg(OutMI.getOperand(2).getReg())) {
481 unsigned NewOpc;
482 switch (OutMI.getOpcode()) {
483 default: llvm_unreachable("Invalid opcode");
484 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
485 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
486 }
487 OutMI.setOpcode(NewOpc);
488 }
489 break;
490 }
491
492 // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
493 // inputs modeled as normal uses instead of implicit uses. As such, truncate
494 // off all but the first operand (the callee). FIXME: Change isel.
495 case X86::TAILJMPr64:
496 case X86::TAILJMPr64_REX:
497 case X86::CALL64r:
498 case X86::CALL64pcrel32: {
499 unsigned Opcode = OutMI.getOpcode();
500 MCOperand Saved = OutMI.getOperand(0);
501 OutMI = MCInst();
502 OutMI.setOpcode(Opcode);
503 OutMI.addOperand(Saved);
504 break;
505 }
506
507 case X86::EH_RETURN:
508 case X86::EH_RETURN64: {
509 OutMI = MCInst();
510 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
511 break;
512 }
513
514 case X86::CLEANUPRET: {
515 // Replace CATCHRET with the appropriate RET.
516 OutMI = MCInst();
517 OutMI.setOpcode(getRetOpcode(AsmPrinter.getSubtarget()));
518 break;
519 }
520
521 case X86::CATCHRET: {
522 // Replace CATCHRET with the appropriate RET.
523 const X86Subtarget &Subtarget = AsmPrinter.getSubtarget();
524 unsigned ReturnReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
525 OutMI = MCInst();
526 OutMI.setOpcode(getRetOpcode(Subtarget));
527 OutMI.addOperand(MCOperand::createReg(ReturnReg));
528 break;
529 }
530
531 // TAILJMPd, TAILJMPd64, TailJMPd_cc - Lower to the correct jump
532 // instruction.
533 {
534 unsigned Opcode;
535 case X86::TAILJMPr:
536 Opcode = X86::JMP32r;
537 goto SetTailJmpOpcode;
538 case X86::TAILJMPd:
539 case X86::TAILJMPd64:
540 Opcode = X86::JMP_1;
541 goto SetTailJmpOpcode;
542 case X86::TAILJMPd_CC:
543 case X86::TAILJMPd64_CC:
544 Opcode = X86::GetCondBranchFromCond(
545 static_cast<X86::CondCode>(MI->getOperand(1).getImm()));
546 goto SetTailJmpOpcode;
547
548 SetTailJmpOpcode:
549 MCOperand Saved = OutMI.getOperand(0);
550 OutMI = MCInst();
551 OutMI.setOpcode(Opcode);
552 OutMI.addOperand(Saved);
553 break;
554 }
555
556 case X86::DEC16r:
557 case X86::DEC32r:
558 case X86::INC16r:
559 case X86::INC32r:
560 // If we aren't in 64-bit mode we can use the 1-byte inc/dec instructions.
561 if (!AsmPrinter.getSubtarget().is64Bit()) {
562 unsigned Opcode;
563 switch (OutMI.getOpcode()) {
564 default: llvm_unreachable("Invalid opcode");
565 case X86::DEC16r: Opcode = X86::DEC16r_alt; break;
566 case X86::DEC32r: Opcode = X86::DEC32r_alt; break;
567 case X86::INC16r: Opcode = X86::INC16r_alt; break;
568 case X86::INC32r: Opcode = X86::INC32r_alt; break;
569 }
570 OutMI.setOpcode(Opcode);
571 }
572 break;
573
574 // These are pseudo-ops for OR to help with the OR->ADD transformation. We do
575 // this with an ugly goto in case the resultant OR uses EAX and needs the
576 // short form.
577 case X86::ADD16rr_DB: OutMI.setOpcode(X86::OR16rr); goto ReSimplify;
578 case X86::ADD32rr_DB: OutMI.setOpcode(X86::OR32rr); goto ReSimplify;
579 case X86::ADD64rr_DB: OutMI.setOpcode(X86::OR64rr); goto ReSimplify;
580 case X86::ADD16ri_DB: OutMI.setOpcode(X86::OR16ri); goto ReSimplify;
581 case X86::ADD32ri_DB: OutMI.setOpcode(X86::OR32ri); goto ReSimplify;
582 case X86::ADD64ri32_DB: OutMI.setOpcode(X86::OR64ri32); goto ReSimplify;
583 case X86::ADD16ri8_DB: OutMI.setOpcode(X86::OR16ri8); goto ReSimplify;
584 case X86::ADD32ri8_DB: OutMI.setOpcode(X86::OR32ri8); goto ReSimplify;
585 case X86::ADD64ri8_DB: OutMI.setOpcode(X86::OR64ri8); goto ReSimplify;
586
587 // Atomic load and store require a separate pseudo-inst because Acquire
588 // implies mayStore and Release implies mayLoad; fix these to regular MOV
589 // instructions here
590 case X86::ACQUIRE_MOV8rm: OutMI.setOpcode(X86::MOV8rm); goto ReSimplify;
591 case X86::ACQUIRE_MOV16rm: OutMI.setOpcode(X86::MOV16rm); goto ReSimplify;
592 case X86::ACQUIRE_MOV32rm: OutMI.setOpcode(X86::MOV32rm); goto ReSimplify;
593 case X86::ACQUIRE_MOV64rm: OutMI.setOpcode(X86::MOV64rm); goto ReSimplify;
594 case X86::RELEASE_MOV8mr: OutMI.setOpcode(X86::MOV8mr); goto ReSimplify;
595 case X86::RELEASE_MOV16mr: OutMI.setOpcode(X86::MOV16mr); goto ReSimplify;
596 case X86::RELEASE_MOV32mr: OutMI.setOpcode(X86::MOV32mr); goto ReSimplify;
597 case X86::RELEASE_MOV64mr: OutMI.setOpcode(X86::MOV64mr); goto ReSimplify;
598 case X86::RELEASE_MOV8mi: OutMI.setOpcode(X86::MOV8mi); goto ReSimplify;
599 case X86::RELEASE_MOV16mi: OutMI.setOpcode(X86::MOV16mi); goto ReSimplify;
600 case X86::RELEASE_MOV32mi: OutMI.setOpcode(X86::MOV32mi); goto ReSimplify;
601 case X86::RELEASE_MOV64mi32: OutMI.setOpcode(X86::MOV64mi32); goto ReSimplify;
602 case X86::RELEASE_ADD8mi: OutMI.setOpcode(X86::ADD8mi); goto ReSimplify;
603 case X86::RELEASE_ADD8mr: OutMI.setOpcode(X86::ADD8mr); goto ReSimplify;
604 case X86::RELEASE_ADD32mi: OutMI.setOpcode(X86::ADD32mi); goto ReSimplify;
605 case X86::RELEASE_ADD32mr: OutMI.setOpcode(X86::ADD32mr); goto ReSimplify;
606 case X86::RELEASE_ADD64mi32: OutMI.setOpcode(X86::ADD64mi32); goto ReSimplify;
607 case X86::RELEASE_ADD64mr: OutMI.setOpcode(X86::ADD64mr); goto ReSimplify;
608 case X86::RELEASE_AND8mi: OutMI.setOpcode(X86::AND8mi); goto ReSimplify;
609 case X86::RELEASE_AND8mr: OutMI.setOpcode(X86::AND8mr); goto ReSimplify;
610 case X86::RELEASE_AND32mi: OutMI.setOpcode(X86::AND32mi); goto ReSimplify;
611 case X86::RELEASE_AND32mr: OutMI.setOpcode(X86::AND32mr); goto ReSimplify;
612 case X86::RELEASE_AND64mi32: OutMI.setOpcode(X86::AND64mi32); goto ReSimplify;
613 case X86::RELEASE_AND64mr: OutMI.setOpcode(X86::AND64mr); goto ReSimplify;
614 case X86::RELEASE_OR8mi: OutMI.setOpcode(X86::OR8mi); goto ReSimplify;
615 case X86::RELEASE_OR8mr: OutMI.setOpcode(X86::OR8mr); goto ReSimplify;
616 case X86::RELEASE_OR32mi: OutMI.setOpcode(X86::OR32mi); goto ReSimplify;
617 case X86::RELEASE_OR32mr: OutMI.setOpcode(X86::OR32mr); goto ReSimplify;
618 case X86::RELEASE_OR64mi32: OutMI.setOpcode(X86::OR64mi32); goto ReSimplify;
619 case X86::RELEASE_OR64mr: OutMI.setOpcode(X86::OR64mr); goto ReSimplify;
620 case X86::RELEASE_XOR8mi: OutMI.setOpcode(X86::XOR8mi); goto ReSimplify;
621 case X86::RELEASE_XOR8mr: OutMI.setOpcode(X86::XOR8mr); goto ReSimplify;
622 case X86::RELEASE_XOR32mi: OutMI.setOpcode(X86::XOR32mi); goto ReSimplify;
623 case X86::RELEASE_XOR32mr: OutMI.setOpcode(X86::XOR32mr); goto ReSimplify;
624 case X86::RELEASE_XOR64mi32: OutMI.setOpcode(X86::XOR64mi32); goto ReSimplify;
625 case X86::RELEASE_XOR64mr: OutMI.setOpcode(X86::XOR64mr); goto ReSimplify;
626 case X86::RELEASE_INC8m: OutMI.setOpcode(X86::INC8m); goto ReSimplify;
627 case X86::RELEASE_INC16m: OutMI.setOpcode(X86::INC16m); goto ReSimplify;
628 case X86::RELEASE_INC32m: OutMI.setOpcode(X86::INC32m); goto ReSimplify;
629 case X86::RELEASE_INC64m: OutMI.setOpcode(X86::INC64m); goto ReSimplify;
630 case X86::RELEASE_DEC8m: OutMI.setOpcode(X86::DEC8m); goto ReSimplify;
631 case X86::RELEASE_DEC16m: OutMI.setOpcode(X86::DEC16m); goto ReSimplify;
632 case X86::RELEASE_DEC32m: OutMI.setOpcode(X86::DEC32m); goto ReSimplify;
633 case X86::RELEASE_DEC64m: OutMI.setOpcode(X86::DEC64m); goto ReSimplify;
634
635 // We don't currently select the correct instruction form for instructions
636 // which have a short %eax, etc. form. Handle this by custom lowering, for
637 // now.
638 //
639 // Note, we are currently not handling the following instructions:
640 // MOV64ao8, MOV64o8a
641 // XCHG16ar, XCHG32ar, XCHG64ar
642 case X86::MOV8mr_NOREX:
643 case X86::MOV8mr:
644 case X86::MOV8rm_NOREX:
645 case X86::MOV8rm:
646 case X86::MOV16mr:
647 case X86::MOV16rm:
648 case X86::MOV32mr:
649 case X86::MOV32rm: {
650 unsigned NewOpc;
651 switch (OutMI.getOpcode()) {
652 default: llvm_unreachable("Invalid opcode");
653 case X86::MOV8mr_NOREX:
654 case X86::MOV8mr: NewOpc = X86::MOV8o32a; break;
655 case X86::MOV8rm_NOREX:
656 case X86::MOV8rm: NewOpc = X86::MOV8ao32; break;
657 case X86::MOV16mr: NewOpc = X86::MOV16o32a; break;
658 case X86::MOV16rm: NewOpc = X86::MOV16ao32; break;
659 case X86::MOV32mr: NewOpc = X86::MOV32o32a; break;
660 case X86::MOV32rm: NewOpc = X86::MOV32ao32; break;
661 }
662 SimplifyShortMoveForm(AsmPrinter, OutMI, NewOpc);
663 break;
664 }
665
666 case X86::ADC8ri: case X86::ADC16ri: case X86::ADC32ri: case X86::ADC64ri32:
667 case X86::ADD8ri: case X86::ADD16ri: case X86::ADD32ri: case X86::ADD64ri32:
668 case X86::AND8ri: case X86::AND16ri: case X86::AND32ri: case X86::AND64ri32:
669 case X86::CMP8ri: case X86::CMP16ri: case X86::CMP32ri: case X86::CMP64ri32:
670 case X86::OR8ri: case X86::OR16ri: case X86::OR32ri: case X86::OR64ri32:
671 case X86::SBB8ri: case X86::SBB16ri: case X86::SBB32ri: case X86::SBB64ri32:
672 case X86::SUB8ri: case X86::SUB16ri: case X86::SUB32ri: case X86::SUB64ri32:
673 case X86::TEST8ri:case X86::TEST16ri:case X86::TEST32ri:case X86::TEST64ri32:
674 case X86::XOR8ri: case X86::XOR16ri: case X86::XOR32ri: case X86::XOR64ri32: {
675 unsigned NewOpc;
676 switch (OutMI.getOpcode()) {
677 default: llvm_unreachable("Invalid opcode");
678 case X86::ADC8ri: NewOpc = X86::ADC8i8; break;
679 case X86::ADC16ri: NewOpc = X86::ADC16i16; break;
680 case X86::ADC32ri: NewOpc = X86::ADC32i32; break;
681 case X86::ADC64ri32: NewOpc = X86::ADC64i32; break;
682 case X86::ADD8ri: NewOpc = X86::ADD8i8; break;
683 case X86::ADD16ri: NewOpc = X86::ADD16i16; break;
684 case X86::ADD32ri: NewOpc = X86::ADD32i32; break;
685 case X86::ADD64ri32: NewOpc = X86::ADD64i32; break;
686 case X86::AND8ri: NewOpc = X86::AND8i8; break;
687 case X86::AND16ri: NewOpc = X86::AND16i16; break;
688 case X86::AND32ri: NewOpc = X86::AND32i32; break;
689 case X86::AND64ri32: NewOpc = X86::AND64i32; break;
690 case X86::CMP8ri: NewOpc = X86::CMP8i8; break;
691 case X86::CMP16ri: NewOpc = X86::CMP16i16; break;
692 case X86::CMP32ri: NewOpc = X86::CMP32i32; break;
693 case X86::CMP64ri32: NewOpc = X86::CMP64i32; break;
694 case X86::OR8ri: NewOpc = X86::OR8i8; break;
695 case X86::OR16ri: NewOpc = X86::OR16i16; break;
696 case X86::OR32ri: NewOpc = X86::OR32i32; break;
697 case X86::OR64ri32: NewOpc = X86::OR64i32; break;
698 case X86::SBB8ri: NewOpc = X86::SBB8i8; break;
699 case X86::SBB16ri: NewOpc = X86::SBB16i16; break;
700 case X86::SBB32ri: NewOpc = X86::SBB32i32; break;
701 case X86::SBB64ri32: NewOpc = X86::SBB64i32; break;
702 case X86::SUB8ri: NewOpc = X86::SUB8i8; break;
703 case X86::SUB16ri: NewOpc = X86::SUB16i16; break;
704 case X86::SUB32ri: NewOpc = X86::SUB32i32; break;
705 case X86::SUB64ri32: NewOpc = X86::SUB64i32; break;
706 case X86::TEST8ri: NewOpc = X86::TEST8i8; break;
707 case X86::TEST16ri: NewOpc = X86::TEST16i16; break;
708 case X86::TEST32ri: NewOpc = X86::TEST32i32; break;
709 case X86::TEST64ri32: NewOpc = X86::TEST64i32; break;
710 case X86::XOR8ri: NewOpc = X86::XOR8i8; break;
711 case X86::XOR16ri: NewOpc = X86::XOR16i16; break;
712 case X86::XOR32ri: NewOpc = X86::XOR32i32; break;
713 case X86::XOR64ri32: NewOpc = X86::XOR64i32; break;
714 }
715 SimplifyShortImmForm(OutMI, NewOpc);
716 break;
717 }
718
719 // Try to shrink some forms of movsx.
720 case X86::MOVSX16rr8:
721 case X86::MOVSX32rr16:
722 case X86::MOVSX64rr32:
723 SimplifyMOVSX(OutMI);
724 break;
725 }
726 }
727
LowerTlsAddr(X86MCInstLower & MCInstLowering,const MachineInstr & MI)728 void X86AsmPrinter::LowerTlsAddr(X86MCInstLower &MCInstLowering,
729 const MachineInstr &MI) {
730
731 bool is64Bits = MI.getOpcode() == X86::TLS_addr64 ||
732 MI.getOpcode() == X86::TLS_base_addr64;
733
734 bool needsPadding = MI.getOpcode() == X86::TLS_addr64;
735
736 MCContext &context = OutStreamer->getContext();
737
738 if (needsPadding)
739 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
740
741 MCSymbolRefExpr::VariantKind SRVK;
742 switch (MI.getOpcode()) {
743 case X86::TLS_addr32:
744 case X86::TLS_addr64:
745 SRVK = MCSymbolRefExpr::VK_TLSGD;
746 break;
747 case X86::TLS_base_addr32:
748 SRVK = MCSymbolRefExpr::VK_TLSLDM;
749 break;
750 case X86::TLS_base_addr64:
751 SRVK = MCSymbolRefExpr::VK_TLSLD;
752 break;
753 default:
754 llvm_unreachable("unexpected opcode");
755 }
756
757 MCSymbol *sym = MCInstLowering.GetSymbolFromOperand(MI.getOperand(3));
758 const MCSymbolRefExpr *symRef = MCSymbolRefExpr::create(sym, SRVK, context);
759
760 MCInst LEA;
761 if (is64Bits) {
762 LEA.setOpcode(X86::LEA64r);
763 LEA.addOperand(MCOperand::createReg(X86::RDI)); // dest
764 LEA.addOperand(MCOperand::createReg(X86::RIP)); // base
765 LEA.addOperand(MCOperand::createImm(1)); // scale
766 LEA.addOperand(MCOperand::createReg(0)); // index
767 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
768 LEA.addOperand(MCOperand::createReg(0)); // seg
769 } else if (SRVK == MCSymbolRefExpr::VK_TLSLDM) {
770 LEA.setOpcode(X86::LEA32r);
771 LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
772 LEA.addOperand(MCOperand::createReg(X86::EBX)); // base
773 LEA.addOperand(MCOperand::createImm(1)); // scale
774 LEA.addOperand(MCOperand::createReg(0)); // index
775 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
776 LEA.addOperand(MCOperand::createReg(0)); // seg
777 } else {
778 LEA.setOpcode(X86::LEA32r);
779 LEA.addOperand(MCOperand::createReg(X86::EAX)); // dest
780 LEA.addOperand(MCOperand::createReg(0)); // base
781 LEA.addOperand(MCOperand::createImm(1)); // scale
782 LEA.addOperand(MCOperand::createReg(X86::EBX)); // index
783 LEA.addOperand(MCOperand::createExpr(symRef)); // disp
784 LEA.addOperand(MCOperand::createReg(0)); // seg
785 }
786 EmitAndCountInstruction(LEA);
787
788 if (needsPadding) {
789 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
790 EmitAndCountInstruction(MCInstBuilder(X86::DATA16_PREFIX));
791 EmitAndCountInstruction(MCInstBuilder(X86::REX64_PREFIX));
792 }
793
794 StringRef name = is64Bits ? "__tls_get_addr" : "___tls_get_addr";
795 MCSymbol *tlsGetAddr = context.getOrCreateSymbol(name);
796 const MCSymbolRefExpr *tlsRef =
797 MCSymbolRefExpr::create(tlsGetAddr, MCSymbolRefExpr::VK_PLT, context);
798
799 EmitAndCountInstruction(
800 MCInstBuilder(is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
801 .addExpr(tlsRef));
802 }
803
804 /// Emit the largest nop instruction smaller than or equal to \p NumBytes
805 /// bytes. Return the size of nop emitted.
EmitNop(MCStreamer & OS,unsigned NumBytes,bool Is64Bit,const MCSubtargetInfo & STI)806 static unsigned EmitNop(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
807 const MCSubtargetInfo &STI) {
808 // This works only for 64bit. For 32bit we have to do additional checking if
809 // the CPU supports multi-byte nops.
810 assert(Is64Bit && "EmitNops only supports X86-64");
811
812 unsigned NopSize;
813 unsigned Opc, BaseReg, ScaleVal, IndexReg, Displacement, SegmentReg;
814 Opc = IndexReg = Displacement = SegmentReg = 0;
815 BaseReg = X86::RAX;
816 ScaleVal = 1;
817 switch (NumBytes) {
818 case 0:
819 llvm_unreachable("Zero nops?");
820 break;
821 case 1:
822 NopSize = 1;
823 Opc = X86::NOOP;
824 break;
825 case 2:
826 NopSize = 2;
827 Opc = X86::XCHG16ar;
828 break;
829 case 3:
830 NopSize = 3;
831 Opc = X86::NOOPL;
832 break;
833 case 4:
834 NopSize = 4;
835 Opc = X86::NOOPL;
836 Displacement = 8;
837 break;
838 case 5:
839 NopSize = 5;
840 Opc = X86::NOOPL;
841 Displacement = 8;
842 IndexReg = X86::RAX;
843 break;
844 case 6:
845 NopSize = 6;
846 Opc = X86::NOOPW;
847 Displacement = 8;
848 IndexReg = X86::RAX;
849 break;
850 case 7:
851 NopSize = 7;
852 Opc = X86::NOOPL;
853 Displacement = 512;
854 break;
855 case 8:
856 NopSize = 8;
857 Opc = X86::NOOPL;
858 Displacement = 512;
859 IndexReg = X86::RAX;
860 break;
861 case 9:
862 NopSize = 9;
863 Opc = X86::NOOPW;
864 Displacement = 512;
865 IndexReg = X86::RAX;
866 break;
867 default:
868 NopSize = 10;
869 Opc = X86::NOOPW;
870 Displacement = 512;
871 IndexReg = X86::RAX;
872 SegmentReg = X86::CS;
873 break;
874 }
875
876 unsigned NumPrefixes = std::min(NumBytes - NopSize, 5U);
877 NopSize += NumPrefixes;
878 for (unsigned i = 0; i != NumPrefixes; ++i)
879 OS.EmitBytes("\x66");
880
881 switch (Opc) {
882 default: llvm_unreachable("Unexpected opcode");
883 case X86::NOOP:
884 OS.EmitInstruction(MCInstBuilder(Opc), STI);
885 break;
886 case X86::XCHG16ar:
887 OS.EmitInstruction(MCInstBuilder(Opc).addReg(X86::AX).addReg(X86::AX), STI);
888 break;
889 case X86::NOOPL:
890 case X86::NOOPW:
891 OS.EmitInstruction(MCInstBuilder(Opc)
892 .addReg(BaseReg)
893 .addImm(ScaleVal)
894 .addReg(IndexReg)
895 .addImm(Displacement)
896 .addReg(SegmentReg),
897 STI);
898 break;
899 }
900 assert(NopSize <= NumBytes && "We overemitted?");
901 return NopSize;
902 }
903
904 /// Emit the optimal amount of multi-byte nops on X86.
EmitNops(MCStreamer & OS,unsigned NumBytes,bool Is64Bit,const MCSubtargetInfo & STI)905 static void EmitNops(MCStreamer &OS, unsigned NumBytes, bool Is64Bit,
906 const MCSubtargetInfo &STI) {
907 unsigned NopsToEmit = NumBytes;
908 (void)NopsToEmit;
909 while (NumBytes) {
910 NumBytes -= EmitNop(OS, NumBytes, Is64Bit, STI);
911 assert(NopsToEmit >= NumBytes && "Emitted more than I asked for!");
912 }
913 }
914
LowerSTATEPOINT(const MachineInstr & MI,X86MCInstLower & MCIL)915 void X86AsmPrinter::LowerSTATEPOINT(const MachineInstr &MI,
916 X86MCInstLower &MCIL) {
917 assert(Subtarget->is64Bit() && "Statepoint currently only supports X86-64");
918
919 StatepointOpers SOpers(&MI);
920 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
921 EmitNops(*OutStreamer, PatchBytes, Subtarget->is64Bit(),
922 getSubtargetInfo());
923 } else {
924 // Lower call target and choose correct opcode
925 const MachineOperand &CallTarget = SOpers.getCallTarget();
926 MCOperand CallTargetMCOp;
927 unsigned CallOpcode;
928 switch (CallTarget.getType()) {
929 case MachineOperand::MO_GlobalAddress:
930 case MachineOperand::MO_ExternalSymbol:
931 CallTargetMCOp = MCIL.LowerSymbolOperand(
932 CallTarget, MCIL.GetSymbolFromOperand(CallTarget));
933 CallOpcode = X86::CALL64pcrel32;
934 // Currently, we only support relative addressing with statepoints.
935 // Otherwise, we'll need a scratch register to hold the target
936 // address. You'll fail asserts during load & relocation if this
937 // symbol is to far away. (TODO: support non-relative addressing)
938 break;
939 case MachineOperand::MO_Immediate:
940 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
941 CallOpcode = X86::CALL64pcrel32;
942 // Currently, we only support relative addressing with statepoints.
943 // Otherwise, we'll need a scratch register to hold the target
944 // immediate. You'll fail asserts during load & relocation if this
945 // address is to far away. (TODO: support non-relative addressing)
946 break;
947 case MachineOperand::MO_Register:
948 // FIXME: Add retpoline support and remove this.
949 if (Subtarget->useRetpoline())
950 report_fatal_error("Lowering register statepoints with retpoline not "
951 "yet implemented.");
952 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
953 CallOpcode = X86::CALL64r;
954 break;
955 default:
956 llvm_unreachable("Unsupported operand type in statepoint call target");
957 break;
958 }
959
960 // Emit call
961 MCInst CallInst;
962 CallInst.setOpcode(CallOpcode);
963 CallInst.addOperand(CallTargetMCOp);
964 OutStreamer->EmitInstruction(CallInst, getSubtargetInfo());
965 }
966
967 // Record our statepoint node in the same section used by STACKMAP
968 // and PATCHPOINT
969 SM.recordStatepoint(MI);
970 }
971
LowerFAULTING_OP(const MachineInstr & FaultingMI,X86MCInstLower & MCIL)972 void X86AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI,
973 X86MCInstLower &MCIL) {
974 // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
975 // <opcode>, <operands>
976
977 unsigned DefRegister = FaultingMI.getOperand(0).getReg();
978 FaultMaps::FaultKind FK =
979 static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
980 MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
981 unsigned Opcode = FaultingMI.getOperand(3).getImm();
982 unsigned OperandsBeginIdx = 4;
983
984 assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
985 FM.recordFaultingOp(FK, HandlerLabel);
986
987 MCInst MI;
988 MI.setOpcode(Opcode);
989
990 if (DefRegister != X86::NoRegister)
991 MI.addOperand(MCOperand::createReg(DefRegister));
992
993 for (auto I = FaultingMI.operands_begin() + OperandsBeginIdx,
994 E = FaultingMI.operands_end();
995 I != E; ++I)
996 if (auto MaybeOperand = MCIL.LowerMachineOperand(&FaultingMI, *I))
997 MI.addOperand(MaybeOperand.getValue());
998
999 OutStreamer->EmitInstruction(MI, getSubtargetInfo());
1000 }
1001
LowerFENTRY_CALL(const MachineInstr & MI,X86MCInstLower & MCIL)1002 void X86AsmPrinter::LowerFENTRY_CALL(const MachineInstr &MI,
1003 X86MCInstLower &MCIL) {
1004 bool Is64Bits = Subtarget->is64Bit();
1005 MCContext &Ctx = OutStreamer->getContext();
1006 MCSymbol *fentry = Ctx.getOrCreateSymbol("__fentry__");
1007 const MCSymbolRefExpr *Op =
1008 MCSymbolRefExpr::create(fentry, MCSymbolRefExpr::VK_None, Ctx);
1009
1010 EmitAndCountInstruction(
1011 MCInstBuilder(Is64Bits ? X86::CALL64pcrel32 : X86::CALLpcrel32)
1012 .addExpr(Op));
1013 }
1014
LowerPATCHABLE_OP(const MachineInstr & MI,X86MCInstLower & MCIL)1015 void X86AsmPrinter::LowerPATCHABLE_OP(const MachineInstr &MI,
1016 X86MCInstLower &MCIL) {
1017 // PATCHABLE_OP minsize, opcode, operands
1018
1019 unsigned MinSize = MI.getOperand(0).getImm();
1020 unsigned Opcode = MI.getOperand(1).getImm();
1021
1022 MCInst MCI;
1023 MCI.setOpcode(Opcode);
1024 for (auto &MO : make_range(MI.operands_begin() + 2, MI.operands_end()))
1025 if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1026 MCI.addOperand(MaybeOperand.getValue());
1027
1028 SmallString<256> Code;
1029 SmallVector<MCFixup, 4> Fixups;
1030 raw_svector_ostream VecOS(Code);
1031 CodeEmitter->encodeInstruction(MCI, VecOS, Fixups, getSubtargetInfo());
1032
1033 if (Code.size() < MinSize) {
1034 if (MinSize == 2 && Opcode == X86::PUSH64r) {
1035 // This is an optimization that lets us get away without emitting a nop in
1036 // many cases.
1037 //
1038 // NB! In some cases the encoding for PUSH64r (e.g. PUSH64r %r9) takes two
1039 // bytes too, so the check on MinSize is important.
1040 MCI.setOpcode(X86::PUSH64rmr);
1041 } else {
1042 unsigned NopSize = EmitNop(*OutStreamer, MinSize, Subtarget->is64Bit(),
1043 getSubtargetInfo());
1044 assert(NopSize == MinSize && "Could not implement MinSize!");
1045 (void)NopSize;
1046 }
1047 }
1048
1049 OutStreamer->EmitInstruction(MCI, getSubtargetInfo());
1050 }
1051
1052 // Lower a stackmap of the form:
1053 // <id>, <shadowBytes>, ...
LowerSTACKMAP(const MachineInstr & MI)1054 void X86AsmPrinter::LowerSTACKMAP(const MachineInstr &MI) {
1055 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1056 SM.recordStackMap(MI);
1057 unsigned NumShadowBytes = MI.getOperand(1).getImm();
1058 SMShadowTracker.reset(NumShadowBytes);
1059 }
1060
1061 // Lower a patchpoint of the form:
1062 // [<def>], <id>, <numBytes>, <target>, <numArgs>, <cc>, ...
LowerPATCHPOINT(const MachineInstr & MI,X86MCInstLower & MCIL)1063 void X86AsmPrinter::LowerPATCHPOINT(const MachineInstr &MI,
1064 X86MCInstLower &MCIL) {
1065 assert(Subtarget->is64Bit() && "Patchpoint currently only supports X86-64");
1066
1067 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
1068
1069 SM.recordPatchPoint(MI);
1070
1071 PatchPointOpers opers(&MI);
1072 unsigned ScratchIdx = opers.getNextScratchIdx();
1073 unsigned EncodedBytes = 0;
1074 const MachineOperand &CalleeMO = opers.getCallTarget();
1075
1076 // Check for null target. If target is non-null (i.e. is non-zero or is
1077 // symbolic) then emit a call.
1078 if (!(CalleeMO.isImm() && !CalleeMO.getImm())) {
1079 MCOperand CalleeMCOp;
1080 switch (CalleeMO.getType()) {
1081 default:
1082 /// FIXME: Add a verifier check for bad callee types.
1083 llvm_unreachable("Unrecognized callee operand type.");
1084 case MachineOperand::MO_Immediate:
1085 if (CalleeMO.getImm())
1086 CalleeMCOp = MCOperand::createImm(CalleeMO.getImm());
1087 break;
1088 case MachineOperand::MO_ExternalSymbol:
1089 case MachineOperand::MO_GlobalAddress:
1090 CalleeMCOp = MCIL.LowerSymbolOperand(CalleeMO,
1091 MCIL.GetSymbolFromOperand(CalleeMO));
1092 break;
1093 }
1094
1095 // Emit MOV to materialize the target address and the CALL to target.
1096 // This is encoded with 12-13 bytes, depending on which register is used.
1097 unsigned ScratchReg = MI.getOperand(ScratchIdx).getReg();
1098 if (X86II::isX86_64ExtendedReg(ScratchReg))
1099 EncodedBytes = 13;
1100 else
1101 EncodedBytes = 12;
1102
1103 EmitAndCountInstruction(
1104 MCInstBuilder(X86::MOV64ri).addReg(ScratchReg).addOperand(CalleeMCOp));
1105 // FIXME: Add retpoline support and remove this.
1106 if (Subtarget->useRetpoline())
1107 report_fatal_error(
1108 "Lowering patchpoint with retpoline not yet implemented.");
1109 EmitAndCountInstruction(MCInstBuilder(X86::CALL64r).addReg(ScratchReg));
1110 }
1111
1112 // Emit padding.
1113 unsigned NumBytes = opers.getNumPatchBytes();
1114 assert(NumBytes >= EncodedBytes &&
1115 "Patchpoint can't request size less than the length of a call.");
1116
1117 EmitNops(*OutStreamer, NumBytes - EncodedBytes, Subtarget->is64Bit(),
1118 getSubtargetInfo());
1119 }
1120
LowerPATCHABLE_EVENT_CALL(const MachineInstr & MI,X86MCInstLower & MCIL)1121 void X86AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
1122 X86MCInstLower &MCIL) {
1123 assert(Subtarget->is64Bit() && "XRay custom events only supports X86-64");
1124
1125 // We want to emit the following pattern, which follows the x86 calling
1126 // convention to prepare for the trampoline call to be patched in.
1127 //
1128 // .p2align 1, ...
1129 // .Lxray_event_sled_N:
1130 // jmp +N // jump across the instrumentation sled
1131 // ... // set up arguments in register
1132 // callq __xray_CustomEvent@plt // force dependency to symbol
1133 // ...
1134 // <jump here>
1135 //
1136 // After patching, it would look something like:
1137 //
1138 // nopw (2-byte nop)
1139 // ...
1140 // callq __xrayCustomEvent // already lowered
1141 // ...
1142 //
1143 // ---
1144 // First we emit the label and the jump.
1145 auto CurSled = OutContext.createTempSymbol("xray_event_sled_", true);
1146 OutStreamer->AddComment("# XRay Custom Event Log");
1147 OutStreamer->EmitCodeAlignment(2);
1148 OutStreamer->EmitLabel(CurSled);
1149
1150 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1151 // an operand (computed as an offset from the jmp instruction).
1152 // FIXME: Find another less hacky way do force the relative jump.
1153 OutStreamer->EmitBinaryData("\xeb\x0f");
1154
1155 // The default C calling convention will place two arguments into %rcx and
1156 // %rdx -- so we only work with those.
1157 unsigned DestRegs[] = {X86::RDI, X86::RSI};
1158 bool UsedMask[] = {false, false};
1159 // Filled out in loop.
1160 unsigned SrcRegs[] = {0, 0};
1161
1162 // Then we put the operands in the %rdi and %rsi registers. We spill the
1163 // values in the register before we clobber them, and mark them as used in
1164 // UsedMask. In case the arguments are already in the correct register, we use
1165 // emit nops appropriately sized to keep the sled the same size in every
1166 // situation.
1167 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1168 if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1169 assert(Op->isReg() && "Only support arguments in registers");
1170 SrcRegs[I] = Op->getReg();
1171 if (SrcRegs[I] != DestRegs[I]) {
1172 UsedMask[I] = true;
1173 EmitAndCountInstruction(
1174 MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1175 } else {
1176 EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1177 }
1178 }
1179
1180 // Now that the register values are stashed, mov arguments into place.
1181 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1182 if (SrcRegs[I] != DestRegs[I])
1183 EmitAndCountInstruction(
1184 MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1185
1186 // We emit a hard dependency on the __xray_CustomEvent symbol, which is the
1187 // name of the trampoline to be implemented by the XRay runtime.
1188 auto TSym = OutContext.getOrCreateSymbol("__xray_CustomEvent");
1189 MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1190 if (isPositionIndependent())
1191 TOp.setTargetFlags(X86II::MO_PLT);
1192
1193 // Emit the call instruction.
1194 EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1195 .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1196
1197 // Restore caller-saved and used registers.
1198 for (unsigned I = sizeof UsedMask; I-- > 0;)
1199 if (UsedMask[I])
1200 EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1201 else
1202 EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1203
1204 OutStreamer->AddComment("xray custom event end.");
1205
1206 // Record the sled version. Older versions of this sled were spelled
1207 // differently, so we let the runtime handle the different offsets we're
1208 // using.
1209 recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 1);
1210 }
1211
LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr & MI,X86MCInstLower & MCIL)1212 void X86AsmPrinter::LowerPATCHABLE_TYPED_EVENT_CALL(const MachineInstr &MI,
1213 X86MCInstLower &MCIL) {
1214 assert(Subtarget->is64Bit() && "XRay typed events only supports X86-64");
1215
1216 // We want to emit the following pattern, which follows the x86 calling
1217 // convention to prepare for the trampoline call to be patched in.
1218 //
1219 // .p2align 1, ...
1220 // .Lxray_event_sled_N:
1221 // jmp +N // jump across the instrumentation sled
1222 // ... // set up arguments in register
1223 // callq __xray_TypedEvent@plt // force dependency to symbol
1224 // ...
1225 // <jump here>
1226 //
1227 // After patching, it would look something like:
1228 //
1229 // nopw (2-byte nop)
1230 // ...
1231 // callq __xrayTypedEvent // already lowered
1232 // ...
1233 //
1234 // ---
1235 // First we emit the label and the jump.
1236 auto CurSled = OutContext.createTempSymbol("xray_typed_event_sled_", true);
1237 OutStreamer->AddComment("# XRay Typed Event Log");
1238 OutStreamer->EmitCodeAlignment(2);
1239 OutStreamer->EmitLabel(CurSled);
1240
1241 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1242 // an operand (computed as an offset from the jmp instruction).
1243 // FIXME: Find another less hacky way do force the relative jump.
1244 OutStreamer->EmitBinaryData("\xeb\x14");
1245
1246 // An x86-64 convention may place three arguments into %rcx, %rdx, and R8,
1247 // so we'll work with those. Or we may be called via SystemV, in which case
1248 // we don't have to do any translation.
1249 unsigned DestRegs[] = {X86::RDI, X86::RSI, X86::RDX};
1250 bool UsedMask[] = {false, false, false};
1251
1252 // Will fill out src regs in the loop.
1253 unsigned SrcRegs[] = {0, 0, 0};
1254
1255 // Then we put the operands in the SystemV registers. We spill the values in
1256 // the registers before we clobber them, and mark them as used in UsedMask.
1257 // In case the arguments are already in the correct register, we emit nops
1258 // appropriately sized to keep the sled the same size in every situation.
1259 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1260 if (auto Op = MCIL.LowerMachineOperand(&MI, MI.getOperand(I))) {
1261 // TODO: Is register only support adequate?
1262 assert(Op->isReg() && "Only supports arguments in registers");
1263 SrcRegs[I] = Op->getReg();
1264 if (SrcRegs[I] != DestRegs[I]) {
1265 UsedMask[I] = true;
1266 EmitAndCountInstruction(
1267 MCInstBuilder(X86::PUSH64r).addReg(DestRegs[I]));
1268 } else {
1269 EmitNops(*OutStreamer, 4, Subtarget->is64Bit(), getSubtargetInfo());
1270 }
1271 }
1272
1273 // In the above loop we only stash all of the destination registers or emit
1274 // nops if the arguments are already in the right place. Doing the actually
1275 // moving is postponed until after all the registers are stashed so nothing
1276 // is clobbers. We've already added nops to account for the size of mov and
1277 // push if the register is in the right place, so we only have to worry about
1278 // emitting movs.
1279 for (unsigned I = 0; I < MI.getNumOperands(); ++I)
1280 if (UsedMask[I])
1281 EmitAndCountInstruction(
1282 MCInstBuilder(X86::MOV64rr).addReg(DestRegs[I]).addReg(SrcRegs[I]));
1283
1284 // We emit a hard dependency on the __xray_TypedEvent symbol, which is the
1285 // name of the trampoline to be implemented by the XRay runtime.
1286 auto TSym = OutContext.getOrCreateSymbol("__xray_TypedEvent");
1287 MachineOperand TOp = MachineOperand::CreateMCSymbol(TSym);
1288 if (isPositionIndependent())
1289 TOp.setTargetFlags(X86II::MO_PLT);
1290
1291 // Emit the call instruction.
1292 EmitAndCountInstruction(MCInstBuilder(X86::CALL64pcrel32)
1293 .addOperand(MCIL.LowerSymbolOperand(TOp, TSym)));
1294
1295 // Restore caller-saved and used registers.
1296 for (unsigned I = sizeof UsedMask; I-- > 0;)
1297 if (UsedMask[I])
1298 EmitAndCountInstruction(MCInstBuilder(X86::POP64r).addReg(DestRegs[I]));
1299 else
1300 EmitNops(*OutStreamer, 1, Subtarget->is64Bit(), getSubtargetInfo());
1301
1302 OutStreamer->AddComment("xray typed event end.");
1303
1304 // Record the sled version.
1305 recordSled(CurSled, MI, SledKind::TYPED_EVENT, 0);
1306 }
1307
LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr & MI,X86MCInstLower & MCIL)1308 void X86AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI,
1309 X86MCInstLower &MCIL) {
1310 // We want to emit the following pattern:
1311 //
1312 // .p2align 1, ...
1313 // .Lxray_sled_N:
1314 // jmp .tmpN
1315 // # 9 bytes worth of noops
1316 //
1317 // We need the 9 bytes because at runtime, we'd be patching over the full 11
1318 // bytes with the following pattern:
1319 //
1320 // mov %r10, <function id, 32-bit> // 6 bytes
1321 // call <relative offset, 32-bits> // 5 bytes
1322 //
1323 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1324 OutStreamer->EmitCodeAlignment(2);
1325 OutStreamer->EmitLabel(CurSled);
1326
1327 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1328 // an operand (computed as an offset from the jmp instruction).
1329 // FIXME: Find another less hacky way do force the relative jump.
1330 OutStreamer->EmitBytes("\xeb\x09");
1331 EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1332 recordSled(CurSled, MI, SledKind::FUNCTION_ENTER);
1333 }
1334
LowerPATCHABLE_RET(const MachineInstr & MI,X86MCInstLower & MCIL)1335 void X86AsmPrinter::LowerPATCHABLE_RET(const MachineInstr &MI,
1336 X86MCInstLower &MCIL) {
1337 // Since PATCHABLE_RET takes the opcode of the return statement as an
1338 // argument, we use that to emit the correct form of the RET that we want.
1339 // i.e. when we see this:
1340 //
1341 // PATCHABLE_RET X86::RET ...
1342 //
1343 // We should emit the RET followed by sleds.
1344 //
1345 // .p2align 1, ...
1346 // .Lxray_sled_N:
1347 // ret # or equivalent instruction
1348 // # 10 bytes worth of noops
1349 //
1350 // This just makes sure that the alignment for the next instruction is 2.
1351 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1352 OutStreamer->EmitCodeAlignment(2);
1353 OutStreamer->EmitLabel(CurSled);
1354 unsigned OpCode = MI.getOperand(0).getImm();
1355 MCInst Ret;
1356 Ret.setOpcode(OpCode);
1357 for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1358 if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1359 Ret.addOperand(MaybeOperand.getValue());
1360 OutStreamer->EmitInstruction(Ret, getSubtargetInfo());
1361 EmitNops(*OutStreamer, 10, Subtarget->is64Bit(), getSubtargetInfo());
1362 recordSled(CurSled, MI, SledKind::FUNCTION_EXIT);
1363 }
1364
LowerPATCHABLE_TAIL_CALL(const MachineInstr & MI,X86MCInstLower & MCIL)1365 void X86AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI,
1366 X86MCInstLower &MCIL) {
1367 // Like PATCHABLE_RET, we have the actual instruction in the operands to this
1368 // instruction so we lower that particular instruction and its operands.
1369 // Unlike PATCHABLE_RET though, we put the sled before the JMP, much like how
1370 // we do it for PATCHABLE_FUNCTION_ENTER. The sled should be very similar to
1371 // the PATCHABLE_FUNCTION_ENTER case, followed by the lowering of the actual
1372 // tail call much like how we have it in PATCHABLE_RET.
1373 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1374 OutStreamer->EmitCodeAlignment(2);
1375 OutStreamer->EmitLabel(CurSled);
1376 auto Target = OutContext.createTempSymbol();
1377
1378 // Use a two-byte `jmp`. This version of JMP takes an 8-bit relative offset as
1379 // an operand (computed as an offset from the jmp instruction).
1380 // FIXME: Find another less hacky way do force the relative jump.
1381 OutStreamer->EmitBytes("\xeb\x09");
1382 EmitNops(*OutStreamer, 9, Subtarget->is64Bit(), getSubtargetInfo());
1383 OutStreamer->EmitLabel(Target);
1384 recordSled(CurSled, MI, SledKind::TAIL_CALL);
1385
1386 unsigned OpCode = MI.getOperand(0).getImm();
1387 MCInst TC;
1388 TC.setOpcode(OpCode);
1389
1390 // Before emitting the instruction, add a comment to indicate that this is
1391 // indeed a tail call.
1392 OutStreamer->AddComment("TAILCALL");
1393 for (auto &MO : make_range(MI.operands_begin() + 1, MI.operands_end()))
1394 if (auto MaybeOperand = MCIL.LowerMachineOperand(&MI, MO))
1395 TC.addOperand(MaybeOperand.getValue());
1396 OutStreamer->EmitInstruction(TC, getSubtargetInfo());
1397 }
1398
1399 // Returns instruction preceding MBBI in MachineFunction.
1400 // If MBBI is the first instruction of the first basic block, returns null.
1401 static MachineBasicBlock::const_iterator
PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI)1402 PrevCrossBBInst(MachineBasicBlock::const_iterator MBBI) {
1403 const MachineBasicBlock *MBB = MBBI->getParent();
1404 while (MBBI == MBB->begin()) {
1405 if (MBB == &MBB->getParent()->front())
1406 return MachineBasicBlock::const_iterator();
1407 MBB = MBB->getPrevNode();
1408 MBBI = MBB->end();
1409 }
1410 return --MBBI;
1411 }
1412
getConstantFromPool(const MachineInstr & MI,const MachineOperand & Op)1413 static const Constant *getConstantFromPool(const MachineInstr &MI,
1414 const MachineOperand &Op) {
1415 if (!Op.isCPI())
1416 return nullptr;
1417
1418 ArrayRef<MachineConstantPoolEntry> Constants =
1419 MI.getParent()->getParent()->getConstantPool()->getConstants();
1420 const MachineConstantPoolEntry &ConstantEntry = Constants[Op.getIndex()];
1421
1422 // Bail if this is a machine constant pool entry, we won't be able to dig out
1423 // anything useful.
1424 if (ConstantEntry.isMachineConstantPoolEntry())
1425 return nullptr;
1426
1427 auto *C = dyn_cast<Constant>(ConstantEntry.Val.ConstVal);
1428 assert((!C || ConstantEntry.getType() == C->getType()) &&
1429 "Expected a constant of the same type!");
1430 return C;
1431 }
1432
getShuffleComment(const MachineInstr * MI,unsigned SrcOp1Idx,unsigned SrcOp2Idx,ArrayRef<int> Mask)1433 static std::string getShuffleComment(const MachineInstr *MI, unsigned SrcOp1Idx,
1434 unsigned SrcOp2Idx, ArrayRef<int> Mask) {
1435 std::string Comment;
1436
1437 // Compute the name for a register. This is really goofy because we have
1438 // multiple instruction printers that could (in theory) use different
1439 // names. Fortunately most people use the ATT style (outside of Windows)
1440 // and they actually agree on register naming here. Ultimately, this is
1441 // a comment, and so its OK if it isn't perfect.
1442 auto GetRegisterName = [](unsigned RegNum) -> StringRef {
1443 return X86ATTInstPrinter::getRegisterName(RegNum);
1444 };
1445
1446 const MachineOperand &DstOp = MI->getOperand(0);
1447 const MachineOperand &SrcOp1 = MI->getOperand(SrcOp1Idx);
1448 const MachineOperand &SrcOp2 = MI->getOperand(SrcOp2Idx);
1449
1450 StringRef DstName = DstOp.isReg() ? GetRegisterName(DstOp.getReg()) : "mem";
1451 StringRef Src1Name =
1452 SrcOp1.isReg() ? GetRegisterName(SrcOp1.getReg()) : "mem";
1453 StringRef Src2Name =
1454 SrcOp2.isReg() ? GetRegisterName(SrcOp2.getReg()) : "mem";
1455
1456 // One source operand, fix the mask to print all elements in one span.
1457 SmallVector<int, 8> ShuffleMask(Mask.begin(), Mask.end());
1458 if (Src1Name == Src2Name)
1459 for (int i = 0, e = ShuffleMask.size(); i != e; ++i)
1460 if (ShuffleMask[i] >= e)
1461 ShuffleMask[i] -= e;
1462
1463 raw_string_ostream CS(Comment);
1464 CS << DstName;
1465
1466 // Handle AVX512 MASK/MASXZ write mask comments.
1467 // MASK: zmmX {%kY}
1468 // MASKZ: zmmX {%kY} {z}
1469 if (SrcOp1Idx > 1) {
1470 assert((SrcOp1Idx == 2 || SrcOp1Idx == 3) && "Unexpected writemask");
1471
1472 const MachineOperand &WriteMaskOp = MI->getOperand(SrcOp1Idx - 1);
1473 if (WriteMaskOp.isReg()) {
1474 CS << " {%" << GetRegisterName(WriteMaskOp.getReg()) << "}";
1475
1476 if (SrcOp1Idx == 2) {
1477 CS << " {z}";
1478 }
1479 }
1480 }
1481
1482 CS << " = ";
1483
1484 for (int i = 0, e = ShuffleMask.size(); i != e; ++i) {
1485 if (i != 0)
1486 CS << ",";
1487 if (ShuffleMask[i] == SM_SentinelZero) {
1488 CS << "zero";
1489 continue;
1490 }
1491
1492 // Otherwise, it must come from src1 or src2. Print the span of elements
1493 // that comes from this src.
1494 bool isSrc1 = ShuffleMask[i] < (int)e;
1495 CS << (isSrc1 ? Src1Name : Src2Name) << '[';
1496
1497 bool IsFirst = true;
1498 while (i != e && ShuffleMask[i] != SM_SentinelZero &&
1499 (ShuffleMask[i] < (int)e) == isSrc1) {
1500 if (!IsFirst)
1501 CS << ',';
1502 else
1503 IsFirst = false;
1504 if (ShuffleMask[i] == SM_SentinelUndef)
1505 CS << "u";
1506 else
1507 CS << ShuffleMask[i] % (int)e;
1508 ++i;
1509 }
1510 CS << ']';
1511 --i; // For loop increments element #.
1512 }
1513 CS.flush();
1514
1515 return Comment;
1516 }
1517
printConstant(const Constant * COp,raw_ostream & CS)1518 static void printConstant(const Constant *COp, raw_ostream &CS) {
1519 if (isa<UndefValue>(COp)) {
1520 CS << "u";
1521 } else if (auto *CI = dyn_cast<ConstantInt>(COp)) {
1522 if (CI->getBitWidth() <= 64) {
1523 CS << CI->getZExtValue();
1524 } else {
1525 // print multi-word constant as (w0,w1)
1526 const auto &Val = CI->getValue();
1527 CS << "(";
1528 for (int i = 0, N = Val.getNumWords(); i < N; ++i) {
1529 if (i > 0)
1530 CS << ",";
1531 CS << Val.getRawData()[i];
1532 }
1533 CS << ")";
1534 }
1535 } else if (auto *CF = dyn_cast<ConstantFP>(COp)) {
1536 SmallString<32> Str;
1537 CF->getValueAPF().toString(Str);
1538 CS << Str;
1539 } else {
1540 CS << "?";
1541 }
1542 }
1543
EmitSEHInstruction(const MachineInstr * MI)1544 void X86AsmPrinter::EmitSEHInstruction(const MachineInstr *MI) {
1545 assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1546 assert(getSubtarget().isOSWindows() && "SEH_ instruction Windows only");
1547 const X86RegisterInfo *RI =
1548 MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1549
1550 // Use the .cv_fpo directives if we're emitting CodeView on 32-bit x86.
1551 if (EmitFPOData) {
1552 X86TargetStreamer *XTS =
1553 static_cast<X86TargetStreamer *>(OutStreamer->getTargetStreamer());
1554 switch (MI->getOpcode()) {
1555 case X86::SEH_PushReg:
1556 XTS->emitFPOPushReg(MI->getOperand(0).getImm());
1557 break;
1558 case X86::SEH_StackAlloc:
1559 XTS->emitFPOStackAlloc(MI->getOperand(0).getImm());
1560 break;
1561 case X86::SEH_SetFrame:
1562 assert(MI->getOperand(1).getImm() == 0 &&
1563 ".cv_fpo_setframe takes no offset");
1564 XTS->emitFPOSetFrame(MI->getOperand(0).getImm());
1565 break;
1566 case X86::SEH_EndPrologue:
1567 XTS->emitFPOEndPrologue();
1568 break;
1569 case X86::SEH_SaveReg:
1570 case X86::SEH_SaveXMM:
1571 case X86::SEH_PushFrame:
1572 llvm_unreachable("SEH_ directive incompatible with FPO");
1573 break;
1574 default:
1575 llvm_unreachable("expected SEH_ instruction");
1576 }
1577 return;
1578 }
1579
1580 // Otherwise, use the .seh_ directives for all other Windows platforms.
1581 switch (MI->getOpcode()) {
1582 case X86::SEH_PushReg:
1583 OutStreamer->EmitWinCFIPushReg(
1584 RI->getSEHRegNum(MI->getOperand(0).getImm()));
1585 break;
1586
1587 case X86::SEH_SaveReg:
1588 OutStreamer->EmitWinCFISaveReg(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1589 MI->getOperand(1).getImm());
1590 break;
1591
1592 case X86::SEH_SaveXMM:
1593 OutStreamer->EmitWinCFISaveXMM(RI->getSEHRegNum(MI->getOperand(0).getImm()),
1594 MI->getOperand(1).getImm());
1595 break;
1596
1597 case X86::SEH_StackAlloc:
1598 OutStreamer->EmitWinCFIAllocStack(MI->getOperand(0).getImm());
1599 break;
1600
1601 case X86::SEH_SetFrame:
1602 OutStreamer->EmitWinCFISetFrame(
1603 RI->getSEHRegNum(MI->getOperand(0).getImm()),
1604 MI->getOperand(1).getImm());
1605 break;
1606
1607 case X86::SEH_PushFrame:
1608 OutStreamer->EmitWinCFIPushFrame(MI->getOperand(0).getImm());
1609 break;
1610
1611 case X86::SEH_EndPrologue:
1612 OutStreamer->EmitWinCFIEndProlog();
1613 break;
1614
1615 default:
1616 llvm_unreachable("expected SEH_ instruction");
1617 }
1618 }
1619
EmitInstruction(const MachineInstr * MI)1620 void X86AsmPrinter::EmitInstruction(const MachineInstr *MI) {
1621 X86MCInstLower MCInstLowering(*MF, *this);
1622 const X86RegisterInfo *RI =
1623 MF->getSubtarget<X86Subtarget>().getRegisterInfo();
1624
1625 // Add a comment about EVEX-2-VEX compression for AVX-512 instrs that
1626 // are compressed from EVEX encoding to VEX encoding.
1627 if (TM.Options.MCOptions.ShowMCEncoding) {
1628 if (MI->getAsmPrinterFlags() & X86::AC_EVEX_2_VEX)
1629 OutStreamer->AddComment("EVEX TO VEX Compression ", false);
1630 }
1631
1632 switch (MI->getOpcode()) {
1633 case TargetOpcode::DBG_VALUE:
1634 llvm_unreachable("Should be handled target independently");
1635
1636 // Emit nothing here but a comment if we can.
1637 case X86::Int_MemBarrier:
1638 OutStreamer->emitRawComment("MEMBARRIER");
1639 return;
1640
1641 case X86::EH_RETURN:
1642 case X86::EH_RETURN64: {
1643 // Lower these as normal, but add some comments.
1644 unsigned Reg = MI->getOperand(0).getReg();
1645 OutStreamer->AddComment(StringRef("eh_return, addr: %") +
1646 X86ATTInstPrinter::getRegisterName(Reg));
1647 break;
1648 }
1649 case X86::CLEANUPRET: {
1650 // Lower these as normal, but add some comments.
1651 OutStreamer->AddComment("CLEANUPRET");
1652 break;
1653 }
1654
1655 case X86::CATCHRET: {
1656 // Lower these as normal, but add some comments.
1657 OutStreamer->AddComment("CATCHRET");
1658 break;
1659 }
1660
1661 case X86::TAILJMPr:
1662 case X86::TAILJMPm:
1663 case X86::TAILJMPd:
1664 case X86::TAILJMPd_CC:
1665 case X86::TAILJMPr64:
1666 case X86::TAILJMPm64:
1667 case X86::TAILJMPd64:
1668 case X86::TAILJMPd64_CC:
1669 case X86::TAILJMPr64_REX:
1670 case X86::TAILJMPm64_REX:
1671 // Lower these as normal, but add some comments.
1672 OutStreamer->AddComment("TAILCALL");
1673 break;
1674
1675 case X86::TLS_addr32:
1676 case X86::TLS_addr64:
1677 case X86::TLS_base_addr32:
1678 case X86::TLS_base_addr64:
1679 return LowerTlsAddr(MCInstLowering, *MI);
1680
1681 case X86::MOVPC32r: {
1682 // This is a pseudo op for a two instruction sequence with a label, which
1683 // looks like:
1684 // call "L1$pb"
1685 // "L1$pb":
1686 // popl %esi
1687
1688 // Emit the call.
1689 MCSymbol *PICBase = MF->getPICBaseSymbol();
1690 // FIXME: We would like an efficient form for this, so we don't have to do a
1691 // lot of extra uniquing.
1692 EmitAndCountInstruction(
1693 MCInstBuilder(X86::CALLpcrel32)
1694 .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
1695
1696 const X86FrameLowering *FrameLowering =
1697 MF->getSubtarget<X86Subtarget>().getFrameLowering();
1698 bool hasFP = FrameLowering->hasFP(*MF);
1699
1700 // TODO: This is needed only if we require precise CFA.
1701 bool HasActiveDwarfFrame = OutStreamer->getNumFrameInfos() &&
1702 !OutStreamer->getDwarfFrameInfos().back().End;
1703
1704 int stackGrowth = -RI->getSlotSize();
1705
1706 if (HasActiveDwarfFrame && !hasFP) {
1707 OutStreamer->EmitCFIAdjustCfaOffset(-stackGrowth);
1708 }
1709
1710 // Emit the label.
1711 OutStreamer->EmitLabel(PICBase);
1712
1713 // popl $reg
1714 EmitAndCountInstruction(
1715 MCInstBuilder(X86::POP32r).addReg(MI->getOperand(0).getReg()));
1716
1717 if (HasActiveDwarfFrame && !hasFP) {
1718 OutStreamer->EmitCFIAdjustCfaOffset(stackGrowth);
1719 }
1720 return;
1721 }
1722
1723 case X86::MOVGOT64r: {
1724 // Materializes the GOT for the 64-bit large code model.
1725 MCSymbol *DotSym = OutContext.createTempSymbol();
1726 OutStreamer->EmitLabel(DotSym);
1727
1728 unsigned DstReg = MI->getOperand(0).getReg();
1729 unsigned ScratchReg = MI->getOperand(1).getReg();
1730 MCSymbol *GOTSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1731
1732 // .LtmpN: leaq .LtmpN(%rip), %dst
1733 const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1734 EmitAndCountInstruction(MCInstBuilder(X86::LEA64r)
1735 .addReg(DstReg) // dest
1736 .addReg(X86::RIP) // base
1737 .addImm(1) // scale
1738 .addReg(0) // index
1739 .addExpr(DotExpr) // disp
1740 .addReg(0)); // seg
1741
1742 // movq $_GLOBAL_OFFSET_TABLE_ - .LtmpN, %scratch
1743 const MCExpr *GOTSymExpr = MCSymbolRefExpr::create(GOTSym, OutContext);
1744 const MCExpr *GOTDiffExpr =
1745 MCBinaryExpr::createSub(GOTSymExpr, DotExpr, OutContext);
1746 EmitAndCountInstruction(MCInstBuilder(X86::MOV64ri)
1747 .addReg(ScratchReg) // dest
1748 .addExpr(GOTDiffExpr)); // disp
1749
1750 // addq %scratch, %dst
1751 EmitAndCountInstruction(MCInstBuilder(X86::ADD64rr)
1752 .addReg(DstReg) // dest
1753 .addReg(DstReg) // dest
1754 .addReg(ScratchReg)); // src
1755 return;
1756 }
1757
1758 case X86::ADD32ri: {
1759 // Lower the MO_GOT_ABSOLUTE_ADDRESS form of ADD32ri.
1760 if (MI->getOperand(2).getTargetFlags() != X86II::MO_GOT_ABSOLUTE_ADDRESS)
1761 break;
1762
1763 // Okay, we have something like:
1764 // EAX = ADD32ri EAX, MO_GOT_ABSOLUTE_ADDRESS(@MYGLOBAL)
1765
1766 // For this, we want to print something like:
1767 // MYGLOBAL + (. - PICBASE)
1768 // However, we can't generate a ".", so just emit a new label here and refer
1769 // to it.
1770 MCSymbol *DotSym = OutContext.createTempSymbol();
1771 OutStreamer->EmitLabel(DotSym);
1772
1773 // Now that we have emitted the label, lower the complex operand expression.
1774 MCSymbol *OpSym = MCInstLowering.GetSymbolFromOperand(MI->getOperand(2));
1775
1776 const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1777 const MCExpr *PICBase =
1778 MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
1779 DotExpr = MCBinaryExpr::createSub(DotExpr, PICBase, OutContext);
1780
1781 DotExpr = MCBinaryExpr::createAdd(
1782 MCSymbolRefExpr::create(OpSym, OutContext), DotExpr, OutContext);
1783
1784 EmitAndCountInstruction(MCInstBuilder(X86::ADD32ri)
1785 .addReg(MI->getOperand(0).getReg())
1786 .addReg(MI->getOperand(1).getReg())
1787 .addExpr(DotExpr));
1788 return;
1789 }
1790 case TargetOpcode::STATEPOINT:
1791 return LowerSTATEPOINT(*MI, MCInstLowering);
1792
1793 case TargetOpcode::FAULTING_OP:
1794 return LowerFAULTING_OP(*MI, MCInstLowering);
1795
1796 case TargetOpcode::FENTRY_CALL:
1797 return LowerFENTRY_CALL(*MI, MCInstLowering);
1798
1799 case TargetOpcode::PATCHABLE_OP:
1800 return LowerPATCHABLE_OP(*MI, MCInstLowering);
1801
1802 case TargetOpcode::STACKMAP:
1803 return LowerSTACKMAP(*MI);
1804
1805 case TargetOpcode::PATCHPOINT:
1806 return LowerPATCHPOINT(*MI, MCInstLowering);
1807
1808 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
1809 return LowerPATCHABLE_FUNCTION_ENTER(*MI, MCInstLowering);
1810
1811 case TargetOpcode::PATCHABLE_RET:
1812 return LowerPATCHABLE_RET(*MI, MCInstLowering);
1813
1814 case TargetOpcode::PATCHABLE_TAIL_CALL:
1815 return LowerPATCHABLE_TAIL_CALL(*MI, MCInstLowering);
1816
1817 case TargetOpcode::PATCHABLE_EVENT_CALL:
1818 return LowerPATCHABLE_EVENT_CALL(*MI, MCInstLowering);
1819
1820 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
1821 return LowerPATCHABLE_TYPED_EVENT_CALL(*MI, MCInstLowering);
1822
1823 case X86::MORESTACK_RET:
1824 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1825 return;
1826
1827 case X86::MORESTACK_RET_RESTORE_R10:
1828 // Return, then restore R10.
1829 EmitAndCountInstruction(MCInstBuilder(getRetOpcode(*Subtarget)));
1830 EmitAndCountInstruction(
1831 MCInstBuilder(X86::MOV64rr).addReg(X86::R10).addReg(X86::RAX));
1832 return;
1833
1834 case X86::SEH_PushReg:
1835 case X86::SEH_SaveReg:
1836 case X86::SEH_SaveXMM:
1837 case X86::SEH_StackAlloc:
1838 case X86::SEH_SetFrame:
1839 case X86::SEH_PushFrame:
1840 case X86::SEH_EndPrologue:
1841 EmitSEHInstruction(MI);
1842 return;
1843
1844 case X86::SEH_Epilogue: {
1845 assert(MF->hasWinCFI() && "SEH_ instruction in function without WinCFI?");
1846 MachineBasicBlock::const_iterator MBBI(MI);
1847 // Check if preceded by a call and emit nop if so.
1848 for (MBBI = PrevCrossBBInst(MBBI);
1849 MBBI != MachineBasicBlock::const_iterator();
1850 MBBI = PrevCrossBBInst(MBBI)) {
1851 // Conservatively assume that pseudo instructions don't emit code and keep
1852 // looking for a call. We may emit an unnecessary nop in some cases.
1853 if (!MBBI->isPseudo()) {
1854 if (MBBI->isCall())
1855 EmitAndCountInstruction(MCInstBuilder(X86::NOOP));
1856 break;
1857 }
1858 }
1859 return;
1860 }
1861
1862 // Lower PSHUFB and VPERMILP normally but add a comment if we can find
1863 // a constant shuffle mask. We won't be able to do this at the MC layer
1864 // because the mask isn't an immediate.
1865 case X86::PSHUFBrm:
1866 case X86::VPSHUFBrm:
1867 case X86::VPSHUFBYrm:
1868 case X86::VPSHUFBZ128rm:
1869 case X86::VPSHUFBZ128rmk:
1870 case X86::VPSHUFBZ128rmkz:
1871 case X86::VPSHUFBZ256rm:
1872 case X86::VPSHUFBZ256rmk:
1873 case X86::VPSHUFBZ256rmkz:
1874 case X86::VPSHUFBZrm:
1875 case X86::VPSHUFBZrmk:
1876 case X86::VPSHUFBZrmkz: {
1877 if (!OutStreamer->isVerboseAsm())
1878 break;
1879 unsigned SrcIdx, MaskIdx;
1880 switch (MI->getOpcode()) {
1881 default: llvm_unreachable("Invalid opcode");
1882 case X86::PSHUFBrm:
1883 case X86::VPSHUFBrm:
1884 case X86::VPSHUFBYrm:
1885 case X86::VPSHUFBZ128rm:
1886 case X86::VPSHUFBZ256rm:
1887 case X86::VPSHUFBZrm:
1888 SrcIdx = 1; MaskIdx = 5; break;
1889 case X86::VPSHUFBZ128rmkz:
1890 case X86::VPSHUFBZ256rmkz:
1891 case X86::VPSHUFBZrmkz:
1892 SrcIdx = 2; MaskIdx = 6; break;
1893 case X86::VPSHUFBZ128rmk:
1894 case X86::VPSHUFBZ256rmk:
1895 case X86::VPSHUFBZrmk:
1896 SrcIdx = 3; MaskIdx = 7; break;
1897 }
1898
1899 assert(MI->getNumOperands() >= 6 &&
1900 "We should always have at least 6 operands!");
1901
1902 const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1903 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1904 SmallVector<int, 64> Mask;
1905 DecodePSHUFBMask(C, Mask);
1906 if (!Mask.empty())
1907 OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask),
1908 !EnablePrintSchedInfo);
1909 }
1910 break;
1911 }
1912
1913 case X86::VPERMILPSrm:
1914 case X86::VPERMILPSYrm:
1915 case X86::VPERMILPSZ128rm:
1916 case X86::VPERMILPSZ128rmk:
1917 case X86::VPERMILPSZ128rmkz:
1918 case X86::VPERMILPSZ256rm:
1919 case X86::VPERMILPSZ256rmk:
1920 case X86::VPERMILPSZ256rmkz:
1921 case X86::VPERMILPSZrm:
1922 case X86::VPERMILPSZrmk:
1923 case X86::VPERMILPSZrmkz:
1924 case X86::VPERMILPDrm:
1925 case X86::VPERMILPDYrm:
1926 case X86::VPERMILPDZ128rm:
1927 case X86::VPERMILPDZ128rmk:
1928 case X86::VPERMILPDZ128rmkz:
1929 case X86::VPERMILPDZ256rm:
1930 case X86::VPERMILPDZ256rmk:
1931 case X86::VPERMILPDZ256rmkz:
1932 case X86::VPERMILPDZrm:
1933 case X86::VPERMILPDZrmk:
1934 case X86::VPERMILPDZrmkz: {
1935 if (!OutStreamer->isVerboseAsm())
1936 break;
1937 unsigned SrcIdx, MaskIdx;
1938 unsigned ElSize;
1939 switch (MI->getOpcode()) {
1940 default: llvm_unreachable("Invalid opcode");
1941 case X86::VPERMILPSrm:
1942 case X86::VPERMILPSYrm:
1943 case X86::VPERMILPSZ128rm:
1944 case X86::VPERMILPSZ256rm:
1945 case X86::VPERMILPSZrm:
1946 SrcIdx = 1; MaskIdx = 5; ElSize = 32; break;
1947 case X86::VPERMILPSZ128rmkz:
1948 case X86::VPERMILPSZ256rmkz:
1949 case X86::VPERMILPSZrmkz:
1950 SrcIdx = 2; MaskIdx = 6; ElSize = 32; break;
1951 case X86::VPERMILPSZ128rmk:
1952 case X86::VPERMILPSZ256rmk:
1953 case X86::VPERMILPSZrmk:
1954 SrcIdx = 3; MaskIdx = 7; ElSize = 32; break;
1955 case X86::VPERMILPDrm:
1956 case X86::VPERMILPDYrm:
1957 case X86::VPERMILPDZ128rm:
1958 case X86::VPERMILPDZ256rm:
1959 case X86::VPERMILPDZrm:
1960 SrcIdx = 1; MaskIdx = 5; ElSize = 64; break;
1961 case X86::VPERMILPDZ128rmkz:
1962 case X86::VPERMILPDZ256rmkz:
1963 case X86::VPERMILPDZrmkz:
1964 SrcIdx = 2; MaskIdx = 6; ElSize = 64; break;
1965 case X86::VPERMILPDZ128rmk:
1966 case X86::VPERMILPDZ256rmk:
1967 case X86::VPERMILPDZrmk:
1968 SrcIdx = 3; MaskIdx = 7; ElSize = 64; break;
1969 }
1970
1971 assert(MI->getNumOperands() >= 6 &&
1972 "We should always have at least 6 operands!");
1973
1974 const MachineOperand &MaskOp = MI->getOperand(MaskIdx);
1975 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
1976 SmallVector<int, 16> Mask;
1977 DecodeVPERMILPMask(C, ElSize, Mask);
1978 if (!Mask.empty())
1979 OutStreamer->AddComment(getShuffleComment(MI, SrcIdx, SrcIdx, Mask),
1980 !EnablePrintSchedInfo);
1981 }
1982 break;
1983 }
1984
1985 case X86::VPERMIL2PDrm:
1986 case X86::VPERMIL2PSrm:
1987 case X86::VPERMIL2PDYrm:
1988 case X86::VPERMIL2PSYrm: {
1989 if (!OutStreamer->isVerboseAsm())
1990 break;
1991 assert(MI->getNumOperands() >= 8 &&
1992 "We should always have at least 8 operands!");
1993
1994 const MachineOperand &CtrlOp = MI->getOperand(MI->getNumOperands() - 1);
1995 if (!CtrlOp.isImm())
1996 break;
1997
1998 unsigned ElSize;
1999 switch (MI->getOpcode()) {
2000 default: llvm_unreachable("Invalid opcode");
2001 case X86::VPERMIL2PSrm: case X86::VPERMIL2PSYrm: ElSize = 32; break;
2002 case X86::VPERMIL2PDrm: case X86::VPERMIL2PDYrm: ElSize = 64; break;
2003 }
2004
2005 const MachineOperand &MaskOp = MI->getOperand(6);
2006 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2007 SmallVector<int, 16> Mask;
2008 DecodeVPERMIL2PMask(C, (unsigned)CtrlOp.getImm(), ElSize, Mask);
2009 if (!Mask.empty())
2010 OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask),
2011 !EnablePrintSchedInfo);
2012 }
2013 break;
2014 }
2015
2016 case X86::VPPERMrrm: {
2017 if (!OutStreamer->isVerboseAsm())
2018 break;
2019 assert(MI->getNumOperands() >= 7 &&
2020 "We should always have at least 7 operands!");
2021
2022 const MachineOperand &MaskOp = MI->getOperand(6);
2023 if (auto *C = getConstantFromPool(*MI, MaskOp)) {
2024 SmallVector<int, 16> Mask;
2025 DecodeVPPERMMask(C, Mask);
2026 if (!Mask.empty())
2027 OutStreamer->AddComment(getShuffleComment(MI, 1, 2, Mask),
2028 !EnablePrintSchedInfo);
2029 }
2030 break;
2031 }
2032
2033 case X86::MMX_MOVQ64rm: {
2034 if (!OutStreamer->isVerboseAsm())
2035 break;
2036 if (MI->getNumOperands() <= 4)
2037 break;
2038 if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2039 std::string Comment;
2040 raw_string_ostream CS(Comment);
2041 const MachineOperand &DstOp = MI->getOperand(0);
2042 CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2043 if (auto *CF = dyn_cast<ConstantFP>(C)) {
2044 CS << "0x" << CF->getValueAPF().bitcastToAPInt().toString(16, false);
2045 OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
2046 }
2047 }
2048 break;
2049 }
2050
2051 #define MOV_CASE(Prefix, Suffix) \
2052 case X86::Prefix##MOVAPD##Suffix##rm: \
2053 case X86::Prefix##MOVAPS##Suffix##rm: \
2054 case X86::Prefix##MOVUPD##Suffix##rm: \
2055 case X86::Prefix##MOVUPS##Suffix##rm: \
2056 case X86::Prefix##MOVDQA##Suffix##rm: \
2057 case X86::Prefix##MOVDQU##Suffix##rm:
2058
2059 #define MOV_AVX512_CASE(Suffix) \
2060 case X86::VMOVDQA64##Suffix##rm: \
2061 case X86::VMOVDQA32##Suffix##rm: \
2062 case X86::VMOVDQU64##Suffix##rm: \
2063 case X86::VMOVDQU32##Suffix##rm: \
2064 case X86::VMOVDQU16##Suffix##rm: \
2065 case X86::VMOVDQU8##Suffix##rm: \
2066 case X86::VMOVAPS##Suffix##rm: \
2067 case X86::VMOVAPD##Suffix##rm: \
2068 case X86::VMOVUPS##Suffix##rm: \
2069 case X86::VMOVUPD##Suffix##rm:
2070
2071 #define CASE_ALL_MOV_RM() \
2072 MOV_CASE(, ) /* SSE */ \
2073 MOV_CASE(V, ) /* AVX-128 */ \
2074 MOV_CASE(V, Y) /* AVX-256 */ \
2075 MOV_AVX512_CASE(Z) \
2076 MOV_AVX512_CASE(Z256) \
2077 MOV_AVX512_CASE(Z128)
2078
2079 // For loads from a constant pool to a vector register, print the constant
2080 // loaded.
2081 CASE_ALL_MOV_RM()
2082 case X86::VBROADCASTF128:
2083 case X86::VBROADCASTI128:
2084 case X86::VBROADCASTF32X4Z256rm:
2085 case X86::VBROADCASTF32X4rm:
2086 case X86::VBROADCASTF32X8rm:
2087 case X86::VBROADCASTF64X2Z128rm:
2088 case X86::VBROADCASTF64X2rm:
2089 case X86::VBROADCASTF64X4rm:
2090 case X86::VBROADCASTI32X4Z256rm:
2091 case X86::VBROADCASTI32X4rm:
2092 case X86::VBROADCASTI32X8rm:
2093 case X86::VBROADCASTI64X2Z128rm:
2094 case X86::VBROADCASTI64X2rm:
2095 case X86::VBROADCASTI64X4rm:
2096 if (!OutStreamer->isVerboseAsm())
2097 break;
2098 if (MI->getNumOperands() <= 4)
2099 break;
2100 if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2101 int NumLanes = 1;
2102 // Override NumLanes for the broadcast instructions.
2103 switch (MI->getOpcode()) {
2104 case X86::VBROADCASTF128: NumLanes = 2; break;
2105 case X86::VBROADCASTI128: NumLanes = 2; break;
2106 case X86::VBROADCASTF32X4Z256rm: NumLanes = 2; break;
2107 case X86::VBROADCASTF32X4rm: NumLanes = 4; break;
2108 case X86::VBROADCASTF32X8rm: NumLanes = 2; break;
2109 case X86::VBROADCASTF64X2Z128rm: NumLanes = 2; break;
2110 case X86::VBROADCASTF64X2rm: NumLanes = 4; break;
2111 case X86::VBROADCASTF64X4rm: NumLanes = 2; break;
2112 case X86::VBROADCASTI32X4Z256rm: NumLanes = 2; break;
2113 case X86::VBROADCASTI32X4rm: NumLanes = 4; break;
2114 case X86::VBROADCASTI32X8rm: NumLanes = 2; break;
2115 case X86::VBROADCASTI64X2Z128rm: NumLanes = 2; break;
2116 case X86::VBROADCASTI64X2rm: NumLanes = 4; break;
2117 case X86::VBROADCASTI64X4rm: NumLanes = 2; break;
2118 }
2119
2120 std::string Comment;
2121 raw_string_ostream CS(Comment);
2122 const MachineOperand &DstOp = MI->getOperand(0);
2123 CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2124 if (auto *CDS = dyn_cast<ConstantDataSequential>(C)) {
2125 CS << "[";
2126 for (int l = 0; l != NumLanes; ++l) {
2127 for (int i = 0, NumElements = CDS->getNumElements(); i < NumElements;
2128 ++i) {
2129 if (i != 0 || l != 0)
2130 CS << ",";
2131 if (CDS->getElementType()->isIntegerTy())
2132 CS << CDS->getElementAsInteger(i);
2133 else if (CDS->getElementType()->isFloatTy())
2134 CS << CDS->getElementAsFloat(i);
2135 else if (CDS->getElementType()->isDoubleTy())
2136 CS << CDS->getElementAsDouble(i);
2137 else
2138 CS << "?";
2139 }
2140 }
2141 CS << "]";
2142 OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
2143 } else if (auto *CV = dyn_cast<ConstantVector>(C)) {
2144 CS << "<";
2145 for (int l = 0; l != NumLanes; ++l) {
2146 for (int i = 0, NumOperands = CV->getNumOperands(); i < NumOperands;
2147 ++i) {
2148 if (i != 0 || l != 0)
2149 CS << ",";
2150 printConstant(CV->getOperand(i), CS);
2151 }
2152 }
2153 CS << ">";
2154 OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
2155 }
2156 }
2157 break;
2158 case X86::VBROADCASTSSrm:
2159 case X86::VBROADCASTSSYrm:
2160 case X86::VBROADCASTSSZ128m:
2161 case X86::VBROADCASTSSZ256m:
2162 case X86::VBROADCASTSSZm:
2163 case X86::VBROADCASTSDYrm:
2164 case X86::VBROADCASTSDZ256m:
2165 case X86::VBROADCASTSDZm:
2166 case X86::VPBROADCASTBrm:
2167 case X86::VPBROADCASTBYrm:
2168 case X86::VPBROADCASTBZ128m:
2169 case X86::VPBROADCASTBZ256m:
2170 case X86::VPBROADCASTBZm:
2171 case X86::VPBROADCASTDrm:
2172 case X86::VPBROADCASTDYrm:
2173 case X86::VPBROADCASTDZ128m:
2174 case X86::VPBROADCASTDZ256m:
2175 case X86::VPBROADCASTDZm:
2176 case X86::VPBROADCASTQrm:
2177 case X86::VPBROADCASTQYrm:
2178 case X86::VPBROADCASTQZ128m:
2179 case X86::VPBROADCASTQZ256m:
2180 case X86::VPBROADCASTQZm:
2181 case X86::VPBROADCASTWrm:
2182 case X86::VPBROADCASTWYrm:
2183 case X86::VPBROADCASTWZ128m:
2184 case X86::VPBROADCASTWZ256m:
2185 case X86::VPBROADCASTWZm:
2186 if (!OutStreamer->isVerboseAsm())
2187 break;
2188 if (MI->getNumOperands() <= 4)
2189 break;
2190 if (auto *C = getConstantFromPool(*MI, MI->getOperand(4))) {
2191 int NumElts;
2192 switch (MI->getOpcode()) {
2193 default: llvm_unreachable("Invalid opcode");
2194 case X86::VBROADCASTSSrm: NumElts = 4; break;
2195 case X86::VBROADCASTSSYrm: NumElts = 8; break;
2196 case X86::VBROADCASTSSZ128m: NumElts = 4; break;
2197 case X86::VBROADCASTSSZ256m: NumElts = 8; break;
2198 case X86::VBROADCASTSSZm: NumElts = 16; break;
2199 case X86::VBROADCASTSDYrm: NumElts = 4; break;
2200 case X86::VBROADCASTSDZ256m: NumElts = 4; break;
2201 case X86::VBROADCASTSDZm: NumElts = 8; break;
2202 case X86::VPBROADCASTBrm: NumElts = 16; break;
2203 case X86::VPBROADCASTBYrm: NumElts = 32; break;
2204 case X86::VPBROADCASTBZ128m: NumElts = 16; break;
2205 case X86::VPBROADCASTBZ256m: NumElts = 32; break;
2206 case X86::VPBROADCASTBZm: NumElts = 64; break;
2207 case X86::VPBROADCASTDrm: NumElts = 4; break;
2208 case X86::VPBROADCASTDYrm: NumElts = 8; break;
2209 case X86::VPBROADCASTDZ128m: NumElts = 4; break;
2210 case X86::VPBROADCASTDZ256m: NumElts = 8; break;
2211 case X86::VPBROADCASTDZm: NumElts = 16; break;
2212 case X86::VPBROADCASTQrm: NumElts = 2; break;
2213 case X86::VPBROADCASTQYrm: NumElts = 4; break;
2214 case X86::VPBROADCASTQZ128m: NumElts = 2; break;
2215 case X86::VPBROADCASTQZ256m: NumElts = 4; break;
2216 case X86::VPBROADCASTQZm: NumElts = 8; break;
2217 case X86::VPBROADCASTWrm: NumElts = 8; break;
2218 case X86::VPBROADCASTWYrm: NumElts = 16; break;
2219 case X86::VPBROADCASTWZ128m: NumElts = 8; break;
2220 case X86::VPBROADCASTWZ256m: NumElts = 16; break;
2221 case X86::VPBROADCASTWZm: NumElts = 32; break;
2222 }
2223
2224 std::string Comment;
2225 raw_string_ostream CS(Comment);
2226 const MachineOperand &DstOp = MI->getOperand(0);
2227 CS << X86ATTInstPrinter::getRegisterName(DstOp.getReg()) << " = ";
2228 CS << "[";
2229 for (int i = 0; i != NumElts; ++i) {
2230 if (i != 0)
2231 CS << ",";
2232 printConstant(C, CS);
2233 }
2234 CS << "]";
2235 OutStreamer->AddComment(CS.str(), !EnablePrintSchedInfo);
2236 }
2237 }
2238
2239 MCInst TmpInst;
2240 MCInstLowering.Lower(MI, TmpInst);
2241 if (MI->getAsmPrinterFlag(MachineInstr::NoSchedComment))
2242 TmpInst.setFlags(TmpInst.getFlags() | X86::NO_SCHED_INFO);
2243
2244 // Stackmap shadows cannot include branch targets, so we can count the bytes
2245 // in a call towards the shadow, but must ensure that the no thread returns
2246 // in to the stackmap shadow. The only way to achieve this is if the call
2247 // is at the end of the shadow.
2248 if (MI->isCall()) {
2249 // Count then size of the call towards the shadow
2250 SMShadowTracker.count(TmpInst, getSubtargetInfo(), CodeEmitter.get());
2251 // Then flush the shadow so that we fill with nops before the call, not
2252 // after it.
2253 SMShadowTracker.emitShadowPadding(*OutStreamer, getSubtargetInfo());
2254 // Then emit the call
2255 OutStreamer->EmitInstruction(TmpInst, getSubtargetInfo());
2256 return;
2257 }
2258
2259 EmitAndCountInstruction(TmpInst);
2260 }
2261