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