This patch changes a static_cast to dyn_cast
[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 #define DEBUG_TYPE "mips-asm-printer"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MCTargetDesc/MipsELFStreamer.h"
19 #include "Mips.h"
20 #include "MipsAsmPrinter.h"
21 #include "MipsInstrInfo.h"
22 #include "MipsMCInstLower.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/MachineMemOperand.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/InlineAsm.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCInst.h"
37 #include "llvm/MC/MCStreamer.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/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetOptions.h"
44
45 using namespace llvm;
46
47 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
48   MipsFI = MF.getInfo<MipsFunctionInfo>();
49   AsmPrinter::runOnMachineFunction(MF);
50   return true;
51 }
52
53 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
54   MCOp = MCInstLowering.LowerOperand(MO);
55   return MCOp.isValid();
56 }
57
58 #include "MipsGenMCPseudoLowering.inc"
59
60 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
61   if (MI->isDebugValue()) {
62     SmallString<128> Str;
63     raw_svector_ostream OS(Str);
64
65     PrintDebugValueComment(MI, OS);
66     return;
67   }
68
69   // Do any auto-generated pseudo lowerings.
70   if (emitPseudoExpansionLowering(OutStreamer, MI))
71     return;
72
73   MachineBasicBlock::const_instr_iterator I = MI;
74   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
75
76   do {
77     MCInst TmpInst0;
78     MCInstLowering.Lower(I++, TmpInst0);
79
80     OutStreamer.EmitInstruction(TmpInst0);
81   } while ((I != E) && I->isInsideBundle()); // Delay slot check
82 }
83
84 //===----------------------------------------------------------------------===//
85 //
86 //  Mips Asm Directives
87 //
88 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
89 //  Describe the stack frame.
90 //
91 //  -- Mask directives "(f)mask  bitmask, offset"
92 //  Tells the assembler which registers are saved and where.
93 //  bitmask - contain a little endian bitset indicating which registers are
94 //            saved on function prologue (e.g. with a 0x80000000 mask, the
95 //            assembler knows the register 31 (RA) is saved at prologue.
96 //  offset  - the position before stack pointer subtraction indicating where
97 //            the first saved register on prologue is located. (e.g. with a
98 //
99 //  Consider the following function prologue:
100 //
101 //    .frame  $fp,48,$ra
102 //    .mask   0xc0000000,-8
103 //       addiu $sp, $sp, -48
104 //       sw $ra, 40($sp)
105 //       sw $fp, 36($sp)
106 //
107 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
108 //    30 (FP) are saved at prologue. As the save order on prologue is from
109 //    left to right, RA is saved first. A -8 offset means that after the
110 //    stack pointer subtration, the first register in the mask (RA) will be
111 //    saved at address 48-8=40.
112 //
113 //===----------------------------------------------------------------------===//
114
115 //===----------------------------------------------------------------------===//
116 // Mask directives
117 //===----------------------------------------------------------------------===//
118
119 // Create a bitmask with all callee saved registers for CPU or Floating Point
120 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
121 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
122   // CPU and FPU Saved Registers Bitmasks
123   unsigned CPUBitmask = 0, FPUBitmask = 0;
124   int CPUTopSavedRegOff, FPUTopSavedRegOff;
125
126   // Set the CPU and FPU Bitmasks
127   const MachineFrameInfo *MFI = MF->getFrameInfo();
128   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
129   // size of stack area to which FP callee-saved regs are saved.
130   unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
131   unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
132   unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
133   bool HasAFGR64Reg = false;
134   unsigned CSFPRegsSize = 0;
135   unsigned i, e = CSI.size();
136
137   // Set FPU Bitmask.
138   for (i = 0; i != e; ++i) {
139     unsigned Reg = CSI[i].getReg();
140     if (Mips::CPURegsRegClass.contains(Reg))
141       break;
142
143     unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
144     if (Mips::AFGR64RegClass.contains(Reg)) {
145       FPUBitmask |= (3 << RegNum);
146       CSFPRegsSize += AFGR64RegSize;
147       HasAFGR64Reg = true;
148       continue;
149     }
150
151     FPUBitmask |= (1 << RegNum);
152     CSFPRegsSize += FGR32RegSize;
153   }
154
155   // Set CPU Bitmask.
156   for (; i != e; ++i) {
157     unsigned Reg = CSI[i].getReg();
158     unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
159     CPUBitmask |= (1 << RegNum);
160   }
161
162   // FP Regs are saved right below where the virtual frame pointer points to.
163   FPUTopSavedRegOff = FPUBitmask ?
164     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
165
166   // CPU Regs are saved below FP Regs.
167   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
168
169   // Print CPUBitmask
170   O << "\t.mask \t"; printHex32(CPUBitmask, O);
171   O << ',' << CPUTopSavedRegOff << '\n';
172
173   // Print FPUBitmask
174   O << "\t.fmask\t"; printHex32(FPUBitmask, O);
175   O << "," << FPUTopSavedRegOff << '\n';
176 }
177
178 // Print a 32 bit hex number with all numbers.
179 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
180   O << "0x";
181   for (int i = 7; i >= 0; i--)
182     O.write_hex((Value & (0xF << (i*4))) >> (i*4));
183 }
184
185 //===----------------------------------------------------------------------===//
186 // Frame and Set directives
187 //===----------------------------------------------------------------------===//
188
189 /// Frame Directive
190 void MipsAsmPrinter::emitFrameDirective() {
191   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
192
193   unsigned stackReg  = RI.getFrameRegister(*MF);
194   unsigned returnReg = RI.getRARegister();
195   unsigned stackSize = MF->getFrameInfo()->getStackSize();
196
197   if (OutStreamer.hasRawTextSupport())
198     OutStreamer.EmitRawText("\t.frame\t$" +
199            StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
200            "," + Twine(stackSize) + ",$" +
201            StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
202 }
203
204 /// Emit Set directives.
205 const char *MipsAsmPrinter::getCurrentABIString() const {
206   switch (Subtarget->getTargetABI()) {
207   case MipsSubtarget::O32:  return "abi32";
208   case MipsSubtarget::N32:  return "abiN32";
209   case MipsSubtarget::N64:  return "abi64";
210   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
211   default: llvm_unreachable("Unknown Mips ABI");
212   }
213 }
214
215 void MipsAsmPrinter::EmitFunctionEntryLabel() {
216   if (OutStreamer.hasRawTextSupport()) {
217     if (Subtarget->inMips16Mode())
218       OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
219     else
220       OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
221     // leave out until FSF available gas has micromips changes
222     // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
223     OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
224   }
225   OutStreamer.EmitLabel(CurrentFnSym);
226 }
227
228 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
229 /// the first basic block in the function.
230 void MipsAsmPrinter::EmitFunctionBodyStart() {
231   MCInstLowering.Initialize(Mang, &MF->getContext());
232
233   emitFrameDirective();
234
235   if (OutStreamer.hasRawTextSupport()) {
236     SmallString<128> Str;
237     raw_svector_ostream OS(Str);
238     printSavedRegsBitmask(OS);
239     OutStreamer.EmitRawText(OS.str());
240
241     OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
242     OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
243     OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
244   }
245 }
246
247 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
248 /// the last basic block in the function.
249 void MipsAsmPrinter::EmitFunctionBodyEnd() {
250   // There are instruction for this macros, but they must
251   // always be at the function end, and we can't emit and
252   // break with BB logic.
253   if (OutStreamer.hasRawTextSupport()) {
254     OutStreamer.EmitRawText(StringRef("\t.set\tat"));
255     OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
256     OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
257     OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
258   }
259 }
260
261 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
262 /// exactly one predecessor and the control transfer mechanism between
263 /// the predecessor and this block is a fall-through.
264 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
265                                                        MBB) const {
266   // The predecessor has to be immediately before this block.
267   const MachineBasicBlock *Pred = *MBB->pred_begin();
268
269   // If the predecessor is a switch statement, assume a jump table
270   // implementation, so it is not a fall through.
271   if (const BasicBlock *bb = Pred->getBasicBlock())
272     if (isa<SwitchInst>(bb->getTerminator()))
273       return false;
274
275   // If this is a landing pad, it isn't a fall through.  If it has no preds,
276   // then nothing falls through to it.
277   if (MBB->isLandingPad() || MBB->pred_empty())
278     return false;
279
280   // If there isn't exactly one predecessor, it can't be a fall through.
281   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
282   ++PI2;
283
284   if (PI2 != MBB->pred_end())
285     return false;
286
287   // The predecessor has to be immediately before this block.
288   if (!Pred->isLayoutSuccessor(MBB))
289     return false;
290
291   // If the block is completely empty, then it definitely does fall through.
292   if (Pred->empty())
293     return true;
294
295   // Otherwise, check the last instruction.
296   // Check if the last terminator is an unconditional branch.
297   MachineBasicBlock::const_iterator I = Pred->end();
298   while (I != Pred->begin() && !(--I)->isTerminator()) ;
299
300   return !I->isBarrier();
301 }
302
303 // Print out an operand for an inline asm expression.
304 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
305                                      unsigned AsmVariant,const char *ExtraCode,
306                                      raw_ostream &O) {
307   // Does this asm operand have a single letter operand modifier?
308   if (ExtraCode && ExtraCode[0]) {
309     if (ExtraCode[1] != 0) return true; // Unknown modifier.
310
311     const MachineOperand &MO = MI->getOperand(OpNum);
312     switch (ExtraCode[0]) {
313     default:
314       // See if this is a generic print operand
315       return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
316     case 'X': // hex const int
317       if ((MO.getType()) != MachineOperand::MO_Immediate)
318         return true;
319       O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
320       return false;
321     case 'x': // hex const int (low 16 bits)
322       if ((MO.getType()) != MachineOperand::MO_Immediate)
323         return true;
324       O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
325       return false;
326     case 'd': // decimal const int
327       if ((MO.getType()) != MachineOperand::MO_Immediate)
328         return true;
329       O << MO.getImm();
330       return false;
331     case 'm': // decimal const int minus 1
332       if ((MO.getType()) != MachineOperand::MO_Immediate)
333         return true;
334       O << MO.getImm() - 1;
335       return false;
336     case 'z': {
337       // $0 if zero, regular printing otherwise
338       if (MO.getType() != MachineOperand::MO_Immediate)
339         return true;
340       int64_t Val = MO.getImm();
341       if (Val)
342         O << Val;
343       else
344         O << "$0";
345       return false;
346     }
347     case 'D': // Second part of a double word register operand
348     case 'L': // Low order register of a double word register operand
349     case 'M': // High order register of a double word register operand
350     {
351       if (OpNum == 0)
352         return true;
353       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
354       if (!FlagsOP.isImm())
355         return true;
356       unsigned Flags = FlagsOP.getImm();
357       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
358       // Number of registers represented by this operand. We are looking
359       // for 2 for 32 bit mode and 1 for 64 bit mode.
360       if (NumVals != 2) {
361         if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
362           unsigned Reg = MO.getReg();
363           O << '$' << MipsInstPrinter::getRegisterName(Reg);
364           return false;
365         }
366         return true;
367       }
368
369       unsigned RegOp = OpNum;
370       if (!Subtarget->isGP64bit()){
371         // Endianess reverses which register holds the high or low value
372         // between M and L.
373         switch(ExtraCode[0]) {
374         case 'M':
375           RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
376           break;
377         case 'L':
378           RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
379           break;
380         case 'D': // Always the second part
381           RegOp = OpNum + 1;
382         }
383         if (RegOp >= MI->getNumOperands())
384           return true;
385         const MachineOperand &MO = MI->getOperand(RegOp);
386         if (!MO.isReg())
387           return true;
388         unsigned Reg = MO.getReg();
389         O << '$' << MipsInstPrinter::getRegisterName(Reg);
390         return false;
391       }
392     }
393     }
394   }
395
396   printOperand(MI, OpNum, O);
397   return false;
398 }
399
400 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
401                                            unsigned OpNum, unsigned AsmVariant,
402                                            const char *ExtraCode,
403                                            raw_ostream &O) {
404   if (ExtraCode && ExtraCode[0])
405     return true; // Unknown modifier.
406
407   const MachineOperand &MO = MI->getOperand(OpNum);
408   assert(MO.isReg() && "unexpected inline asm memory operand");
409   O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
410
411   return false;
412 }
413
414 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
415                                   raw_ostream &O) {
416   const MachineOperand &MO = MI->getOperand(opNum);
417   bool closeP = false;
418
419   if (MO.getTargetFlags())
420     closeP = true;
421
422   switch(MO.getTargetFlags()) {
423   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
424   case MipsII::MO_GOT_CALL: O << "%call16("; break;
425   case MipsII::MO_GOT:      O << "%got(";    break;
426   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
427   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
428   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
429   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
430   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
431   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
432   case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
433   case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
434   case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
435   case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
436   case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
437   }
438
439   switch (MO.getType()) {
440     case MachineOperand::MO_Register:
441       O << '$'
442         << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
443       break;
444
445     case MachineOperand::MO_Immediate:
446       O << MO.getImm();
447       break;
448
449     case MachineOperand::MO_MachineBasicBlock:
450       O << *MO.getMBB()->getSymbol();
451       return;
452
453     case MachineOperand::MO_GlobalAddress:
454       O << *Mang->getSymbol(MO.getGlobal());
455       break;
456
457     case MachineOperand::MO_BlockAddress: {
458       MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
459       O << BA->getName();
460       break;
461     }
462
463     case MachineOperand::MO_ExternalSymbol:
464       O << *GetExternalSymbolSymbol(MO.getSymbolName());
465       break;
466
467     case MachineOperand::MO_JumpTableIndex:
468       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
469         << '_' << MO.getIndex();
470       break;
471
472     case MachineOperand::MO_ConstantPoolIndex:
473       O << MAI->getPrivateGlobalPrefix() << "CPI"
474         << getFunctionNumber() << "_" << MO.getIndex();
475       if (MO.getOffset())
476         O << "+" << MO.getOffset();
477       break;
478
479     default:
480       llvm_unreachable("<unknown operand type>");
481   }
482
483   if (closeP) O << ")";
484 }
485
486 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
487                                       raw_ostream &O) {
488   const MachineOperand &MO = MI->getOperand(opNum);
489   if (MO.isImm())
490     O << (unsigned short int)MO.getImm();
491   else
492     printOperand(MI, opNum, O);
493 }
494
495 void MipsAsmPrinter::
496 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
497   // Load/Store memory operands -- imm($reg)
498   // If PIC target the target is loaded as the
499   // pattern lw $25,%call16($28)
500   printOperand(MI, opNum+1, O);
501   O << "(";
502   printOperand(MI, opNum, O);
503   O << ")";
504 }
505
506 void MipsAsmPrinter::
507 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
508   // when using stack locations for not load/store instructions
509   // print the same way as all normal 3 operand instructions.
510   printOperand(MI, opNum, O);
511   O << ", ";
512   printOperand(MI, opNum+1, O);
513   return;
514 }
515
516 void MipsAsmPrinter::
517 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
518                 const char *Modifier) {
519   const MachineOperand &MO = MI->getOperand(opNum);
520   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
521 }
522
523 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
524   // FIXME: Use SwitchSection.
525
526   // Tell the assembler which ABI we are using
527   if (OutStreamer.hasRawTextSupport())
528     OutStreamer.EmitRawText("\t.section .mdebug." +
529                             Twine(getCurrentABIString()));
530
531   // TODO: handle O64 ABI
532   if (OutStreamer.hasRawTextSupport()) {
533     if (Subtarget->isABI_EABI()) {
534       if (Subtarget->isGP32bit())
535         OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
536       else
537         OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
538     }
539   }
540
541   // return to previous section
542   if (OutStreamer.hasRawTextSupport())
543     OutStreamer.EmitRawText(StringRef("\t.previous"));
544
545 }
546
547 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
548
549   if (OutStreamer.hasRawTextSupport()) return;
550
551   // Emit Mips ELF register info
552   Subtarget->getMReginfo().emitMipsReginfoSectionCG(
553              OutStreamer, getObjFileLowering(), *Subtarget);
554   if (MipsELFStreamer *MES = dyn_cast<MipsELFStreamer>(&OutStreamer))
555     MES->emitELFHeaderFlagsCG(*Subtarget);
556 }
557
558 MachineLocation
559 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
560   // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
561   assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
562   assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
563          "Unexpected MachineOperand types");
564   return MachineLocation(MI->getOperand(0).getReg(),
565                          MI->getOperand(1).getImm());
566 }
567
568 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
569                                            raw_ostream &OS) {
570   // TODO: implement
571 }
572
573 // Force static initialization.
574 extern "C" void LLVMInitializeMipsAsmPrinter() {
575   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
576   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
577   RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
578   RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
579 }