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