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