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