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