Expand .cprestore directive to multiple instructions if the offset does not fit
[oota-llvm.git] / lib / Target / Mips / MipsAsmPrinter.cpp
1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
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 #define DEBUG_TYPE "mips-asm-printer"
16 #include "Mips.h"
17 #include "MipsAsmPrinter.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsMCInstLower.h"
21 #include "InstPrinter/MipsInstPrinter.h"
22 #include "MCTargetDesc/MipsBaseInfo.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45
46 using namespace llvm;
47
48 static bool isUnalignedLoadStore(unsigned Opc) {
49   return Opc == Mips::ULW    || Opc == Mips::ULH    || Opc == Mips::ULHu ||
50          Opc == Mips::USW    || Opc == Mips::USH    ||
51          Opc == Mips::ULW_P8 || Opc == Mips::ULH_P8 || Opc == Mips::ULHu_P8 ||
52          Opc == Mips::USW_P8 || Opc == Mips::USH_P8;
53 }
54
55 static bool isDirective(unsigned Opc) {
56   return Opc == Mips::MACRO   || Opc == Mips::NOMACRO ||
57          Opc == Mips::REORDER || Opc == Mips::NOREORDER ||
58          Opc == Mips::ATMACRO || Opc == Mips::NOAT;
59 }
60
61 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
62   SmallString<128> Str;
63   raw_svector_ostream OS(Str);
64
65   if (MI->isDebugValue()) {
66     PrintDebugValueComment(MI, OS);
67     return;
68   }
69
70   MipsMCInstLower MCInstLowering(Mang, *MF, *this);
71   unsigned Opc = MI->getOpcode();
72   MCInst TmpInst0;
73   SmallVector<MCInst, 4> MCInsts;
74   MCInstLowering.Lower(MI, TmpInst0);
75
76   if (!OutStreamer.hasRawTextSupport() && isDirective(Opc))
77     return;
78
79   // Enclose unaligned load or store with .macro & .nomacro directives.
80   if (isUnalignedLoadStore(Opc)) {
81     if (OutStreamer.hasRawTextSupport()) {
82       MCInst Directive;
83       Directive.setOpcode(Mips::MACRO);
84       OutStreamer.EmitInstruction(Directive);
85       OutStreamer.EmitInstruction(TmpInst0);
86       Directive.setOpcode(Mips::NOMACRO);
87       OutStreamer.EmitInstruction(Directive);
88     } else {
89       MCInstLowering.LowerUnalignedLoadStore(MI, MCInsts);
90       for (SmallVector<MCInst, 4>::iterator I = MCInsts.begin(); I
91           != MCInsts.end(); ++I)
92         OutStreamer.EmitInstruction(*I);
93     }
94     return;
95   }
96
97   if (!OutStreamer.hasRawTextSupport()) {
98     // Lower CPLOAD and CPRESTORE
99     if (Opc == Mips::CPLOAD)
100       MCInstLowering.LowerCPLOAD(MI, MCInsts);
101     else if (Opc == Mips::CPRESTORE)
102       MCInstLowering.LowerCPRESTORE(MI, MCInsts);
103     
104     if (!MCInsts.empty()) {
105       for (SmallVector<MCInst, 4>::iterator I = MCInsts.begin();
106            I != MCInsts.end(); ++I)
107         OutStreamer.EmitInstruction(*I);
108       return;
109     }
110   }
111
112   OutStreamer.EmitInstruction(TmpInst0);
113 }
114
115 //===----------------------------------------------------------------------===//
116 //
117 //  Mips Asm Directives
118 //
119 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
120 //  Describe the stack frame.
121 //
122 //  -- Mask directives "(f)mask  bitmask, offset"
123 //  Tells the assembler which registers are saved and where.
124 //  bitmask - contain a little endian bitset indicating which registers are
125 //            saved on function prologue (e.g. with a 0x80000000 mask, the
126 //            assembler knows the register 31 (RA) is saved at prologue.
127 //  offset  - the position before stack pointer subtraction indicating where
128 //            the first saved register on prologue is located. (e.g. with a
129 //
130 //  Consider the following function prologue:
131 //
132 //    .frame  $fp,48,$ra
133 //    .mask   0xc0000000,-8
134 //       addiu $sp, $sp, -48
135 //       sw $ra, 40($sp)
136 //       sw $fp, 36($sp)
137 //
138 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
139 //    30 (FP) are saved at prologue. As the save order on prologue is from
140 //    left to right, RA is saved first. A -8 offset means that after the
141 //    stack pointer subtration, the first register in the mask (RA) will be
142 //    saved at address 48-8=40.
143 //
144 //===----------------------------------------------------------------------===//
145
146 //===----------------------------------------------------------------------===//
147 // Mask directives
148 //===----------------------------------------------------------------------===//
149
150 // Create a bitmask with all callee saved registers for CPU or Floating Point
151 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
152 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
153   // CPU and FPU Saved Registers Bitmasks
154   unsigned CPUBitmask = 0, FPUBitmask = 0;
155   int CPUTopSavedRegOff, FPUTopSavedRegOff;
156
157   // Set the CPU and FPU Bitmasks
158   const MachineFrameInfo *MFI = MF->getFrameInfo();
159   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
160   // size of stack area to which FP callee-saved regs are saved.
161   unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
162   unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
163   unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
164   bool HasAFGR64Reg = false;
165   unsigned CSFPRegsSize = 0;
166   unsigned i, e = CSI.size();
167
168   // Set FPU Bitmask.
169   for (i = 0; i != e; ++i) {
170     unsigned Reg = CSI[i].getReg();
171     if (Mips::CPURegsRegisterClass->contains(Reg))
172       break;
173
174     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
175     if (Mips::AFGR64RegisterClass->contains(Reg)) {
176       FPUBitmask |= (3 << RegNum);
177       CSFPRegsSize += AFGR64RegSize;
178       HasAFGR64Reg = true;
179       continue;
180     }
181
182     FPUBitmask |= (1 << RegNum);
183     CSFPRegsSize += FGR32RegSize;
184   }
185
186   // Set CPU Bitmask.
187   for (; i != e; ++i) {
188     unsigned Reg = CSI[i].getReg();
189     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
190     CPUBitmask |= (1 << RegNum);
191   }
192
193   // FP Regs are saved right below where the virtual frame pointer points to.
194   FPUTopSavedRegOff = FPUBitmask ?
195     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
196
197   // CPU Regs are saved below FP Regs.
198   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
199
200   // Print CPUBitmask
201   O << "\t.mask \t"; printHex32(CPUBitmask, O);
202   O << ',' << CPUTopSavedRegOff << '\n';
203
204   // Print FPUBitmask
205   O << "\t.fmask\t"; printHex32(FPUBitmask, O);
206   O << "," << FPUTopSavedRegOff << '\n';
207 }
208
209 // Print a 32 bit hex number with all numbers.
210 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
211   O << "0x";
212   for (int i = 7; i >= 0; i--)
213     O.write_hex((Value & (0xF << (i*4))) >> (i*4));
214 }
215
216 //===----------------------------------------------------------------------===//
217 // Frame and Set directives
218 //===----------------------------------------------------------------------===//
219
220 /// Frame Directive
221 void MipsAsmPrinter::emitFrameDirective() {
222   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
223
224   unsigned stackReg  = RI.getFrameRegister(*MF);
225   unsigned returnReg = RI.getRARegister();
226   unsigned stackSize = MF->getFrameInfo()->getStackSize();
227
228   if (OutStreamer.hasRawTextSupport()) 
229     OutStreamer.EmitRawText("\t.frame\t$" +
230            StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
231            "," + Twine(stackSize) + ",$" +
232            StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
233 }
234
235 /// Emit Set directives.
236 const char *MipsAsmPrinter::getCurrentABIString() const {
237   switch (Subtarget->getTargetABI()) {
238   case MipsSubtarget::O32:  return "abi32";
239   case MipsSubtarget::N32:  return "abiN32";
240   case MipsSubtarget::N64:  return "abi64";
241   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
242   default: break;
243   }
244
245   llvm_unreachable("Unknown Mips ABI");
246   return NULL;
247 }
248
249 void MipsAsmPrinter::EmitFunctionEntryLabel() {
250   if (OutStreamer.hasRawTextSupport()) 
251     OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
252   OutStreamer.EmitLabel(CurrentFnSym);
253 }
254
255 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
256 /// the first basic block in the function.
257 void MipsAsmPrinter::EmitFunctionBodyStart() {
258   emitFrameDirective();
259
260   if (OutStreamer.hasRawTextSupport()) {
261     SmallString<128> Str;
262     raw_svector_ostream OS(Str);
263     printSavedRegsBitmask(OS);
264     OutStreamer.EmitRawText(OS.str());
265   }
266 }
267
268 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
269 /// the last basic block in the function.
270 void MipsAsmPrinter::EmitFunctionBodyEnd() {
271   // There are instruction for this macros, but they must
272   // always be at the function end, and we can't emit and
273   // break with BB logic.
274   if (OutStreamer.hasRawTextSupport()) {
275     OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
276     OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
277     OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
278   }
279 }
280
281 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
282 /// exactly one predecessor and the control transfer mechanism between
283 /// the predecessor and this block is a fall-through.
284 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
285                                                        MBB) const {
286   // The predecessor has to be immediately before this block.
287   const MachineBasicBlock *Pred = *MBB->pred_begin();
288
289   // If the predecessor is a switch statement, assume a jump table
290   // implementation, so it is not a fall through.
291   if (const BasicBlock *bb = Pred->getBasicBlock())
292     if (isa<SwitchInst>(bb->getTerminator()))
293       return false;
294
295   // If this is a landing pad, it isn't a fall through.  If it has no preds,
296   // then nothing falls through to it.
297   if (MBB->isLandingPad() || MBB->pred_empty())
298     return false;
299
300   // If there isn't exactly one predecessor, it can't be a fall through.
301   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
302   ++PI2;
303  
304   if (PI2 != MBB->pred_end())
305     return false;  
306
307   // The predecessor has to be immediately before this block.
308   if (!Pred->isLayoutSuccessor(MBB))
309     return false;
310    
311   // If the block is completely empty, then it definitely does fall through.
312   if (Pred->empty())
313     return true;
314   
315   // Otherwise, check the last instruction.
316   // Check if the last terminator is an unconditional branch.
317   MachineBasicBlock::const_iterator I = Pred->end();
318   while (I != Pred->begin() && !(--I)->isTerminator()) ;
319
320   return !I->isBarrier();
321 }
322
323 // Print out an operand for an inline asm expression.
324 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
325                                      unsigned AsmVariant,const char *ExtraCode,
326                                      raw_ostream &O) {
327   // Does this asm operand have a single letter operand modifier?
328   if (ExtraCode && ExtraCode[0])
329     return true; // Unknown modifier.
330
331   printOperand(MI, OpNo, O);
332   return false;
333 }
334
335 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
336                                            unsigned OpNum, unsigned AsmVariant,
337                                            const char *ExtraCode,
338                                            raw_ostream &O) {
339   if (ExtraCode && ExtraCode[0])
340      return true; // Unknown modifier.
341    
342   const MachineOperand &MO = MI->getOperand(OpNum);
343   assert(MO.isReg() && "unexpected inline asm memory operand");
344   O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
345   return false;
346 }
347
348 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
349                                   raw_ostream &O) {
350   const MachineOperand &MO = MI->getOperand(opNum);
351   bool closeP = false;
352
353   if (MO.getTargetFlags())
354     closeP = true;
355
356   switch(MO.getTargetFlags()) {
357   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
358   case MipsII::MO_GOT_CALL: O << "%call16("; break;
359   case MipsII::MO_GOT:      O << "%got(";    break;
360   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
361   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
362   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
363   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
364   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
365   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
366   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
367   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
368   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
369   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
370   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
371   }
372
373   switch (MO.getType()) {
374     case MachineOperand::MO_Register:
375       O << '$'
376         << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
377       break;
378
379     case MachineOperand::MO_Immediate:
380       O << MO.getImm();
381       break;
382
383     case MachineOperand::MO_MachineBasicBlock:
384       O << *MO.getMBB()->getSymbol();
385       return;
386
387     case MachineOperand::MO_GlobalAddress:
388       O << *Mang->getSymbol(MO.getGlobal());
389       break;
390
391     case MachineOperand::MO_BlockAddress: {
392       MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
393       O << BA->getName();
394       break;
395     }
396
397     case MachineOperand::MO_ExternalSymbol:
398       O << *GetExternalSymbolSymbol(MO.getSymbolName());
399       break;
400
401     case MachineOperand::MO_JumpTableIndex:
402       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
403         << '_' << MO.getIndex();
404       break;
405
406     case MachineOperand::MO_ConstantPoolIndex:
407       O << MAI->getPrivateGlobalPrefix() << "CPI"
408         << getFunctionNumber() << "_" << MO.getIndex();
409       if (MO.getOffset())
410         O << "+" << MO.getOffset();
411       break;
412
413     default:
414       llvm_unreachable("<unknown operand type>");
415   }
416
417   if (closeP) O << ")";
418 }
419
420 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
421                                       raw_ostream &O) {
422   const MachineOperand &MO = MI->getOperand(opNum);
423   if (MO.isImm())
424     O << (unsigned short int)MO.getImm();
425   else
426     printOperand(MI, opNum, O);
427 }
428
429 void MipsAsmPrinter::
430 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
431   // Load/Store memory operands -- imm($reg)
432   // If PIC target the target is loaded as the
433   // pattern lw $25,%call16($28)
434   printOperand(MI, opNum+1, O);
435   O << "(";
436   printOperand(MI, opNum, O);
437   O << ")";
438 }
439
440 void MipsAsmPrinter::
441 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
442   // when using stack locations for not load/store instructions
443   // print the same way as all normal 3 operand instructions.
444   printOperand(MI, opNum, O);
445   O << ", ";
446   printOperand(MI, opNum+1, O);
447   return;
448 }
449
450 void MipsAsmPrinter::
451 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
452                 const char *Modifier) {
453   const MachineOperand& MO = MI->getOperand(opNum);
454   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
455 }
456
457 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
458   // FIXME: Use SwitchSection.
459
460   // Tell the assembler which ABI we are using
461   if (OutStreamer.hasRawTextSupport())
462     OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
463
464   // TODO: handle O64 ABI
465   if (OutStreamer.hasRawTextSupport()) {
466     if (Subtarget->isABI_EABI()) {
467       if (Subtarget->isGP32bit())
468         OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
469       else
470         OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
471     }
472   }
473
474   // return to previous section
475   if (OutStreamer.hasRawTextSupport())
476     OutStreamer.EmitRawText(StringRef("\t.previous"));
477 }
478
479 MachineLocation
480 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
481   // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
482   assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
483   assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
484          "Unexpected MachineOperand types");
485   return MachineLocation(MI->getOperand(0).getReg(),
486                          MI->getOperand(1).getImm());
487 }
488
489 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
490                                            raw_ostream &OS) {
491   // TODO: implement
492 }
493
494 // Force static initialization.
495 extern "C" void LLVMInitializeMipsAsmPrinter() {
496   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
497   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
498   RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
499   RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
500 }