]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/Mips/MipsAsmPrinter.cpp
Merge llvm, clang, compiler-rt, libc++, lld and lldb release_40 branch
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / Mips / MipsAsmPrinter.cpp
1 //===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===//
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 a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MCTargetDesc/MipsMCNaCl.h"
18 #include "Mips.h"
19 #include "MipsAsmPrinter.h"
20 #include "MipsInstrInfo.h"
21 #include "MipsMCInstLower.h"
22 #include "MipsTargetMachine.h"
23 #include "MipsTargetStreamer.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCELFStreamer.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCInst.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSymbolELF.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <string>
51
52 using namespace llvm;
53
54 #define DEBUG_TYPE "mips-asm-printer"
55
56 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
57   return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
58 }
59
60 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
61   Subtarget = &MF.getSubtarget<MipsSubtarget>();
62
63   MipsFI = MF.getInfo<MipsFunctionInfo>();
64   if (Subtarget->inMips16Mode())
65     for (std::map<
66              const char *,
67              const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
68              it = MipsFI->StubsNeeded.begin();
69          it != MipsFI->StubsNeeded.end(); ++it) {
70       const char *Symbol = it->first;
71       const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
72       if (StubsNeeded.find(Symbol) == StubsNeeded.end())
73         StubsNeeded[Symbol] = Signature;
74     }
75   MCP = MF.getConstantPool();
76
77   // In NaCl, all indirect jump targets must be aligned to bundle size.
78   if (Subtarget->isTargetNaCl())
79     NaClAlignIndirectJumpTargets(MF);
80
81   AsmPrinter::runOnMachineFunction(MF);
82   return true;
83 }
84
85 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
86   MCOp = MCInstLowering.LowerOperand(MO);
87   return MCOp.isValid();
88 }
89
90 #include "MipsGenMCPseudoLowering.inc"
91
92 // Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM,
93 // JALR, or JALR64 as appropriate for the target
94 void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer,
95                                               const MachineInstr *MI) {
96   bool HasLinkReg = false;
97   bool InMicroMipsMode = Subtarget->inMicroMipsMode();
98   MCInst TmpInst0;
99
100   if (Subtarget->hasMips64r6()) {
101     // MIPS64r6 should use (JALR64 ZERO_64, $rs)
102     TmpInst0.setOpcode(Mips::JALR64);
103     HasLinkReg = true;
104   } else if (Subtarget->hasMips32r6()) {
105     // MIPS32r6 should use (JALR ZERO, $rs)
106     if (InMicroMipsMode)
107       TmpInst0.setOpcode(Mips::JRC16_MMR6);
108     else {
109       TmpInst0.setOpcode(Mips::JALR);
110       HasLinkReg = true;
111     }
112   } else if (Subtarget->inMicroMipsMode())
113     // microMIPS should use (JR_MM $rs)
114     TmpInst0.setOpcode(Mips::JR_MM);
115   else {
116     // Everything else should use (JR $rs)
117     TmpInst0.setOpcode(Mips::JR);
118   }
119
120   MCOperand MCOp;
121
122   if (HasLinkReg) {
123     unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
124     TmpInst0.addOperand(MCOperand::createReg(ZeroReg));
125   }
126
127   lowerOperand(MI->getOperand(0), MCOp);
128   TmpInst0.addOperand(MCOp);
129
130   EmitToStreamer(OutStreamer, TmpInst0);
131 }
132
133 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
134   MipsTargetStreamer &TS = getTargetStreamer();
135   TS.forbidModuleDirective();
136
137   if (MI->isDebugValue()) {
138     SmallString<128> Str;
139     raw_svector_ostream OS(Str);
140
141     PrintDebugValueComment(MI, OS);
142     return;
143   }
144
145   // If we just ended a constant pool, mark it as such.
146   if (InConstantPool && MI->getOpcode() != Mips::CONSTPOOL_ENTRY) {
147     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
148     InConstantPool = false;
149   }
150   if (MI->getOpcode() == Mips::CONSTPOOL_ENTRY) {
151     // CONSTPOOL_ENTRY - This instruction represents a floating
152     //constant pool in the function.  The first operand is the ID#
153     // for this instruction, the second is the index into the
154     // MachineConstantPool that this is, the third is the size in
155     // bytes of this constant pool entry.
156     // The required alignment is specified on the basic block holding this MI.
157     //
158     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
159     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
160
161     // If this is the first entry of the pool, mark it.
162     if (!InConstantPool) {
163       OutStreamer->EmitDataRegion(MCDR_DataRegion);
164       InConstantPool = true;
165     }
166
167     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
168
169     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
170     if (MCPE.isMachineConstantPoolEntry())
171       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
172     else
173       EmitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal);
174     return;
175   }
176
177
178   MachineBasicBlock::const_instr_iterator I = MI->getIterator();
179   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
180
181   do {
182     // Do any auto-generated pseudo lowerings.
183     if (emitPseudoExpansionLowering(*OutStreamer, &*I))
184       continue;
185
186     if (I->getOpcode() == Mips::PseudoReturn ||
187         I->getOpcode() == Mips::PseudoReturn64 ||
188         I->getOpcode() == Mips::PseudoIndirectBranch ||
189         I->getOpcode() == Mips::PseudoIndirectBranch64 ||
190         I->getOpcode() == Mips::TAILCALLREG ||
191         I->getOpcode() == Mips::TAILCALLREG64) {
192       emitPseudoIndirectBranch(*OutStreamer, &*I);
193       continue;
194     }
195
196     // The inMips16Mode() test is not permanent.
197     // Some instructions are marked as pseudo right now which
198     // would make the test fail for the wrong reason but
199     // that will be fixed soon. We need this here because we are
200     // removing another test for this situation downstream in the
201     // callchain.
202     //
203     if (I->isPseudo() && !Subtarget->inMips16Mode()
204         && !isLongBranchPseudo(I->getOpcode()))
205       llvm_unreachable("Pseudo opcode found in EmitInstruction()");
206
207     MCInst TmpInst0;
208     MCInstLowering.Lower(&*I, TmpInst0);
209     EmitToStreamer(*OutStreamer, TmpInst0);
210   } while ((++I != E) && I->isInsideBundle()); // Delay slot check
211 }
212
213 //===----------------------------------------------------------------------===//
214 //
215 //  Mips Asm Directives
216 //
217 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
218 //  Describe the stack frame.
219 //
220 //  -- Mask directives "(f)mask  bitmask, offset"
221 //  Tells the assembler which registers are saved and where.
222 //  bitmask - contain a little endian bitset indicating which registers are
223 //            saved on function prologue (e.g. with a 0x80000000 mask, the
224 //            assembler knows the register 31 (RA) is saved at prologue.
225 //  offset  - the position before stack pointer subtraction indicating where
226 //            the first saved register on prologue is located. (e.g. with a
227 //
228 //  Consider the following function prologue:
229 //
230 //    .frame  $fp,48,$ra
231 //    .mask   0xc0000000,-8
232 //       addiu $sp, $sp, -48
233 //       sw $ra, 40($sp)
234 //       sw $fp, 36($sp)
235 //
236 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
237 //    30 (FP) are saved at prologue. As the save order on prologue is from
238 //    left to right, RA is saved first. A -8 offset means that after the
239 //    stack pointer subtration, the first register in the mask (RA) will be
240 //    saved at address 48-8=40.
241 //
242 //===----------------------------------------------------------------------===//
243
244 //===----------------------------------------------------------------------===//
245 // Mask directives
246 //===----------------------------------------------------------------------===//
247
248 // Create a bitmask with all callee saved registers for CPU or Floating Point
249 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
250 void MipsAsmPrinter::printSavedRegsBitmask() {
251   // CPU and FPU Saved Registers Bitmasks
252   unsigned CPUBitmask = 0, FPUBitmask = 0;
253   int CPUTopSavedRegOff, FPUTopSavedRegOff;
254
255   // Set the CPU and FPU Bitmasks
256   const MachineFrameInfo &MFI = MF->getFrameInfo();
257   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
258   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
259   // size of stack area to which FP callee-saved regs are saved.
260   unsigned CPURegSize = Mips::GPR32RegClass.getSize();
261   unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
262   unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
263   bool HasAFGR64Reg = false;
264   unsigned CSFPRegsSize = 0;
265
266   for (const auto &I : CSI) {
267     unsigned Reg = I.getReg();
268     unsigned RegNum = TRI->getEncodingValue(Reg);
269
270     // If it's a floating point register, set the FPU Bitmask.
271     // If it's a general purpose register, set the CPU Bitmask.
272     if (Mips::FGR32RegClass.contains(Reg)) {
273       FPUBitmask |= (1 << RegNum);
274       CSFPRegsSize += FGR32RegSize;
275     } else if (Mips::AFGR64RegClass.contains(Reg)) {
276       FPUBitmask |= (3 << RegNum);
277       CSFPRegsSize += AFGR64RegSize;
278       HasAFGR64Reg = true;
279     } else if (Mips::GPR32RegClass.contains(Reg))
280       CPUBitmask |= (1 << RegNum);
281   }
282
283   // FP Regs are saved right below where the virtual frame pointer points to.
284   FPUTopSavedRegOff = FPUBitmask ?
285     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
286
287   // CPU Regs are saved below FP Regs.
288   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
289
290   MipsTargetStreamer &TS = getTargetStreamer();
291   // Print CPUBitmask
292   TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
293
294   // Print FPUBitmask
295   TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
296 }
297
298 //===----------------------------------------------------------------------===//
299 // Frame and Set directives
300 //===----------------------------------------------------------------------===//
301
302 /// Frame Directive
303 void MipsAsmPrinter::emitFrameDirective() {
304   const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo();
305
306   unsigned stackReg  = RI.getFrameRegister(*MF);
307   unsigned returnReg = RI.getRARegister();
308   unsigned stackSize = MF->getFrameInfo().getStackSize();
309
310   getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
311 }
312
313 /// Emit Set directives.
314 const char *MipsAsmPrinter::getCurrentABIString() const {
315   switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) {
316   case MipsABIInfo::ABI::O32:  return "abi32";
317   case MipsABIInfo::ABI::N32:  return "abiN32";
318   case MipsABIInfo::ABI::N64:  return "abi64";
319   default: llvm_unreachable("Unknown Mips ABI");
320   }
321 }
322
323 void MipsAsmPrinter::EmitFunctionEntryLabel() {
324   MipsTargetStreamer &TS = getTargetStreamer();
325
326   // NaCl sandboxing requires that indirect call instructions are masked.
327   // This means that function entry points should be bundle-aligned.
328   if (Subtarget->isTargetNaCl())
329     EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
330
331   if (Subtarget->inMicroMipsMode()) {
332     TS.emitDirectiveSetMicroMips();
333     TS.setUsesMicroMips();
334   } else
335     TS.emitDirectiveSetNoMicroMips();
336
337   if (Subtarget->inMips16Mode())
338     TS.emitDirectiveSetMips16();
339   else
340     TS.emitDirectiveSetNoMips16();
341
342   TS.emitDirectiveEnt(*CurrentFnSym);
343   OutStreamer->EmitLabel(CurrentFnSym);
344 }
345
346 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
347 /// the first basic block in the function.
348 void MipsAsmPrinter::EmitFunctionBodyStart() {
349   MipsTargetStreamer &TS = getTargetStreamer();
350
351   MCInstLowering.Initialize(&MF->getContext());
352
353   bool IsNakedFunction = MF->getFunction()->hasFnAttribute(Attribute::Naked);
354   if (!IsNakedFunction)
355     emitFrameDirective();
356
357   if (!IsNakedFunction)
358     printSavedRegsBitmask();
359
360   if (!Subtarget->inMips16Mode()) {
361     TS.emitDirectiveSetNoReorder();
362     TS.emitDirectiveSetNoMacro();
363     TS.emitDirectiveSetNoAt();
364   }
365 }
366
367 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
368 /// the last basic block in the function.
369 void MipsAsmPrinter::EmitFunctionBodyEnd() {
370   MipsTargetStreamer &TS = getTargetStreamer();
371
372   // There are instruction for this macros, but they must
373   // always be at the function end, and we can't emit and
374   // break with BB logic.
375   if (!Subtarget->inMips16Mode()) {
376     TS.emitDirectiveSetAt();
377     TS.emitDirectiveSetMacro();
378     TS.emitDirectiveSetReorder();
379   }
380   TS.emitDirectiveEnd(CurrentFnSym->getName());
381   // Make sure to terminate any constant pools that were at the end
382   // of the function.
383   if (!InConstantPool)
384     return;
385   InConstantPool = false;
386   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
387 }
388
389 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
390   MipsTargetStreamer &TS = getTargetStreamer();
391   if (MBB.size() == 0)
392     TS.emitDirectiveInsn();
393 }
394
395 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
396 /// exactly one predecessor and the control transfer mechanism between
397 /// the predecessor and this block is a fall-through.
398 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
399                                                        MBB) const {
400   // The predecessor has to be immediately before this block.
401   const MachineBasicBlock *Pred = *MBB->pred_begin();
402
403   // If the predecessor is a switch statement, assume a jump table
404   // implementation, so it is not a fall through.
405   if (const BasicBlock *bb = Pred->getBasicBlock())
406     if (isa<SwitchInst>(bb->getTerminator()))
407       return false;
408
409   // If this is a landing pad, it isn't a fall through.  If it has no preds,
410   // then nothing falls through to it.
411   if (MBB->isEHPad() || MBB->pred_empty())
412     return false;
413
414   // If there isn't exactly one predecessor, it can't be a fall through.
415   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
416   ++PI2;
417
418   if (PI2 != MBB->pred_end())
419     return false;
420
421   // The predecessor has to be immediately before this block.
422   if (!Pred->isLayoutSuccessor(MBB))
423     return false;
424
425   // If the block is completely empty, then it definitely does fall through.
426   if (Pred->empty())
427     return true;
428
429   // Otherwise, check the last instruction.
430   // Check if the last terminator is an unconditional branch.
431   MachineBasicBlock::const_iterator I = Pred->end();
432   while (I != Pred->begin() && !(--I)->isTerminator()) ;
433
434   return !I->isBarrier();
435 }
436
437 // Print out an operand for an inline asm expression.
438 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
439                                      unsigned AsmVariant, const char *ExtraCode,
440                                      raw_ostream &O) {
441   // Does this asm operand have a single letter operand modifier?
442   if (ExtraCode && ExtraCode[0]) {
443     if (ExtraCode[1] != 0) return true; // Unknown modifier.
444
445     const MachineOperand &MO = MI->getOperand(OpNum);
446     switch (ExtraCode[0]) {
447     default:
448       // See if this is a generic print operand
449       return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
450     case 'X': // hex const int
451       if ((MO.getType()) != MachineOperand::MO_Immediate)
452         return true;
453       O << "0x" << Twine::utohexstr(MO.getImm());
454       return false;
455     case 'x': // hex const int (low 16 bits)
456       if ((MO.getType()) != MachineOperand::MO_Immediate)
457         return true;
458       O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff);
459       return false;
460     case 'd': // decimal const int
461       if ((MO.getType()) != MachineOperand::MO_Immediate)
462         return true;
463       O << MO.getImm();
464       return false;
465     case 'm': // decimal const int minus 1
466       if ((MO.getType()) != MachineOperand::MO_Immediate)
467         return true;
468       O << MO.getImm() - 1;
469       return false;
470     case 'z': {
471       // $0 if zero, regular printing otherwise
472       if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) {
473         O << "$0";
474         return false;
475       }
476       // If not, call printOperand as normal.
477       break;
478     }
479     case 'D': // Second part of a double word register operand
480     case 'L': // Low order register of a double word register operand
481     case 'M': // High order register of a double word register operand
482     {
483       if (OpNum == 0)
484         return true;
485       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
486       if (!FlagsOP.isImm())
487         return true;
488       unsigned Flags = FlagsOP.getImm();
489       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
490       // Number of registers represented by this operand. We are looking
491       // for 2 for 32 bit mode and 1 for 64 bit mode.
492       if (NumVals != 2) {
493         if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
494           unsigned Reg = MO.getReg();
495           O << '$' << MipsInstPrinter::getRegisterName(Reg);
496           return false;
497         }
498         return true;
499       }
500
501       unsigned RegOp = OpNum;
502       if (!Subtarget->isGP64bit()){
503         // Endianness reverses which register holds the high or low value
504         // between M and L.
505         switch(ExtraCode[0]) {
506         case 'M':
507           RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
508           break;
509         case 'L':
510           RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
511           break;
512         case 'D': // Always the second part
513           RegOp = OpNum + 1;
514         }
515         if (RegOp >= MI->getNumOperands())
516           return true;
517         const MachineOperand &MO = MI->getOperand(RegOp);
518         if (!MO.isReg())
519           return true;
520         unsigned Reg = MO.getReg();
521         O << '$' << MipsInstPrinter::getRegisterName(Reg);
522         return false;
523       }
524     }
525     case 'w':
526       // Print MSA registers for the 'f' constraint
527       // In LLVM, the 'w' modifier doesn't need to do anything.
528       // We can just call printOperand as normal.
529       break;
530     }
531   }
532
533   printOperand(MI, OpNum, O);
534   return false;
535 }
536
537 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
538                                            unsigned OpNum, unsigned AsmVariant,
539                                            const char *ExtraCode,
540                                            raw_ostream &O) {
541   assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands");
542   const MachineOperand &BaseMO = MI->getOperand(OpNum);
543   const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1);
544   assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand.");
545   assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand.");
546   int Offset = OffsetMO.getImm();
547
548   // Currently we are expecting either no ExtraCode or 'D'
549   if (ExtraCode) {
550     if (ExtraCode[0] == 'D')
551       Offset += 4;
552     else
553       return true; // Unknown modifier.
554     // FIXME: M = high order bits
555     // FIXME: L = low order bits
556   }
557
558   O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) << ")";
559
560   return false;
561 }
562
563 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
564                                   raw_ostream &O) {
565   const MachineOperand &MO = MI->getOperand(opNum);
566   bool closeP = false;
567
568   if (MO.getTargetFlags())
569     closeP = true;
570
571   switch(MO.getTargetFlags()) {
572   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
573   case MipsII::MO_GOT_CALL: O << "%call16("; break;
574   case MipsII::MO_GOT:      O << "%got(";    break;
575   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
576   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
577   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
578   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
579   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
580   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
581   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
582   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
583   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
584   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
585   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
586   }
587
588   switch (MO.getType()) {
589     case MachineOperand::MO_Register:
590       O << '$'
591         << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
592       break;
593
594     case MachineOperand::MO_Immediate:
595       O << MO.getImm();
596       break;
597
598     case MachineOperand::MO_MachineBasicBlock:
599       MO.getMBB()->getSymbol()->print(O, MAI);
600       return;
601
602     case MachineOperand::MO_GlobalAddress:
603       getSymbol(MO.getGlobal())->print(O, MAI);
604       break;
605
606     case MachineOperand::MO_BlockAddress: {
607       MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
608       O << BA->getName();
609       break;
610     }
611
612     case MachineOperand::MO_ConstantPoolIndex:
613       O << getDataLayout().getPrivateGlobalPrefix() << "CPI"
614         << getFunctionNumber() << "_" << MO.getIndex();
615       if (MO.getOffset())
616         O << "+" << MO.getOffset();
617       break;
618
619     default:
620       llvm_unreachable("<unknown operand type>");
621   }
622
623   if (closeP) O << ")";
624 }
625
626 void MipsAsmPrinter::
627 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
628   // Load/Store memory operands -- imm($reg)
629   // If PIC target the target is loaded as the
630   // pattern lw $25,%call16($28)
631
632   // opNum can be invalid if instruction has reglist as operand.
633   // MemOperand is always last operand of instruction (base + offset).
634   switch (MI->getOpcode()) {
635   default:
636     break;
637   case Mips::SWM32_MM:
638   case Mips::LWM32_MM:
639     opNum = MI->getNumOperands() - 2;
640     break;
641   }
642
643   printOperand(MI, opNum+1, O);
644   O << "(";
645   printOperand(MI, opNum, O);
646   O << ")";
647 }
648
649 void MipsAsmPrinter::
650 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
651   // when using stack locations for not load/store instructions
652   // print the same way as all normal 3 operand instructions.
653   printOperand(MI, opNum, O);
654   O << ", ";
655   printOperand(MI, opNum+1, O);
656   return;
657 }
658
659 void MipsAsmPrinter::
660 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
661                 const char *Modifier) {
662   const MachineOperand &MO = MI->getOperand(opNum);
663   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
664 }
665
666 void MipsAsmPrinter::
667 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
668   for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
669     if (i != opNum) O << ", ";
670     printOperand(MI, i, O);
671   }
672 }
673
674 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
675   MipsTargetStreamer &TS = getTargetStreamer();
676
677   // MipsTargetStreamer has an initialization order problem when emitting an
678   // object file directly (see MipsTargetELFStreamer for full details). Work
679   // around it by re-initializing the PIC state here.
680   TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent());
681
682   // Compute MIPS architecture attributes based on the default subtarget
683   // that we'd have constructed. Module level directives aren't LTO
684   // clean anyhow.
685   // FIXME: For ifunc related functions we could iterate over and look
686   // for a feature string that doesn't match the default one.
687   const Triple &TT = TM.getTargetTriple();
688   StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU());
689   StringRef FS = TM.getTargetFeatureString();
690   const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
691   const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM);
692
693   bool IsABICalls = STI.isABICalls();
694   const MipsABIInfo &ABI = MTM.getABI();
695   if (IsABICalls) {
696     TS.emitDirectiveAbiCalls();
697     // FIXME: This condition should be a lot more complicated that it is here.
698     //        Ideally it should test for properties of the ABI and not the ABI
699     //        itself.
700     //        For the moment, I'm only correcting enough to make MIPS-IV work.
701     if (!isPositionIndependent() && !ABI.IsN64())
702       TS.emitDirectiveOptionPic0();
703   }
704
705   // Tell the assembler which ABI we are using
706   std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
707   OutStreamer->SwitchSection(
708       OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0));
709
710   // NaN: At the moment we only support:
711   // 1. .nan legacy (default)
712   // 2. .nan 2008
713   STI.isNaN2008() ? TS.emitDirectiveNaN2008()
714                   : TS.emitDirectiveNaNLegacy();
715
716   // TODO: handle O64 ABI
717
718   TS.updateABIInfo(STI);
719
720   // We should always emit a '.module fp=...' but binutils 2.24 does not accept
721   // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or
722   // -mfp64) and omit it otherwise.
723   if (ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit()))
724     TS.emitDirectiveModuleFP();
725
726   // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
727   // accept it. We therefore emit it when it contradicts the default or an
728   // option has changed the default (i.e. FPXX) and omit it otherwise.
729   if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
730     TS.emitDirectiveModuleOddSPReg();
731 }
732
733 void MipsAsmPrinter::emitInlineAsmStart() const {
734   MipsTargetStreamer &TS = getTargetStreamer();
735
736   // GCC's choice of assembler options for inline assembly code ('at', 'macro'
737   // and 'reorder') is different from LLVM's choice for generated code ('noat',
738   // 'nomacro' and 'noreorder').
739   // In order to maintain compatibility with inline assembly code which depends
740   // on GCC's assembler options being used, we have to switch to those options
741   // for the duration of the inline assembly block and then switch back.
742   TS.emitDirectiveSetPush();
743   TS.emitDirectiveSetAt();
744   TS.emitDirectiveSetMacro();
745   TS.emitDirectiveSetReorder();
746   OutStreamer->AddBlankLine();
747 }
748
749 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
750                                       const MCSubtargetInfo *EndInfo) const {
751   OutStreamer->AddBlankLine();
752   getTargetStreamer().emitDirectiveSetPop();
753 }
754
755 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
756   MCInst I;
757   I.setOpcode(Mips::JAL);
758   I.addOperand(
759       MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext)));
760   OutStreamer->EmitInstruction(I, STI);
761 }
762
763 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
764                                   unsigned Reg) {
765   MCInst I;
766   I.setOpcode(Opcode);
767   I.addOperand(MCOperand::createReg(Reg));
768   OutStreamer->EmitInstruction(I, STI);
769 }
770
771 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
772                                      unsigned Opcode, unsigned Reg1,
773                                      unsigned Reg2) {
774   MCInst I;
775   //
776   // Because of the current td files for Mips32, the operands for MTC1
777   // appear backwards from their normal assembly order. It's not a trivial
778   // change to fix this in the td file so we adjust for it here.
779   //
780   if (Opcode == Mips::MTC1) {
781     unsigned Temp = Reg1;
782     Reg1 = Reg2;
783     Reg2 = Temp;
784   }
785   I.setOpcode(Opcode);
786   I.addOperand(MCOperand::createReg(Reg1));
787   I.addOperand(MCOperand::createReg(Reg2));
788   OutStreamer->EmitInstruction(I, STI);
789 }
790
791 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
792                                         unsigned Opcode, unsigned Reg1,
793                                         unsigned Reg2, unsigned Reg3) {
794   MCInst I;
795   I.setOpcode(Opcode);
796   I.addOperand(MCOperand::createReg(Reg1));
797   I.addOperand(MCOperand::createReg(Reg2));
798   I.addOperand(MCOperand::createReg(Reg3));
799   OutStreamer->EmitInstruction(I, STI);
800 }
801
802 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
803                                       unsigned MovOpc, unsigned Reg1,
804                                       unsigned Reg2, unsigned FPReg1,
805                                       unsigned FPReg2, bool LE) {
806   if (!LE) {
807     unsigned temp = Reg1;
808     Reg1 = Reg2;
809     Reg2 = temp;
810   }
811   EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1);
812   EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2);
813 }
814
815 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
816                                          Mips16HardFloatInfo::FPParamVariant PV,
817                                          bool LE, bool ToFP) {
818   using namespace Mips16HardFloatInfo;
819   unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
820   switch (PV) {
821   case FSig:
822     EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
823     break;
824   case FFSig:
825     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
826     break;
827   case FDSig:
828     EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
829     EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
830     break;
831   case DSig:
832     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
833     break;
834   case DDSig:
835     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
836     EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
837     break;
838   case DFSig:
839     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
840     EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14);
841     break;
842   case NoSig:
843     return;
844   }
845 }
846
847 void MipsAsmPrinter::EmitSwapFPIntRetval(
848     const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
849     bool LE) {
850   using namespace Mips16HardFloatInfo;
851   unsigned MovOpc = Mips::MFC1;
852   switch (RV) {
853   case FRet:
854     EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0);
855     break;
856   case DRet:
857     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
858     break;
859   case CFRet:
860     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
861     break;
862   case CDRet:
863     EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
864     EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
865     break;
866   case NoFPRet:
867     break;
868   }
869 }
870
871 void MipsAsmPrinter::EmitFPCallStub(
872     const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
873   MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol));
874   using namespace Mips16HardFloatInfo;
875   bool LE = getDataLayout().isLittleEndian();
876   // Construct a local MCSubtargetInfo here.
877   // This is because the MachineFunction won't exist (but have not yet been
878   // freed) and since we're at the global level we can use the default
879   // constructed subtarget.
880   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
881       TM.getTargetTriple().str(), TM.getTargetCPU(),
882       TM.getTargetFeatureString()));
883
884   //
885   // .global xxxx
886   //
887   OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global);
888   const char *RetType;
889   //
890   // make the comment field identifying the return and parameter
891   // types of the floating point stub
892   // # Stub function to call rettype xxxx (params)
893   //
894   switch (Signature->RetSig) {
895   case FRet:
896     RetType = "float";
897     break;
898   case DRet:
899     RetType = "double";
900     break;
901   case CFRet:
902     RetType = "complex";
903     break;
904   case CDRet:
905     RetType = "double complex";
906     break;
907   case NoFPRet:
908     RetType = "";
909     break;
910   }
911   const char *Parms;
912   switch (Signature->ParamSig) {
913   case FSig:
914     Parms = "float";
915     break;
916   case FFSig:
917     Parms = "float, float";
918     break;
919   case FDSig:
920     Parms = "float, double";
921     break;
922   case DSig:
923     Parms = "double";
924     break;
925   case DDSig:
926     Parms = "double, double";
927     break;
928   case DFSig:
929     Parms = "double, float";
930     break;
931   case NoSig:
932     Parms = "";
933     break;
934   }
935   OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " +
936                           Twine(Symbol) + " (" + Twine(Parms) + ")");
937   //
938   // probably not necessary but we save and restore the current section state
939   //
940   OutStreamer->PushSection();
941   //
942   // .section mips16.call.fpxxxx,"ax",@progbits
943   //
944   MCSectionELF *M = OutContext.getELFSection(
945       ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
946       ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
947   OutStreamer->SwitchSection(M, nullptr);
948   //
949   // .align 2
950   //
951   OutStreamer->EmitValueToAlignment(4);
952   MipsTargetStreamer &TS = getTargetStreamer();
953   //
954   // .set nomips16
955   // .set nomicromips
956   //
957   TS.emitDirectiveSetNoMips16();
958   TS.emitDirectiveSetNoMicroMips();
959   //
960   // .ent __call_stub_fp_xxxx
961   // .type  __call_stub_fp_xxxx,@function
962   //  __call_stub_fp_xxxx:
963   //
964   std::string x = "__call_stub_fp_" + std::string(Symbol);
965   MCSymbolELF *Stub =
966       cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x)));
967   TS.emitDirectiveEnt(*Stub);
968   MCSymbol *MType =
969       OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
970   OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
971   OutStreamer->EmitLabel(Stub);
972
973   // Only handle non-pic for now.
974   assert(!isPositionIndependent() &&
975          "should not be here if we are compiling pic");
976   TS.emitDirectiveSetReorder();
977   //
978   // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
979   // stubs without raw text but this current patch is for compiler generated
980   // functions and they all return some value.
981   // The calling sequence for non pic is different in that case and we need
982   // to implement %lo and %hi in order to handle the case of no return value
983   // See the corresponding method in Mips16HardFloat for details.
984   //
985   // mov the return address to S2.
986   // we have no stack space to store it and we are about to make another call.
987   // We need to make sure that the enclosing function knows to save S2
988   // This should have already been handled.
989   //
990   // Mov $18, $31
991
992   EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO);
993
994   EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true);
995
996   // Jal xxxx
997   //
998   EmitJal(*STI, MSymbol);
999
1000   // fix return values
1001   EmitSwapFPIntRetval(*STI, Signature->RetSig, LE);
1002   //
1003   // do the return
1004   // if (Signature->RetSig == NoFPRet)
1005   //  llvm_unreachable("should not be any stubs here with no return value");
1006   // else
1007   EmitInstrReg(*STI, Mips::JR, Mips::S2);
1008
1009   MCSymbol *Tmp = OutContext.createTempSymbol();
1010   OutStreamer->EmitLabel(Tmp);
1011   const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext);
1012   const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext);
1013   const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext);
1014   OutStreamer->emitELFSize(Stub, T_min_E);
1015   TS.emitDirectiveEnd(x);
1016   OutStreamer->PopSection();
1017 }
1018
1019 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
1020   // Emit needed stubs
1021   //
1022   for (std::map<
1023            const char *,
1024            const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
1025            it = StubsNeeded.begin();
1026        it != StubsNeeded.end(); ++it) {
1027     const char *Symbol = it->first;
1028     const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1029     EmitFPCallStub(Symbol, Signature);
1030   }
1031   // return to the text section
1032   OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1033 }
1034
1035 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1036                                            raw_ostream &OS) {
1037   // TODO: implement
1038 }
1039
1040 // Emit .dtprelword or .dtpreldword directive
1041 // and value for debug thread local expression.
1042 void MipsAsmPrinter::EmitDebugValue(const MCExpr *Value,
1043                                           unsigned Size) const {
1044   switch (Size) {
1045   case 4:
1046     OutStreamer->EmitDTPRel32Value(Value);
1047     break;
1048   case 8:
1049     OutStreamer->EmitDTPRel64Value(Value);
1050     break;
1051   default:
1052     llvm_unreachable("Unexpected size of expression value.");
1053   }
1054 }
1055
1056 // Align all targets of indirect branches on bundle size.  Used only if target
1057 // is NaCl.
1058 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1059   // Align all blocks that are jumped to through jump table.
1060   if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1061     const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1062     for (unsigned I = 0; I < JT.size(); ++I) {
1063       const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
1064
1065       for (unsigned J = 0; J < MBBs.size(); ++J)
1066         MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1067     }
1068   }
1069
1070   // If basic block address is taken, block can be target of indirect branch.
1071   for (auto &MBB : MF) {
1072     if (MBB.hasAddressTaken())
1073       MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1074   }
1075 }
1076
1077 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1078   return (Opcode == Mips::LONG_BRANCH_LUi
1079           || Opcode == Mips::LONG_BRANCH_ADDiu
1080           || Opcode == Mips::LONG_BRANCH_DADDiu);
1081 }
1082
1083 // Force static initialization.
1084 extern "C" void LLVMInitializeMipsAsmPrinter() {
1085   RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1086   RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1087   RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1088   RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());
1089 }