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