Adding dllimport, dllexport and external weak linkage types.
[oota-llvm.git] / lib / Target / X86 / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86IntelAsmPrinter.h"
17 #include "X86TargetAsmInfo.h"
18 #include "X86.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetOptions.h"
25 using namespace llvm;
26
27 /// runOnMachineFunction - This uses the printMachineInstruction()
28 /// method to print assembly for each instruction.
29 ///
30 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
31   SetupMachineFunction(MF);
32   O << "\n\n";
33
34   // Print out constants referenced by the function
35   EmitConstantPool(MF.getConstantPool());
36
37   // Print out labels for the function.
38   const Function* F = MF.getFunction();
39   switch (F->getLinkage()) {
40   default: assert(0 && "Unsupported linkage type!");
41   case Function::InternalLinkage:
42     SwitchToTextSection("_text", F);
43     EmitAlignment(4);
44     break;    
45   case Function::DLLExportLinkage:
46     DLLExportedFns.insert(CurrentFnName);
47     //FALLS THROUGH
48   case Function::ExternalLinkage:
49     O << "\tpublic " << CurrentFnName << "\n";
50     SwitchToTextSection("_text", F);
51     EmitAlignment(4);
52     break;    
53   }
54   
55   O << CurrentFnName << "\tproc near\n";
56   
57   // Print out code for the function.
58   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
59        I != E; ++I) {
60     // Print a label for the basic block if there are any predecessors.
61     if (I->pred_begin() != I->pred_end()) {
62       printBasicBlockLabel(I, true);
63       O << '\n';
64     }
65     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
66          II != E; ++II) {
67       // Print the assembly for the instruction.
68       O << "\t";
69       printMachineInstruction(II);
70     }
71   }
72
73   O << CurrentFnName << "\tendp\n";
74
75   // We didn't modify anything.
76   return false;
77 }
78
79 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
80   unsigned char value = MI->getOperand(Op).getImmedValue();
81   assert(value <= 7 && "Invalid ssecc argument!");
82   switch (value) {
83   case 0: O << "eq"; break;
84   case 1: O << "lt"; break;
85   case 2: O << "le"; break;
86   case 3: O << "unord"; break;
87   case 4: O << "neq"; break;
88   case 5: O << "nlt"; break;
89   case 6: O << "nle"; break;
90   case 7: O << "ord"; break;
91   }
92 }
93
94 void X86IntelAsmPrinter::printOp(const MachineOperand &MO, 
95                                  const char *Modifier) {
96   const MRegisterInfo &RI = *TM.getRegisterInfo();
97   switch (MO.getType()) {
98   case MachineOperand::MO_Register:
99     if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
100       unsigned Reg = MO.getReg();
101       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
102         MVT::ValueType VT = (strcmp(Modifier,"subreg64") == 0) ?
103           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
104                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
105         Reg = getX86SubSuperRegister(Reg, VT);
106       }
107       O << RI.get(Reg).Name;
108     } else
109       O << "reg" << MO.getReg();
110     return;
111
112   case MachineOperand::MO_Immediate:
113     O << MO.getImmedValue();
114     return;
115   case MachineOperand::MO_MachineBasicBlock:
116     printBasicBlockLabel(MO.getMachineBasicBlock());
117     return;
118   case MachineOperand::MO_ConstantPoolIndex: {
119     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
120     if (!isMemOp) O << "OFFSET ";
121     O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
122       << getFunctionNumber() << "_" << MO.getConstantPoolIndex();
123     int Offset = MO.getOffset();
124     if (Offset > 0)
125       O << " + " << Offset;
126     else if (Offset < 0)
127       O << Offset;
128     O << "]";
129     return;
130   }
131   case MachineOperand::MO_GlobalAddress: {
132     bool isCallOp = Modifier && !strcmp(Modifier, "call");
133     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
134     GlobalValue *GV = MO.getGlobal();    
135
136     if (!isMemOp && !isCallOp) O << "OFFSET ";
137     if (GV->hasDLLImportLinkage()) {
138       // FIXME: This should be fixed with full support of stdcall & fastcall
139       // CC's
140       O << "__imp_";          
141     } 
142     O << Mang->getValueName(GV);
143     int Offset = MO.getOffset();
144     if (Offset > 0)
145       O << " + " << Offset;
146     else if (Offset < 0)
147       O << Offset;
148     return;
149   }
150   case MachineOperand::MO_ExternalSymbol: {
151     bool isCallOp = Modifier && !strcmp(Modifier, "call");
152     if (!isCallOp) O << "OFFSET ";
153     O << TAI->getGlobalPrefix() << MO.getSymbolName();
154     return;
155   }
156   default:
157     O << "<unknown operand type>"; return;
158   }
159 }
160
161 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
162                                            const char *Modifier) {
163   assert(isMem(MI, Op) && "Invalid memory reference!");
164
165   const MachineOperand &BaseReg  = MI->getOperand(Op);
166   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
167   const MachineOperand &IndexReg = MI->getOperand(Op+2);
168   const MachineOperand &DispSpec = MI->getOperand(Op+3);
169
170   if (BaseReg.isFrameIndex()) {
171     O << "[frame slot #" << BaseReg.getFrameIndex();
172     if (DispSpec.getImmedValue())
173       O << " + " << DispSpec.getImmedValue();
174     O << "]";
175     return;
176   }
177
178   O << "[";
179   bool NeedPlus = false;
180   if (BaseReg.getReg()) {
181     printOp(BaseReg, Modifier);
182     NeedPlus = true;
183   }
184
185   if (IndexReg.getReg()) {
186     if (NeedPlus) O << " + ";
187     if (ScaleVal != 1)
188       O << ScaleVal << "*";
189     printOp(IndexReg, Modifier);
190     NeedPlus = true;
191   }
192
193   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex()) {
194     if (NeedPlus)
195       O << " + ";
196     printOp(DispSpec, "mem");
197   } else {
198     int DispVal = DispSpec.getImmedValue();
199     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
200       if (NeedPlus)
201         if (DispVal > 0)
202           O << " + ";
203         else {
204           O << " - ";
205           DispVal = -DispVal;
206         }
207       O << DispVal;
208     }
209   }
210   O << "]";
211 }
212
213 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
214   O << "\"L" << getFunctionNumber() << "$pb\"\n";
215   O << "\"L" << getFunctionNumber() << "$pb\":";
216 }
217
218 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
219                                            const char Mode) {
220   const MRegisterInfo &RI = *TM.getRegisterInfo();
221   unsigned Reg = MO.getReg();
222   switch (Mode) {
223   default: return true;  // Unknown mode.
224   case 'b': // Print QImode register
225     Reg = getX86SubSuperRegister(Reg, MVT::i8);
226     break;
227   case 'h': // Print QImode high register
228     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
229     break;
230   case 'w': // Print HImode register
231     Reg = getX86SubSuperRegister(Reg, MVT::i16);
232     break;
233   case 'k': // Print SImode register
234     Reg = getX86SubSuperRegister(Reg, MVT::i32);
235     break;
236   }
237
238   O << '%' << RI.get(Reg).Name;
239   return false;
240 }
241
242 /// PrintAsmOperand - Print out an operand for an inline asm expression.
243 ///
244 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
245                                          unsigned AsmVariant, 
246                                          const char *ExtraCode) {
247   // Does this asm operand have a single letter operand modifier?
248   if (ExtraCode && ExtraCode[0]) {
249     if (ExtraCode[1] != 0) return true; // Unknown modifier.
250     
251     switch (ExtraCode[0]) {
252     default: return true;  // Unknown modifier.
253     case 'b': // Print QImode register
254     case 'h': // Print QImode high register
255     case 'w': // Print HImode register
256     case 'k': // Print SImode register
257       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
258     }
259   }
260   
261   printOperand(MI, OpNo);
262   return false;
263 }
264
265 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
266                                                unsigned OpNo,
267                                                unsigned AsmVariant, 
268                                                const char *ExtraCode) {
269   if (ExtraCode && ExtraCode[0])
270     return true; // Unknown modifier.
271   printMemReference(MI, OpNo);
272   return false;
273 }
274
275 /// printMachineInstruction -- Print out a single X86 LLVM instruction
276 /// MI in Intel syntax to the current output stream.
277 ///
278 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
279   ++EmittedInsts;
280
281   // See if a truncate instruction can be turned into a nop.
282   switch (MI->getOpcode()) {
283   default: break;
284   case X86::TRUNC_64to32:
285   case X86::TRUNC_64to16:
286   case X86::TRUNC_32to16:
287   case X86::TRUNC_32to8:
288   case X86::TRUNC_16to8:
289   case X86::TRUNC_32_to8:
290   case X86::TRUNC_16_to8: {
291     const MachineOperand &MO0 = MI->getOperand(0);
292     const MachineOperand &MO1 = MI->getOperand(1);
293     unsigned Reg0 = MO0.getReg();
294     unsigned Reg1 = MO1.getReg();
295     unsigned Opc = MI->getOpcode();
296     if (Opc == X86::TRUNC_64to32)
297       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
298     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
299       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
300     else
301       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
302     O << TAI->getCommentString() << " TRUNCATE ";
303     if (Reg0 != Reg1)
304       O << "\n\t";
305     break;
306   }
307   case X86::PsMOVZX64rr32:
308     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
309     break;
310   }
311
312   // Call the autogenerated instruction printer routines.
313   printInstruction(MI);
314 }
315
316 bool X86IntelAsmPrinter::doInitialization(Module &M) {
317   X86SharedAsmPrinter::doInitialization(M);
318   
319   Mang->markCharUnacceptable('.');
320
321   O << "\t.686\n\t.model flat\n\n";
322
323   // Emit declarations for external functions.
324   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
325     if (I->isExternal())
326       O << "\textern " << Mang->getValueName(I) << ":near\n";
327
328   // Emit declarations for external globals.  Note that VC++ always declares
329   // external globals to have type byte, and if that's good enough for VC++...
330   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
331        I != E; ++I) {
332     if (I->isExternal())
333       O << "\textern " << Mang->getValueName(I) << ":byte\n";
334   }
335
336   return false;
337 }
338
339 bool X86IntelAsmPrinter::doFinalization(Module &M) {
340   const TargetData *TD = TM.getTargetData();
341
342   // Print out module-level global variables here.
343   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
344        I != E; ++I) {
345     if (I->isExternal()) continue;   // External global require no code
346     
347     // Check to see if this is a special global used by LLVM, if so, emit it.
348     if (EmitSpecialLLVMGlobal(I))
349       continue;
350     
351     std::string name = Mang->getValueName(I);
352     Constant *C = I->getInitializer();
353     unsigned Size = TD->getTypeSize(C->getType());
354     unsigned Align = getPreferredAlignmentLog(I);
355     bool bCustomSegment = false;
356
357     switch (I->getLinkage()) {
358     case GlobalValue::LinkOnceLinkage:
359     case GlobalValue::WeakLinkage:
360       SwitchToDataSection("", 0);
361       O << name << "?\tsegment common 'COMMON'\n";
362       bCustomSegment = true;
363       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
364       // are also available.
365       break;
366     case GlobalValue::AppendingLinkage:
367       SwitchToDataSection("", 0);
368       O << name << "?\tsegment public 'DATA'\n";
369       bCustomSegment = true;
370       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
371       // are also available.
372       break;
373     case GlobalValue::DLLExportLinkage:
374       DLLExportedGVs.insert(name);
375       // FALL THROUGH
376     case GlobalValue::ExternalLinkage:
377       O << "\tpublic " << name << "\n";
378       // FALL THROUGH
379     case GlobalValue::InternalLinkage:
380       SwitchToDataSection(TAI->getDataSection(), I);
381       break;
382     default:
383       assert(0 && "Unknown linkage type!");
384     }
385
386     if (!bCustomSegment)
387       EmitAlignment(Align, I);
388
389     O << name << ":\t\t\t\t" << TAI->getCommentString()
390       << " " << I->getName() << '\n';
391
392     EmitGlobalConstant(C);
393
394     if (bCustomSegment)
395       O << name << "?\tends\n";
396   }
397
398     // Output linker support code for dllexported globals
399   if ((DLLExportedGVs.begin() != DLLExportedGVs.end()) ||
400       (DLLExportedFns.begin() != DLLExportedFns.end())) {
401     SwitchToDataSection("", 0);
402     O << "; WARNING: The following code is valid only with MASM v8.x and (possible) higher\n"
403       << "; This version of MASM is usually shipped with Microsoft Visual Studio 2005\n"
404       << "; or (possible) further versions. Unfortunately, there is no way to support\n"
405       << "; dllexported symbols in the earlier versions of MASM in fully automatic way\n\n";
406     O << "_drectve\t segment info alias('.drectve')\n";
407   }
408
409   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
410          e = DLLExportedGVs.end();
411          i != e; ++i) {
412     O << "\t db ' /EXPORT:" << *i << ",data'\n";
413   }    
414
415   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
416          e = DLLExportedFns.end();
417          i != e; ++i) {
418     O << "\t db ' /EXPORT:" << *i << "'\n";
419   }    
420
421   if ((DLLExportedGVs.begin() != DLLExportedGVs.end()) ||
422       (DLLExportedFns.begin() != DLLExportedFns.end())) {
423     O << "_drectve\t ends\n";    
424   }
425   
426   // Bypass X86SharedAsmPrinter::doFinalization().
427   AsmPrinter::doFinalization(M);
428   SwitchToDataSection("", 0);
429   O << "\tend\n";
430   return false; // success
431 }
432
433 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
434   unsigned NumElts = CVA->getNumOperands();
435   if (NumElts) {
436     // ML does not have escape sequences except '' for '.  It also has a maximum
437     // string length of 255.
438     unsigned len = 0;
439     bool inString = false;
440     for (unsigned i = 0; i < NumElts; i++) {
441       int n = cast<ConstantInt>(CVA->getOperand(i))->getRawValue() & 255;
442       if (len == 0)
443         O << "\tdb ";
444
445       if (n >= 32 && n <= 127) {
446         if (!inString) {
447           if (len > 0) {
448             O << ",'";
449             len += 2;
450           } else {
451             O << "'";
452             len++;
453           }
454           inString = true;
455         }
456         if (n == '\'') {
457           O << "'";
458           len++;
459         }
460         O << char(n);
461       } else {
462         if (inString) {
463           O << "'";
464           len++;
465           inString = false;
466         }
467         if (len > 0) {
468           O << ",";
469           len++;
470         }
471         O << n;
472         len += 1 + (n > 9) + (n > 99);
473       }
474
475       if (len > 60) {
476         if (inString) {
477           O << "'";
478           inString = false;
479         }
480         O << "\n";
481         len = 0;
482       }
483     }
484
485     if (len > 0) {
486       if (inString)
487         O << "'";
488       O << "\n";
489     }
490   }
491 }
492
493 // Include the auto-generated portion of the assembly writer.
494 #include "X86GenAsmWriter1.inc"