[mips][mips64r6] Use JALR for returns instead of JR (which is not available on MIPS32...
[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 "MipsTargetStreamer.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.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/MCSymbol.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() {
57   return static_cast<MipsTargetStreamer &>(*OutStreamer.getTargetStreamer());
58 }
59
60 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
61   // Initialize TargetLoweringObjectFile.
62   if (Subtarget->allowMixed16_32())
63     const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
64       .Initialize(OutContext, TM);
65   MipsFI = MF.getInfo<MipsFunctionInfo>();
66   if (Subtarget->inMips16Mode())
67     for (std::map<
68              const char *,
69              const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
70              it = MipsFI->StubsNeeded.begin();
71          it != MipsFI->StubsNeeded.end(); ++it) {
72       const char *Symbol = it->first;
73       const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
74       if (StubsNeeded.find(Symbol) == StubsNeeded.end())
75         StubsNeeded[Symbol] = Signature;
76     }
77   MCP = MF.getConstantPool();
78
79   // In NaCl, all indirect jump targets must be aligned to bundle size.
80   if (Subtarget->isTargetNaCl())
81     NaClAlignIndirectJumpTargets(MF);
82
83   AsmPrinter::runOnMachineFunction(MF);
84   return true;
85 }
86
87 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
88   MCOp = MCInstLowering.LowerOperand(MO);
89   return MCOp.isValid();
90 }
91
92 #include "MipsGenMCPseudoLowering.inc"
93
94 void MipsAsmPrinter::emitPseudoReturn(MCStreamer &OutStreamer,
95                                       const MachineInstr *MI) {
96   // Lower PseudoReturn to JR, JR_MM, JALR, or JALR64 as appropriate for the
97   // target
98   bool HasLinkReg = false;
99   MCInst TmpInst0;
100
101   if (Subtarget->hasMips64r6()) {
102     // MIPS64r6 should use (JALR64 ZERO_64, $rs)
103     TmpInst0.setOpcode(Mips::JALR64);
104     HasLinkReg = true;
105   } else if (Subtarget->hasMips32r6()) {
106     // MIPS32r6 should use (JALR ZERO, $rs)
107     TmpInst0.setOpcode(Mips::JALR);
108     HasLinkReg = true;
109   } else if (Subtarget->inMicroMipsMode())
110     // microMIPS should use (JR_MM $rs)
111     TmpInst0.setOpcode(Mips::JR_MM);
112   else {
113     // Everything else should use (JR $rs)
114     TmpInst0.setOpcode(Mips::JR);
115   }
116
117   MCOperand MCOp;
118
119   if (HasLinkReg) {
120     unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
121     TmpInst0.addOperand(MCOperand::CreateReg(ZeroReg));
122   }
123
124   lowerOperand(MI->getOperand(0), MCOp);
125   TmpInst0.addOperand(MCOp);
126
127   EmitToStreamer(OutStreamer, TmpInst0);
128 }
129
130 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
131   MipsTargetStreamer &TS = getTargetStreamer();
132   TS.setCanHaveModuleDir(false);
133
134   if (MI->isDebugValue()) {
135     SmallString<128> Str;
136     raw_svector_ostream OS(Str);
137
138     PrintDebugValueComment(MI, OS);
139     return;
140   }
141
142   // If we just ended a constant pool, mark it as such.
143   if (InConstantPool && MI->getOpcode() != Mips::CONSTPOOL_ENTRY) {
144     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
145     InConstantPool = false;
146   }
147   if (MI->getOpcode() == Mips::CONSTPOOL_ENTRY) {
148     // CONSTPOOL_ENTRY - This instruction represents a floating
149     //constant pool in the function.  The first operand is the ID#
150     // for this instruction, the second is the index into the
151     // MachineConstantPool that this is, the third is the size in
152     // bytes of this constant pool entry.
153     // The required alignment is specified on the basic block holding this MI.
154     //
155     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
156     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
157
158     // If this is the first entry of the pool, mark it.
159     if (!InConstantPool) {
160       OutStreamer.EmitDataRegion(MCDR_DataRegion);
161       InConstantPool = true;
162     }
163
164     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
165
166     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
167     if (MCPE.isMachineConstantPoolEntry())
168       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
169     else
170       EmitGlobalConstant(MCPE.Val.ConstVal);
171     return;
172   }
173
174
175   MachineBasicBlock::const_instr_iterator I = MI;
176   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
177
178   do {
179     // Do any auto-generated pseudo lowerings.
180     if (emitPseudoExpansionLowering(OutStreamer, &*I))
181       continue;
182
183     if (I->getOpcode() == Mips::PseudoReturn ||
184         I->getOpcode() == Mips::PseudoReturn64) {
185       emitPseudoReturn(OutStreamer, &*I);
186       continue;
187     }
188
189     // The inMips16Mode() test is not permanent.
190     // Some instructions are marked as pseudo right now which
191     // would make the test fail for the wrong reason but
192     // that will be fixed soon. We need this here because we are
193     // removing another test for this situation downstream in the
194     // callchain.
195     //
196     if (I->isPseudo() && !Subtarget->inMips16Mode()
197         && !isLongBranchPseudo(I->getOpcode()))
198       llvm_unreachable("Pseudo opcode found in EmitInstruction()");
199
200     MCInst TmpInst0;
201     MCInstLowering.Lower(I, TmpInst0);
202     EmitToStreamer(OutStreamer, TmpInst0);
203   } while ((++I != E) && I->isInsideBundle()); // Delay slot check
204 }
205
206 //===----------------------------------------------------------------------===//
207 //
208 //  Mips Asm Directives
209 //
210 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
211 //  Describe the stack frame.
212 //
213 //  -- Mask directives "(f)mask  bitmask, offset"
214 //  Tells the assembler which registers are saved and where.
215 //  bitmask - contain a little endian bitset indicating which registers are
216 //            saved on function prologue (e.g. with a 0x80000000 mask, the
217 //            assembler knows the register 31 (RA) is saved at prologue.
218 //  offset  - the position before stack pointer subtraction indicating where
219 //            the first saved register on prologue is located. (e.g. with a
220 //
221 //  Consider the following function prologue:
222 //
223 //    .frame  $fp,48,$ra
224 //    .mask   0xc0000000,-8
225 //       addiu $sp, $sp, -48
226 //       sw $ra, 40($sp)
227 //       sw $fp, 36($sp)
228 //
229 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
230 //    30 (FP) are saved at prologue. As the save order on prologue is from
231 //    left to right, RA is saved first. A -8 offset means that after the
232 //    stack pointer subtration, the first register in the mask (RA) will be
233 //    saved at address 48-8=40.
234 //
235 //===----------------------------------------------------------------------===//
236
237 //===----------------------------------------------------------------------===//
238 // Mask directives
239 //===----------------------------------------------------------------------===//
240
241 // Create a bitmask with all callee saved registers for CPU or Floating Point
242 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
243 void MipsAsmPrinter::printSavedRegsBitmask() {
244   // CPU and FPU Saved Registers Bitmasks
245   unsigned CPUBitmask = 0, FPUBitmask = 0;
246   int CPUTopSavedRegOff, FPUTopSavedRegOff;
247
248   // Set the CPU and FPU Bitmasks
249   const MachineFrameInfo *MFI = MF->getFrameInfo();
250   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
251   // size of stack area to which FP callee-saved regs are saved.
252   unsigned CPURegSize = Mips::GPR32RegClass.getSize();
253   unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
254   unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
255   bool HasAFGR64Reg = false;
256   unsigned CSFPRegsSize = 0;
257   unsigned i, e = CSI.size();
258
259   // Set FPU Bitmask.
260   for (i = 0; i != e; ++i) {
261     unsigned Reg = CSI[i].getReg();
262     if (Mips::GPR32RegClass.contains(Reg))
263       break;
264
265     unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
266     if (Mips::AFGR64RegClass.contains(Reg)) {
267       FPUBitmask |= (3 << RegNum);
268       CSFPRegsSize += AFGR64RegSize;
269       HasAFGR64Reg = true;
270       continue;
271     }
272
273     FPUBitmask |= (1 << RegNum);
274     CSFPRegsSize += FGR32RegSize;
275   }
276
277   // Set CPU Bitmask.
278   for (; i != e; ++i) {
279     unsigned Reg = CSI[i].getReg();
280     unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
281     CPUBitmask |= (1 << RegNum);
282   }
283
284   // FP Regs are saved right below where the virtual frame pointer points to.
285   FPUTopSavedRegOff = FPUBitmask ?
286     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
287
288   // CPU Regs are saved below FP Regs.
289   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
290
291   MipsTargetStreamer &TS = getTargetStreamer();
292   // Print CPUBitmask
293   TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
294
295   // Print FPUBitmask
296   TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
297 }
298
299 //===----------------------------------------------------------------------===//
300 // Frame and Set directives
301 //===----------------------------------------------------------------------===//
302
303 /// Frame Directive
304 void MipsAsmPrinter::emitFrameDirective() {
305   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
306
307   unsigned stackReg  = RI.getFrameRegister(*MF);
308   unsigned returnReg = RI.getRARegister();
309   unsigned stackSize = MF->getFrameInfo()->getStackSize();
310
311   getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
312 }
313
314 /// Emit Set directives.
315 const char *MipsAsmPrinter::getCurrentABIString() const {
316   switch (Subtarget->getTargetABI()) {
317   case MipsSubtarget::O32:  return "abi32";
318   case MipsSubtarget::N32:  return "abiN32";
319   case MipsSubtarget::N64:  return "abi64";
320   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
321   default: llvm_unreachable("Unknown Mips ABI");
322   }
323 }
324
325 void MipsAsmPrinter::EmitFunctionEntryLabel() {
326   MipsTargetStreamer &TS = getTargetStreamer();
327
328   // NaCl sandboxing requires that indirect call instructions are masked.
329   // This means that function entry points should be bundle-aligned.
330   if (Subtarget->isTargetNaCl())
331     EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
332
333   if (Subtarget->inMicroMipsMode())
334     TS.emitDirectiveSetMicroMips();
335   else
336     TS.emitDirectiveSetNoMicroMips();
337
338   if (Subtarget->inMips16Mode())
339     TS.emitDirectiveSetMips16();
340   else
341     TS.emitDirectiveSetNoMips16();
342
343   TS.emitDirectiveEnt(*CurrentFnSym);
344   OutStreamer.EmitLabel(CurrentFnSym);
345 }
346
347 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
348 /// the first basic block in the function.
349 void MipsAsmPrinter::EmitFunctionBodyStart() {
350   MipsTargetStreamer &TS = getTargetStreamer();
351
352   MCInstLowering.Initialize(&MF->getContext());
353
354   bool IsNakedFunction =
355     MF->getFunction()->
356       getAttributes().hasAttribute(AttributeSet::FunctionIndex,
357                                    Attribute::Naked);
358   if (!IsNakedFunction)
359     emitFrameDirective();
360
361   if (!IsNakedFunction)
362     printSavedRegsBitmask();
363
364   if (!Subtarget->inMips16Mode()) {
365     TS.emitDirectiveSetNoReorder();
366     TS.emitDirectiveSetNoMacro();
367     TS.emitDirectiveSetNoAt();
368   }
369 }
370
371 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
372 /// the last basic block in the function.
373 void MipsAsmPrinter::EmitFunctionBodyEnd() {
374   MipsTargetStreamer &TS = getTargetStreamer();
375
376   // There are instruction for this macros, but they must
377   // always be at the function end, and we can't emit and
378   // break with BB logic.
379   if (!Subtarget->inMips16Mode()) {
380     TS.emitDirectiveSetAt();
381     TS.emitDirectiveSetMacro();
382     TS.emitDirectiveSetReorder();
383   }
384   TS.emitDirectiveEnd(CurrentFnSym->getName());
385   // Make sure to terminate any constant pools that were at the end
386   // of the function.
387   if (!InConstantPool)
388     return;
389   InConstantPool = false;
390   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
391 }
392
393 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
394 /// exactly one predecessor and the control transfer mechanism between
395 /// the predecessor and this block is a fall-through.
396 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
397                                                        MBB) const {
398   // The predecessor has to be immediately before this block.
399   const MachineBasicBlock *Pred = *MBB->pred_begin();
400
401   // If the predecessor is a switch statement, assume a jump table
402   // implementation, so it is not a fall through.
403   if (const BasicBlock *bb = Pred->getBasicBlock())
404     if (isa<SwitchInst>(bb->getTerminator()))
405       return false;
406
407   // If this is a landing pad, it isn't a fall through.  If it has no preds,
408   // then nothing falls through to it.
409   if (MBB->isLandingPad() || MBB->pred_empty())
410     return false;
411
412   // If there isn't exactly one predecessor, it can't be a fall through.
413   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
414   ++PI2;
415
416   if (PI2 != MBB->pred_end())
417     return false;
418
419   // The predecessor has to be immediately before this block.
420   if (!Pred->isLayoutSuccessor(MBB))
421     return false;
422
423   // If the block is completely empty, then it definitely does fall through.
424   if (Pred->empty())
425     return true;
426
427   // Otherwise, check the last instruction.
428   // Check if the last terminator is an unconditional branch.
429   MachineBasicBlock::const_iterator I = Pred->end();
430   while (I != Pred->begin() && !(--I)->isTerminator()) ;
431
432   return !I->isBarrier();
433 }
434
435 // Print out an operand for an inline asm expression.
436 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
437                                      unsigned AsmVariant,const char *ExtraCode,
438                                      raw_ostream &O) {
439   // Does this asm operand have a single letter operand modifier?
440   if (ExtraCode && ExtraCode[0]) {
441     if (ExtraCode[1] != 0) return true; // Unknown modifier.
442
443     const MachineOperand &MO = MI->getOperand(OpNum);
444     switch (ExtraCode[0]) {
445     default:
446       // See if this is a generic print operand
447       return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
448     case 'X': // hex const int
449       if ((MO.getType()) != MachineOperand::MO_Immediate)
450         return true;
451       O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
452       return false;
453     case 'x': // hex const int (low 16 bits)
454       if ((MO.getType()) != MachineOperand::MO_Immediate)
455         return true;
456       O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
457       return false;
458     case 'd': // decimal const int
459       if ((MO.getType()) != MachineOperand::MO_Immediate)
460         return true;
461       O << MO.getImm();
462       return false;
463     case 'm': // decimal const int minus 1
464       if ((MO.getType()) != MachineOperand::MO_Immediate)
465         return true;
466       O << MO.getImm() - 1;
467       return false;
468     case 'z': {
469       // $0 if zero, regular printing otherwise
470       if (MO.getType() != MachineOperand::MO_Immediate)
471         return true;
472       int64_t Val = MO.getImm();
473       if (Val)
474         O << Val;
475       else
476         O << "$0";
477       return false;
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         // Endianess 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   int Offset = 0;
542   // Currently we are expecting either no ExtraCode or 'D'
543   if (ExtraCode) {
544     if (ExtraCode[0] == 'D')
545       Offset = 4;
546     else
547       return true; // Unknown modifier.
548   }
549
550   const MachineOperand &MO = MI->getOperand(OpNum);
551   assert(MO.isReg() && "unexpected inline asm memory operand");
552   O << Offset << "($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
553
554   return false;
555 }
556
557 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
558                                   raw_ostream &O) {
559   const DataLayout *DL = TM.getDataLayout();
560   const MachineOperand &MO = MI->getOperand(opNum);
561   bool closeP = false;
562
563   if (MO.getTargetFlags())
564     closeP = true;
565
566   switch(MO.getTargetFlags()) {
567   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
568   case MipsII::MO_GOT_CALL: O << "%call16("; break;
569   case MipsII::MO_GOT:      O << "%got(";    break;
570   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
571   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
572   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
573   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
574   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
575   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
576   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
577   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
578   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
579   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
580   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
581   }
582
583   switch (MO.getType()) {
584     case MachineOperand::MO_Register:
585       O << '$'
586         << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
587       break;
588
589     case MachineOperand::MO_Immediate:
590       O << MO.getImm();
591       break;
592
593     case MachineOperand::MO_MachineBasicBlock:
594       O << *MO.getMBB()->getSymbol();
595       return;
596
597     case MachineOperand::MO_GlobalAddress:
598       O << *getSymbol(MO.getGlobal());
599       break;
600
601     case MachineOperand::MO_BlockAddress: {
602       MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
603       O << BA->getName();
604       break;
605     }
606
607     case MachineOperand::MO_ConstantPoolIndex:
608       O << DL->getPrivateGlobalPrefix() << "CPI"
609         << getFunctionNumber() << "_" << MO.getIndex();
610       if (MO.getOffset())
611         O << "+" << MO.getOffset();
612       break;
613
614     default:
615       llvm_unreachable("<unknown operand type>");
616   }
617
618   if (closeP) O << ")";
619 }
620
621 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
622                                       raw_ostream &O) {
623   const MachineOperand &MO = MI->getOperand(opNum);
624   if (MO.isImm())
625     O << (unsigned short int)MO.getImm();
626   else
627     printOperand(MI, opNum, O);
628 }
629
630 void MipsAsmPrinter::printUnsignedImm8(const MachineInstr *MI, int opNum,
631                                        raw_ostream &O) {
632   const MachineOperand &MO = MI->getOperand(opNum);
633   if (MO.isImm())
634     O << (unsigned short int)(unsigned char)MO.getImm();
635   else
636     printOperand(MI, opNum, O);
637 }
638
639 void MipsAsmPrinter::
640 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
641   // Load/Store memory operands -- imm($reg)
642   // If PIC target the target is loaded as the
643   // pattern lw $25,%call16($28)
644   printOperand(MI, opNum+1, O);
645   O << "(";
646   printOperand(MI, opNum, O);
647   O << ")";
648 }
649
650 void MipsAsmPrinter::
651 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
652   // when using stack locations for not load/store instructions
653   // print the same way as all normal 3 operand instructions.
654   printOperand(MI, opNum, O);
655   O << ", ";
656   printOperand(MI, opNum+1, O);
657   return;
658 }
659
660 void MipsAsmPrinter::
661 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
662                 const char *Modifier) {
663   const MachineOperand &MO = MI->getOperand(opNum);
664   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
665 }
666
667 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
668   // TODO: Need to add -mabicalls and -mno-abicalls flags.
669   // Currently we assume that -mabicalls is the default.
670   bool IsABICalls = true;
671   if (IsABICalls) {
672     getTargetStreamer().emitDirectiveAbiCalls();
673     Reloc::Model RM = Subtarget->getRelocationModel();
674     // FIXME: This condition should be a lot more complicated that it is here.
675     //        Ideally it should test for properties of the ABI and not the ABI
676     //        itself.
677     //        For the moment, I'm only correcting enough to make MIPS-IV work.
678     if (RM == Reloc::Static && !Subtarget->isABI_N64())
679       getTargetStreamer().emitDirectiveOptionPic0();
680   }
681
682   // Tell the assembler which ABI we are using
683   std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
684   OutStreamer.SwitchSection(OutContext.getELFSection(
685       SectionName, ELF::SHT_PROGBITS, 0, SectionKind::getDataRel()));
686
687   // NaN: At the moment we only support:
688   // 1. .nan legacy (default)
689   // 2. .nan 2008
690   Subtarget->isNaN2008() ? getTargetStreamer().emitDirectiveNaN2008()
691     : getTargetStreamer().emitDirectiveNaNLegacy();
692
693   // TODO: handle O64 ABI
694
695   if (Subtarget->isABI_EABI()) {
696     if (Subtarget->isGP32bit())
697       OutStreamer.SwitchSection(
698           OutContext.getELFSection(".gcc_compiled_long32", ELF::SHT_PROGBITS, 0,
699                                    SectionKind::getDataRel()));
700     else
701       OutStreamer.SwitchSection(
702           OutContext.getELFSection(".gcc_compiled_long64", ELF::SHT_PROGBITS, 0,
703                                    SectionKind::getDataRel()));
704   }
705   getTargetStreamer().updateABIInfo(*Subtarget);
706   getTargetStreamer().emitDirectiveModuleFP(
707       getTargetStreamer().getABIFlagsSection().FpABI, Subtarget->isABI_O32());
708 }
709
710 void MipsAsmPrinter::EmitJal(MCSymbol *Symbol) {
711   MCInst I;
712   I.setOpcode(Mips::JAL);
713   I.addOperand(
714       MCOperand::CreateExpr(MCSymbolRefExpr::Create(Symbol, OutContext)));
715   OutStreamer.EmitInstruction(I, getSubtargetInfo());
716 }
717
718 void MipsAsmPrinter::EmitInstrReg(unsigned Opcode, unsigned Reg) {
719   MCInst I;
720   I.setOpcode(Opcode);
721   I.addOperand(MCOperand::CreateReg(Reg));
722   OutStreamer.EmitInstruction(I, getSubtargetInfo());
723 }
724
725 void MipsAsmPrinter::EmitInstrRegReg(unsigned Opcode, unsigned Reg1,
726                                      unsigned Reg2) {
727   MCInst I;
728   //
729   // Because of the current td files for Mips32, the operands for MTC1
730   // appear backwards from their normal assembly order. It's not a trivial
731   // change to fix this in the td file so we adjust for it here.
732   //
733   if (Opcode == Mips::MTC1) {
734     unsigned Temp = Reg1;
735     Reg1 = Reg2;
736     Reg2 = Temp;
737   }
738   I.setOpcode(Opcode);
739   I.addOperand(MCOperand::CreateReg(Reg1));
740   I.addOperand(MCOperand::CreateReg(Reg2));
741   OutStreamer.EmitInstruction(I, getSubtargetInfo());
742 }
743
744 void MipsAsmPrinter::EmitInstrRegRegReg(unsigned Opcode, unsigned Reg1,
745                                         unsigned Reg2, unsigned Reg3) {
746   MCInst I;
747   I.setOpcode(Opcode);
748   I.addOperand(MCOperand::CreateReg(Reg1));
749   I.addOperand(MCOperand::CreateReg(Reg2));
750   I.addOperand(MCOperand::CreateReg(Reg3));
751   OutStreamer.EmitInstruction(I, getSubtargetInfo());
752 }
753
754 void MipsAsmPrinter::EmitMovFPIntPair(unsigned MovOpc, unsigned Reg1,
755                                       unsigned Reg2, unsigned FPReg1,
756                                       unsigned FPReg2, bool LE) {
757   if (!LE) {
758     unsigned temp = Reg1;
759     Reg1 = Reg2;
760     Reg2 = temp;
761   }
762   EmitInstrRegReg(MovOpc, Reg1, FPReg1);
763   EmitInstrRegReg(MovOpc, Reg2, FPReg2);
764 }
765
766 void MipsAsmPrinter::EmitSwapFPIntParams(Mips16HardFloatInfo::FPParamVariant PV,
767                                          bool LE, bool ToFP) {
768   using namespace Mips16HardFloatInfo;
769   unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
770   switch (PV) {
771   case FSig:
772     EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
773     break;
774   case FFSig:
775     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
776     break;
777   case FDSig:
778     EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
779     EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
780     break;
781   case DSig:
782     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
783     break;
784   case DDSig:
785     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
786     EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
787     break;
788   case DFSig:
789     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
790     EmitInstrRegReg(MovOpc, Mips::A2, Mips::F14);
791     break;
792   case NoSig:
793     return;
794   }
795 }
796
797 void
798 MipsAsmPrinter::EmitSwapFPIntRetval(Mips16HardFloatInfo::FPReturnVariant RV,
799                                     bool LE) {
800   using namespace Mips16HardFloatInfo;
801   unsigned MovOpc = Mips::MFC1;
802   switch (RV) {
803   case FRet:
804     EmitInstrRegReg(MovOpc, Mips::V0, Mips::F0);
805     break;
806   case DRet:
807     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
808     break;
809   case CFRet:
810     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
811     break;
812   case CDRet:
813     EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
814     EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
815     break;
816   case NoFPRet:
817     break;
818   }
819 }
820
821 void MipsAsmPrinter::EmitFPCallStub(
822     const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
823   MCSymbol *MSymbol = OutContext.GetOrCreateSymbol(StringRef(Symbol));
824   using namespace Mips16HardFloatInfo;
825   bool LE = Subtarget->isLittle();
826   //
827   // .global xxxx
828   //
829   OutStreamer.EmitSymbolAttribute(MSymbol, MCSA_Global);
830   const char *RetType;
831   //
832   // make the comment field identifying the return and parameter
833   // types of the floating point stub
834   // # Stub function to call rettype xxxx (params)
835   //
836   switch (Signature->RetSig) {
837   case FRet:
838     RetType = "float";
839     break;
840   case DRet:
841     RetType = "double";
842     break;
843   case CFRet:
844     RetType = "complex";
845     break;
846   case CDRet:
847     RetType = "double complex";
848     break;
849   case NoFPRet:
850     RetType = "";
851     break;
852   }
853   const char *Parms;
854   switch (Signature->ParamSig) {
855   case FSig:
856     Parms = "float";
857     break;
858   case FFSig:
859     Parms = "float, float";
860     break;
861   case FDSig:
862     Parms = "float, double";
863     break;
864   case DSig:
865     Parms = "double";
866     break;
867   case DDSig:
868     Parms = "double, double";
869     break;
870   case DFSig:
871     Parms = "double, float";
872     break;
873   case NoSig:
874     Parms = "";
875     break;
876   }
877   OutStreamer.AddComment("\t# Stub function to call " + Twine(RetType) + " " +
878                          Twine(Symbol) + " (" + Twine(Parms) + ")");
879   //
880   // probably not necessary but we save and restore the current section state
881   //
882   OutStreamer.PushSection();
883   //
884   // .section mips16.call.fpxxxx,"ax",@progbits
885   //
886   const MCSectionELF *M = OutContext.getELFSection(
887       ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
888       ELF::SHF_ALLOC | ELF::SHF_EXECINSTR, SectionKind::getText());
889   OutStreamer.SwitchSection(M, nullptr);
890   //
891   // .align 2
892   //
893   OutStreamer.EmitValueToAlignment(4);
894   MipsTargetStreamer &TS = getTargetStreamer();
895   //
896   // .set nomips16
897   // .set nomicromips
898   //
899   TS.emitDirectiveSetNoMips16();
900   TS.emitDirectiveSetNoMicroMips();
901   //
902   // .ent __call_stub_fp_xxxx
903   // .type  __call_stub_fp_xxxx,@function
904   //  __call_stub_fp_xxxx:
905   //
906   std::string x = "__call_stub_fp_" + std::string(Symbol);
907   MCSymbol *Stub = OutContext.GetOrCreateSymbol(StringRef(x));
908   TS.emitDirectiveEnt(*Stub);
909   MCSymbol *MType =
910       OutContext.GetOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
911   OutStreamer.EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
912   OutStreamer.EmitLabel(Stub);
913   //
914   // we just handle non pic for now. these function will not be
915   // called otherwise. when the full stub generation is moved here
916   // we need to deal with pic.
917   //
918   if (Subtarget->getRelocationModel() == Reloc::PIC_)
919     llvm_unreachable("should not be here if we are compiling pic");
920   TS.emitDirectiveSetReorder();
921   //
922   // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
923   // stubs without raw text but this current patch is for compiler generated
924   // functions and they all return some value.
925   // The calling sequence for non pic is different in that case and we need
926   // to implement %lo and %hi in order to handle the case of no return value
927   // See the corresponding method in Mips16HardFloat for details.
928   //
929   // mov the return address to S2.
930   // we have no stack space to store it and we are about to make another call.
931   // We need to make sure that the enclosing function knows to save S2
932   // This should have already been handled.
933   //
934   // Mov $18, $31
935
936   EmitInstrRegRegReg(Mips::ADDu, Mips::S2, Mips::RA, Mips::ZERO);
937
938   EmitSwapFPIntParams(Signature->ParamSig, LE, true);
939
940   // Jal xxxx
941   //
942   EmitJal(MSymbol);
943
944   // fix return values
945   EmitSwapFPIntRetval(Signature->RetSig, LE);
946   //
947   // do the return
948   // if (Signature->RetSig == NoFPRet)
949   //  llvm_unreachable("should not be any stubs here with no return value");
950   // else
951   EmitInstrReg(Mips::JR, Mips::S2);
952
953   MCSymbol *Tmp = OutContext.CreateTempSymbol();
954   OutStreamer.EmitLabel(Tmp);
955   const MCSymbolRefExpr *E = MCSymbolRefExpr::Create(Stub, OutContext);
956   const MCSymbolRefExpr *T = MCSymbolRefExpr::Create(Tmp, OutContext);
957   const MCExpr *T_min_E = MCBinaryExpr::CreateSub(T, E, OutContext);
958   OutStreamer.EmitELFSize(Stub, T_min_E);
959   TS.emitDirectiveEnd(x);
960   OutStreamer.PopSection();
961 }
962
963 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
964   // Emit needed stubs
965   //
966   for (std::map<
967            const char *,
968            const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
969            it = StubsNeeded.begin();
970        it != StubsNeeded.end(); ++it) {
971     const char *Symbol = it->first;
972     const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
973     EmitFPCallStub(Symbol, Signature);
974   }
975   // return to the text section
976   OutStreamer.SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
977 }
978
979 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
980                                            raw_ostream &OS) {
981   // TODO: implement
982 }
983
984 // Align all targets of indirect branches on bundle size.  Used only if target
985 // is NaCl.
986 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
987   // Align all blocks that are jumped to through jump table.
988   if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
989     const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
990     for (unsigned I = 0; I < JT.size(); ++I) {
991       const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
992
993       for (unsigned J = 0; J < MBBs.size(); ++J)
994         MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
995     }
996   }
997
998   // If basic block address is taken, block can be target of indirect branch.
999   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
1000                                  MBB != E; ++MBB) {
1001     if (MBB->hasAddressTaken())
1002       MBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1003   }
1004 }
1005
1006 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1007   return (Opcode == Mips::LONG_BRANCH_LUi
1008           || Opcode == Mips::LONG_BRANCH_ADDiu
1009           || Opcode == Mips::LONG_BRANCH_DADDiu);
1010 }
1011
1012 // Force static initialization.
1013 extern "C" void LLVMInitializeMipsAsmPrinter() {
1014   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
1015   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
1016   RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
1017   RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
1018 }