4aa79ff51dd2eba48c490dfe0ec8a73285da17ef
[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 = &TM.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 std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
256   // size of stack area to which FP callee-saved regs are saved.
257   unsigned CPURegSize = Mips::GPR32RegClass.getSize();
258   unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
259   unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
260   bool HasAFGR64Reg = false;
261   unsigned CSFPRegsSize = 0;
262   unsigned i, e = CSI.size();
263
264   // Set FPU Bitmask.
265   for (i = 0; i != e; ++i) {
266     unsigned Reg = CSI[i].getReg();
267     if (Mips::GPR32RegClass.contains(Reg))
268       break;
269
270     unsigned RegNum =
271         TM.getSubtargetImpl()->getRegisterInfo()->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 =
287         TM.getSubtargetImpl()->getRegisterInfo()->getEncodingValue(Reg);
288     CPUBitmask |= (1 << RegNum);
289   }
290
291   // FP Regs are saved right below where the virtual frame pointer points to.
292   FPUTopSavedRegOff = FPUBitmask ?
293     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
294
295   // CPU Regs are saved below FP Regs.
296   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
297
298   MipsTargetStreamer &TS = getTargetStreamer();
299   // Print CPUBitmask
300   TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
301
302   // Print FPUBitmask
303   TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
304 }
305
306 //===----------------------------------------------------------------------===//
307 // Frame and Set directives
308 //===----------------------------------------------------------------------===//
309
310 /// Frame Directive
311 void MipsAsmPrinter::emitFrameDirective() {
312   const TargetRegisterInfo &RI = *TM.getSubtargetImpl()->getRegisterInfo();
313
314   unsigned stackReg  = RI.getFrameRegister(*MF);
315   unsigned returnReg = RI.getRARegister();
316   unsigned stackSize = MF->getFrameInfo()->getStackSize();
317
318   getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
319 }
320
321 /// Emit Set directives.
322 const char *MipsAsmPrinter::getCurrentABIString() const {
323   switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) {
324   case MipsABIInfo::ABI::O32:  return "abi32";
325   case MipsABIInfo::ABI::N32:  return "abiN32";
326   case MipsABIInfo::ABI::N64:  return "abi64";
327   case MipsABIInfo::ABI::EABI: return "eabi32"; // TODO: handle eabi64
328   default: llvm_unreachable("Unknown Mips ABI");
329   }
330 }
331
332 void MipsAsmPrinter::EmitFunctionEntryLabel() {
333   MipsTargetStreamer &TS = getTargetStreamer();
334
335   // NaCl sandboxing requires that indirect call instructions are masked.
336   // This means that function entry points should be bundle-aligned.
337   if (Subtarget->isTargetNaCl())
338     EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
339
340   if (Subtarget->inMicroMipsMode())
341     TS.emitDirectiveSetMicroMips();
342   else
343     TS.emitDirectiveSetNoMicroMips();
344
345   if (Subtarget->inMips16Mode())
346     TS.emitDirectiveSetMips16();
347   else
348     TS.emitDirectiveSetNoMips16();
349
350   TS.emitDirectiveEnt(*CurrentFnSym);
351   OutStreamer.EmitLabel(CurrentFnSym);
352 }
353
354 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
355 /// the first basic block in the function.
356 void MipsAsmPrinter::EmitFunctionBodyStart() {
357   MipsTargetStreamer &TS = getTargetStreamer();
358
359   MCInstLowering.Initialize(&MF->getContext());
360
361   bool IsNakedFunction =
362     MF->getFunction()->
363       getAttributes().hasAttribute(AttributeSet::FunctionIndex,
364                                    Attribute::Naked);
365   if (!IsNakedFunction)
366     emitFrameDirective();
367
368   if (!IsNakedFunction)
369     printSavedRegsBitmask();
370
371   if (!Subtarget->inMips16Mode()) {
372     TS.emitDirectiveSetNoReorder();
373     TS.emitDirectiveSetNoMacro();
374     TS.emitDirectiveSetNoAt();
375   }
376 }
377
378 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
379 /// the last basic block in the function.
380 void MipsAsmPrinter::EmitFunctionBodyEnd() {
381   MipsTargetStreamer &TS = getTargetStreamer();
382
383   // There are instruction for this macros, but they must
384   // always be at the function end, and we can't emit and
385   // break with BB logic.
386   if (!Subtarget->inMips16Mode()) {
387     TS.emitDirectiveSetAt();
388     TS.emitDirectiveSetMacro();
389     TS.emitDirectiveSetReorder();
390   }
391   TS.emitDirectiveEnd(CurrentFnSym->getName());
392   // Make sure to terminate any constant pools that were at the end
393   // of the function.
394   if (!InConstantPool)
395     return;
396   InConstantPool = false;
397   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
398 }
399
400 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
401 /// exactly one predecessor and the control transfer mechanism between
402 /// the predecessor and this block is a fall-through.
403 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
404                                                        MBB) const {
405   // The predecessor has to be immediately before this block.
406   const MachineBasicBlock *Pred = *MBB->pred_begin();
407
408   // If the predecessor is a switch statement, assume a jump table
409   // implementation, so it is not a fall through.
410   if (const BasicBlock *bb = Pred->getBasicBlock())
411     if (isa<SwitchInst>(bb->getTerminator()))
412       return false;
413
414   // If this is a landing pad, it isn't a fall through.  If it has no preds,
415   // then nothing falls through to it.
416   if (MBB->isLandingPad() || MBB->pred_empty())
417     return false;
418
419   // If there isn't exactly one predecessor, it can't be a fall through.
420   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
421   ++PI2;
422
423   if (PI2 != MBB->pred_end())
424     return false;
425
426   // The predecessor has to be immediately before this block.
427   if (!Pred->isLayoutSuccessor(MBB))
428     return false;
429
430   // If the block is completely empty, then it definitely does fall through.
431   if (Pred->empty())
432     return true;
433
434   // Otherwise, check the last instruction.
435   // Check if the last terminator is an unconditional branch.
436   MachineBasicBlock::const_iterator I = Pred->end();
437   while (I != Pred->begin() && !(--I)->isTerminator()) ;
438
439   return !I->isBarrier();
440 }
441
442 // Print out an operand for an inline asm expression.
443 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
444                                      unsigned AsmVariant,const char *ExtraCode,
445                                      raw_ostream &O) {
446   // Does this asm operand have a single letter operand modifier?
447   if (ExtraCode && ExtraCode[0]) {
448     if (ExtraCode[1] != 0) return true; // Unknown modifier.
449
450     const MachineOperand &MO = MI->getOperand(OpNum);
451     switch (ExtraCode[0]) {
452     default:
453       // See if this is a generic print operand
454       return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
455     case 'X': // hex const int
456       if ((MO.getType()) != MachineOperand::MO_Immediate)
457         return true;
458       O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
459       return false;
460     case 'x': // hex const int (low 16 bits)
461       if ((MO.getType()) != MachineOperand::MO_Immediate)
462         return true;
463       O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
464       return false;
465     case 'd': // decimal const int
466       if ((MO.getType()) != MachineOperand::MO_Immediate)
467         return true;
468       O << MO.getImm();
469       return false;
470     case 'm': // decimal const int minus 1
471       if ((MO.getType()) != MachineOperand::MO_Immediate)
472         return true;
473       O << MO.getImm() - 1;
474       return false;
475     case 'z': {
476       // $0 if zero, regular printing otherwise
477       if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) {
478         O << "$0";
479         return false;
480       }
481       // If not, call printOperand as normal.
482       break;
483     }
484     case 'D': // Second part of a double word register operand
485     case 'L': // Low order register of a double word register operand
486     case 'M': // High order register of a double word register operand
487     {
488       if (OpNum == 0)
489         return true;
490       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
491       if (!FlagsOP.isImm())
492         return true;
493       unsigned Flags = FlagsOP.getImm();
494       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
495       // Number of registers represented by this operand. We are looking
496       // for 2 for 32 bit mode and 1 for 64 bit mode.
497       if (NumVals != 2) {
498         if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
499           unsigned Reg = MO.getReg();
500           O << '$' << MipsInstPrinter::getRegisterName(Reg);
501           return false;
502         }
503         return true;
504       }
505
506       unsigned RegOp = OpNum;
507       if (!Subtarget->isGP64bit()){
508         // Endianess reverses which register holds the high or low value
509         // between M and L.
510         switch(ExtraCode[0]) {
511         case 'M':
512           RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
513           break;
514         case 'L':
515           RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
516           break;
517         case 'D': // Always the second part
518           RegOp = OpNum + 1;
519         }
520         if (RegOp >= MI->getNumOperands())
521           return true;
522         const MachineOperand &MO = MI->getOperand(RegOp);
523         if (!MO.isReg())
524           return true;
525         unsigned Reg = MO.getReg();
526         O << '$' << MipsInstPrinter::getRegisterName(Reg);
527         return false;
528       }
529     }
530     case 'w':
531       // Print MSA registers for the 'f' constraint
532       // In LLVM, the 'w' modifier doesn't need to do anything.
533       // We can just call printOperand as normal.
534       break;
535     }
536   }
537
538   printOperand(MI, OpNum, O);
539   return false;
540 }
541
542 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
543                                            unsigned OpNum, unsigned AsmVariant,
544                                            const char *ExtraCode,
545                                            raw_ostream &O) {
546   int Offset = 0;
547   // Currently we are expecting either no ExtraCode or 'D'
548   if (ExtraCode) {
549     if (ExtraCode[0] == 'D')
550       Offset = 4;
551     else
552       return true; // Unknown modifier.
553   }
554
555   const MachineOperand &MO = MI->getOperand(OpNum);
556   assert(MO.isReg() && "unexpected inline asm memory operand");
557   O << Offset << "($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
558
559   return false;
560 }
561
562 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
563                                   raw_ostream &O) {
564   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
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       O << *MO.getMBB()->getSymbol();
600       return;
601
602     case MachineOperand::MO_GlobalAddress:
603       O << *getSymbol(MO.getGlobal());
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 << DL->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::printUnsignedImm(const MachineInstr *MI, int opNum,
627                                       raw_ostream &O) {
628   const MachineOperand &MO = MI->getOperand(opNum);
629   if (MO.isImm())
630     O << (unsigned short int)MO.getImm();
631   else
632     printOperand(MI, opNum, O);
633 }
634
635 void MipsAsmPrinter::printUnsignedImm8(const MachineInstr *MI, int opNum,
636                                        raw_ostream &O) {
637   const MachineOperand &MO = MI->getOperand(opNum);
638   if (MO.isImm())
639     O << (unsigned short int)(unsigned char)MO.getImm();
640   else
641     printOperand(MI, opNum, O);
642 }
643
644 void MipsAsmPrinter::
645 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
646   // Load/Store memory operands -- imm($reg)
647   // If PIC target the target is loaded as the
648   // pattern lw $25,%call16($28)
649
650   // opNum can be invalid if instruction has reglist as operand.
651   // MemOperand is always last operand of instruction (base + offset).
652   switch (MI->getOpcode()) {
653   default:
654     break;
655   case Mips::SWM32_MM:
656   case Mips::LWM32_MM:
657     opNum = MI->getNumOperands() - 2;
658     break;
659   }
660
661   printOperand(MI, opNum+1, O);
662   O << "(";
663   printOperand(MI, opNum, O);
664   O << ")";
665 }
666
667 void MipsAsmPrinter::
668 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
669   // when using stack locations for not load/store instructions
670   // print the same way as all normal 3 operand instructions.
671   printOperand(MI, opNum, O);
672   O << ", ";
673   printOperand(MI, opNum+1, O);
674   return;
675 }
676
677 void MipsAsmPrinter::
678 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
679                 const char *Modifier) {
680   const MachineOperand &MO = MI->getOperand(opNum);
681   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
682 }
683
684 void MipsAsmPrinter::
685 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
686   for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
687     if (i != opNum) O << ", ";
688     printOperand(MI, i, O);
689   }
690 }
691
692 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
693   bool IsABICalls = Subtarget->isABICalls();
694   if (IsABICalls) {
695     getTargetStreamer().emitDirectiveAbiCalls();
696     Reloc::Model RM = TM.getRelocationModel();
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 (RM == Reloc::Static && !Subtarget->isABI_N64())
702       getTargetStreamer().emitDirectiveOptionPic0();
703   }
704
705   // Tell the assembler which ABI we are using
706   std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
707   OutStreamer.SwitchSection(OutContext.getELFSection(
708       SectionName, ELF::SHT_PROGBITS, 0, SectionKind::getDataRel()));
709
710   // NaN: At the moment we only support:
711   // 1. .nan legacy (default)
712   // 2. .nan 2008
713   Subtarget->isNaN2008() ? getTargetStreamer().emitDirectiveNaN2008()
714     : getTargetStreamer().emitDirectiveNaNLegacy();
715
716   // TODO: handle O64 ABI
717
718   if (Subtarget->isABI_EABI()) {
719     if (Subtarget->isGP32bit())
720       OutStreamer.SwitchSection(
721           OutContext.getELFSection(".gcc_compiled_long32", ELF::SHT_PROGBITS, 0,
722                                    SectionKind::getDataRel()));
723     else
724       OutStreamer.SwitchSection(
725           OutContext.getELFSection(".gcc_compiled_long64", ELF::SHT_PROGBITS, 0,
726                                    SectionKind::getDataRel()));
727   }
728
729   getTargetStreamer().updateABIInfo(*Subtarget);
730
731   // We should always emit a '.module fp=...' but binutils 2.24 does not accept
732   // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or
733   // -mfp64) and omit it otherwise.
734   if (Subtarget->isABI_O32() && (Subtarget->isABI_FPXX() ||
735                                  Subtarget->isFP64bit()))
736     getTargetStreamer().emitDirectiveModuleFP();
737
738   // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
739   // accept it. We therefore emit it when it contradicts the default or an
740   // option has changed the default (i.e. FPXX) and omit it otherwise.
741   if (Subtarget->isABI_O32() && (!Subtarget->useOddSPReg() ||
742                                  Subtarget->isABI_FPXX()))
743     getTargetStreamer().emitDirectiveModuleOddSPReg(Subtarget->useOddSPReg(),
744                                                     Subtarget->isABI_O32());
745 }
746
747 void MipsAsmPrinter::emitInlineAsmStart(
748     const MCSubtargetInfo &StartInfo) const {
749   MipsTargetStreamer &TS = getTargetStreamer();
750
751   // GCC's choice of assembler options for inline assembly code ('at', 'macro'
752   // and 'reorder') is different from LLVM's choice for generated code ('noat',
753   // 'nomacro' and 'noreorder').
754   // In order to maintain compatibility with inline assembly code which depends
755   // on GCC's assembler options being used, we have to switch to those options
756   // for the duration of the inline assembly block and then switch back.
757   TS.emitDirectiveSetPush();
758   TS.emitDirectiveSetAt();
759   TS.emitDirectiveSetMacro();
760   TS.emitDirectiveSetReorder();
761   OutStreamer.AddBlankLine();
762 }
763
764 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
765                                       const MCSubtargetInfo *EndInfo) const {
766   OutStreamer.AddBlankLine();
767   getTargetStreamer().emitDirectiveSetPop();
768 }
769
770 void MipsAsmPrinter::EmitJal(MCSymbol *Symbol) {
771   MCInst I;
772   I.setOpcode(Mips::JAL);
773   I.addOperand(
774       MCOperand::CreateExpr(MCSymbolRefExpr::Create(Symbol, OutContext)));
775   OutStreamer.EmitInstruction(I, getSubtargetInfo());
776 }
777
778 void MipsAsmPrinter::EmitInstrReg(unsigned Opcode, unsigned Reg) {
779   MCInst I;
780   I.setOpcode(Opcode);
781   I.addOperand(MCOperand::CreateReg(Reg));
782   OutStreamer.EmitInstruction(I, getSubtargetInfo());
783 }
784
785 void MipsAsmPrinter::EmitInstrRegReg(unsigned Opcode, unsigned Reg1,
786                                      unsigned Reg2) {
787   MCInst I;
788   //
789   // Because of the current td files for Mips32, the operands for MTC1
790   // appear backwards from their normal assembly order. It's not a trivial
791   // change to fix this in the td file so we adjust for it here.
792   //
793   if (Opcode == Mips::MTC1) {
794     unsigned Temp = Reg1;
795     Reg1 = Reg2;
796     Reg2 = Temp;
797   }
798   I.setOpcode(Opcode);
799   I.addOperand(MCOperand::CreateReg(Reg1));
800   I.addOperand(MCOperand::CreateReg(Reg2));
801   OutStreamer.EmitInstruction(I, getSubtargetInfo());
802 }
803
804 void MipsAsmPrinter::EmitInstrRegRegReg(unsigned Opcode, unsigned Reg1,
805                                         unsigned Reg2, unsigned Reg3) {
806   MCInst I;
807   I.setOpcode(Opcode);
808   I.addOperand(MCOperand::CreateReg(Reg1));
809   I.addOperand(MCOperand::CreateReg(Reg2));
810   I.addOperand(MCOperand::CreateReg(Reg3));
811   OutStreamer.EmitInstruction(I, getSubtargetInfo());
812 }
813
814 void MipsAsmPrinter::EmitMovFPIntPair(unsigned MovOpc, unsigned Reg1,
815                                       unsigned Reg2, unsigned FPReg1,
816                                       unsigned FPReg2, bool LE) {
817   if (!LE) {
818     unsigned temp = Reg1;
819     Reg1 = Reg2;
820     Reg2 = temp;
821   }
822   EmitInstrRegReg(MovOpc, Reg1, FPReg1);
823   EmitInstrRegReg(MovOpc, Reg2, FPReg2);
824 }
825
826 void MipsAsmPrinter::EmitSwapFPIntParams(Mips16HardFloatInfo::FPParamVariant PV,
827                                          bool LE, bool ToFP) {
828   using namespace Mips16HardFloatInfo;
829   unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
830   switch (PV) {
831   case FSig:
832     EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
833     break;
834   case FFSig:
835     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
836     break;
837   case FDSig:
838     EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
839     EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
840     break;
841   case DSig:
842     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
843     break;
844   case DDSig:
845     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
846     EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
847     break;
848   case DFSig:
849     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
850     EmitInstrRegReg(MovOpc, Mips::A2, Mips::F14);
851     break;
852   case NoSig:
853     return;
854   }
855 }
856
857 void
858 MipsAsmPrinter::EmitSwapFPIntRetval(Mips16HardFloatInfo::FPReturnVariant RV,
859                                     bool LE) {
860   using namespace Mips16HardFloatInfo;
861   unsigned MovOpc = Mips::MFC1;
862   switch (RV) {
863   case FRet:
864     EmitInstrRegReg(MovOpc, Mips::V0, Mips::F0);
865     break;
866   case DRet:
867     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
868     break;
869   case CFRet:
870     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
871     break;
872   case CDRet:
873     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
874     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
875     break;
876   case NoFPRet:
877     break;
878   }
879 }
880
881 void MipsAsmPrinter::EmitFPCallStub(
882     const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
883   MCSymbol *MSymbol = OutContext.GetOrCreateSymbol(StringRef(Symbol));
884   using namespace Mips16HardFloatInfo;
885   bool LE = Subtarget->isLittle();
886   //
887   // .global xxxx
888   //
889   OutStreamer.EmitSymbolAttribute(MSymbol, MCSA_Global);
890   const char *RetType;
891   //
892   // make the comment field identifying the return and parameter
893   // types of the floating point stub
894   // # Stub function to call rettype xxxx (params)
895   //
896   switch (Signature->RetSig) {
897   case FRet:
898     RetType = "float";
899     break;
900   case DRet:
901     RetType = "double";
902     break;
903   case CFRet:
904     RetType = "complex";
905     break;
906   case CDRet:
907     RetType = "double complex";
908     break;
909   case NoFPRet:
910     RetType = "";
911     break;
912   }
913   const char *Parms;
914   switch (Signature->ParamSig) {
915   case FSig:
916     Parms = "float";
917     break;
918   case FFSig:
919     Parms = "float, float";
920     break;
921   case FDSig:
922     Parms = "float, double";
923     break;
924   case DSig:
925     Parms = "double";
926     break;
927   case DDSig:
928     Parms = "double, double";
929     break;
930   case DFSig:
931     Parms = "double, float";
932     break;
933   case NoSig:
934     Parms = "";
935     break;
936   }
937   OutStreamer.AddComment("\t# Stub function to call " + Twine(RetType) + " " +
938                          Twine(Symbol) + " (" + Twine(Parms) + ")");
939   //
940   // probably not necessary but we save and restore the current section state
941   //
942   OutStreamer.PushSection();
943   //
944   // .section mips16.call.fpxxxx,"ax",@progbits
945   //
946   const MCSectionELF *M = OutContext.getELFSection(
947       ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
948       ELF::SHF_ALLOC | ELF::SHF_EXECINSTR, SectionKind::getText());
949   OutStreamer.SwitchSection(M, nullptr);
950   //
951   // .align 2
952   //
953   OutStreamer.EmitValueToAlignment(4);
954   MipsTargetStreamer &TS = getTargetStreamer();
955   //
956   // .set nomips16
957   // .set nomicromips
958   //
959   TS.emitDirectiveSetNoMips16();
960   TS.emitDirectiveSetNoMicroMips();
961   //
962   // .ent __call_stub_fp_xxxx
963   // .type  __call_stub_fp_xxxx,@function
964   //  __call_stub_fp_xxxx:
965   //
966   std::string x = "__call_stub_fp_" + std::string(Symbol);
967   MCSymbol *Stub = OutContext.GetOrCreateSymbol(StringRef(x));
968   TS.emitDirectiveEnt(*Stub);
969   MCSymbol *MType =
970       OutContext.GetOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
971   OutStreamer.EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
972   OutStreamer.EmitLabel(Stub);
973   //
974   // we just handle non pic for now. these function will not be
975   // called otherwise. when the full stub generation is moved here
976   // we need to deal with pic.
977   //
978   if (TM.getRelocationModel() == Reloc::PIC_)
979     llvm_unreachable("should not be here if we are compiling pic");
980   TS.emitDirectiveSetReorder();
981   //
982   // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
983   // stubs without raw text but this current patch is for compiler generated
984   // functions and they all return some value.
985   // The calling sequence for non pic is different in that case and we need
986   // to implement %lo and %hi in order to handle the case of no return value
987   // See the corresponding method in Mips16HardFloat for details.
988   //
989   // mov the return address to S2.
990   // we have no stack space to store it and we are about to make another call.
991   // We need to make sure that the enclosing function knows to save S2
992   // This should have already been handled.
993   //
994   // Mov $18, $31
995
996   EmitInstrRegRegReg(Mips::ADDu, Mips::S2, Mips::RA, Mips::ZERO);
997
998   EmitSwapFPIntParams(Signature->ParamSig, LE, true);
999
1000   // Jal xxxx
1001   //
1002   EmitJal(MSymbol);
1003
1004   // fix return values
1005   EmitSwapFPIntRetval(Signature->RetSig, LE);
1006   //
1007   // do the return
1008   // if (Signature->RetSig == NoFPRet)
1009   //  llvm_unreachable("should not be any stubs here with no return value");
1010   // else
1011   EmitInstrReg(Mips::JR, Mips::S2);
1012
1013   MCSymbol *Tmp = OutContext.CreateTempSymbol();
1014   OutStreamer.EmitLabel(Tmp);
1015   const MCSymbolRefExpr *E = MCSymbolRefExpr::Create(Stub, OutContext);
1016   const MCSymbolRefExpr *T = MCSymbolRefExpr::Create(Tmp, OutContext);
1017   const MCExpr *T_min_E = MCBinaryExpr::CreateSub(T, E, OutContext);
1018   OutStreamer.EmitELFSize(Stub, T_min_E);
1019   TS.emitDirectiveEnd(x);
1020   OutStreamer.PopSection();
1021 }
1022
1023 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
1024   // Emit needed stubs
1025   //
1026   for (std::map<
1027            const char *,
1028            const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
1029            it = StubsNeeded.begin();
1030        it != StubsNeeded.end(); ++it) {
1031     const char *Symbol = it->first;
1032     const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1033     EmitFPCallStub(Symbol, Signature);
1034   }
1035   // return to the text section
1036   OutStreamer.SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1037 }
1038
1039 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1040                                            raw_ostream &OS) {
1041   // TODO: implement
1042 }
1043
1044 // Align all targets of indirect branches on bundle size.  Used only if target
1045 // is NaCl.
1046 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1047   // Align all blocks that are jumped to through jump table.
1048   if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1049     const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1050     for (unsigned I = 0; I < JT.size(); ++I) {
1051       const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
1052
1053       for (unsigned J = 0; J < MBBs.size(); ++J)
1054         MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1055     }
1056   }
1057
1058   // If basic block address is taken, block can be target of indirect branch.
1059   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
1060                                  MBB != E; ++MBB) {
1061     if (MBB->hasAddressTaken())
1062       MBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1063   }
1064 }
1065
1066 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1067   return (Opcode == Mips::LONG_BRANCH_LUi
1068           || Opcode == Mips::LONG_BRANCH_ADDiu
1069           || Opcode == Mips::LONG_BRANCH_DADDiu);
1070 }
1071
1072 // Force static initialization.
1073 extern "C" void LLVMInitializeMipsAsmPrinter() {
1074   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
1075   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
1076   RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
1077   RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
1078 }