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