change AsmPrinter to use DwarfDebug/DwarfException directly
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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 implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Target/Mangler.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/Format.h"
46 using namespace llvm;
47
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
49
50 char AsmPrinter::ID = 0;
51
52 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
53 static gcp_map_type &getGCMap(void *&P) {
54   if (P == 0)
55     P = new gcp_map_type();
56   return *(gcp_map_type*)P;
57 }
58
59
60 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
61   : MachineFunctionPass(&ID),
62     TM(tm), MAI(tm.getMCAsmInfo()),
63     OutContext(Streamer.getContext()),
64     OutStreamer(Streamer),
65     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
66   DD = 0; DE = 0; MMI = 0; LI = 0;
67   GCMetadataPrinters = 0;
68   VerboseAsm = Streamer.isVerboseAsm();
69 }
70
71 AsmPrinter::~AsmPrinter() {
72   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
73   
74   if (GCMetadataPrinters != 0) {
75     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
76     
77     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
78       delete I->second;
79     delete &GCMap;
80     GCMetadataPrinters = 0;
81   }
82   
83   delete &OutStreamer;
84 }
85
86 /// getFunctionNumber - Return a unique ID for the current function.
87 ///
88 unsigned AsmPrinter::getFunctionNumber() const {
89   return MF->getFunctionNumber();
90 }
91
92 TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
93   return TM.getTargetLowering()->getObjFileLowering();
94 }
95
96
97 /// getTargetData - Return information about data layout.
98 const TargetData &AsmPrinter::getTargetData() const {
99   return *TM.getTargetData();
100 }
101
102 /// getCurrentSection() - Return the current section we are emitting to.
103 const MCSection *AsmPrinter::getCurrentSection() const {
104   return OutStreamer.getCurrentSection();
105 }
106
107
108
109 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
110   AU.setPreservesAll();
111   MachineFunctionPass::getAnalysisUsage(AU);
112   AU.addRequired<MachineModuleInfo>();
113   AU.addRequired<GCModuleInfo>();
114   if (isVerbose())
115     AU.addRequired<MachineLoopInfo>();
116 }
117
118 bool AsmPrinter::doInitialization(Module &M) {
119   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
120   MMI->AnalyzeModule(M);
121
122   // Initialize TargetLoweringObjectFile.
123   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
124     .Initialize(OutContext, TM);
125   
126   Mang = new Mangler(OutContext, *TM.getTargetData());
127   
128   // Allow the target to emit any magic that it wants at the start of the file.
129   EmitStartOfAsmFile(M);
130
131   // Very minimal debug info. It is ignored if we emit actual debug info. If we
132   // don't, this at least helps the user find where a global came from.
133   if (MAI->hasSingleParameterDotFile()) {
134     // .file "foo.c"
135     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
136   }
137
138   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
139   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
140   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
141     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
142       MP->beginAssembly(*this);
143
144   // Emit module-level inline asm if it exists.
145   if (!M.getModuleInlineAsm().empty()) {
146     OutStreamer.AddComment("Start of file scope inline assembly");
147     OutStreamer.AddBlankLine();
148     EmitInlineAsm(M.getModuleInlineAsm());
149     OutStreamer.AddComment("End of file scope inline assembly");
150     OutStreamer.AddBlankLine();
151   }
152
153   if (MAI->doesSupportDebugInformation())
154     DD = new DwarfDebug(this, &M);
155     
156   if (MAI->doesSupportExceptionHandling())
157     DE = new DwarfException(this);
158
159   return false;
160 }
161
162 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
163   switch ((GlobalValue::LinkageTypes)Linkage) {
164   case GlobalValue::CommonLinkage:
165   case GlobalValue::LinkOnceAnyLinkage:
166   case GlobalValue::LinkOnceODRLinkage:
167   case GlobalValue::WeakAnyLinkage:
168   case GlobalValue::WeakODRLinkage:
169   case GlobalValue::LinkerPrivateLinkage:
170     if (MAI->getWeakDefDirective() != 0) {
171       // .globl _foo
172       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
173       // .weak_definition _foo
174       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
175     } else if (const char *LinkOnce = MAI->getLinkOnceDirective()) {
176       // .globl _foo
177       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
178       // FIXME: linkonce should be a section attribute, handled by COFF Section
179       // assignment.
180       // http://sourceware.org/binutils/docs-2.20/as/Linkonce.html#Linkonce
181       // .linkonce discard
182       // FIXME: It would be nice to use .linkonce samesize for non-common
183       // globals.
184       OutStreamer.EmitRawText(StringRef(LinkOnce));
185     } else {
186       // .weak _foo
187       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
188     }
189     break;
190   case GlobalValue::DLLExportLinkage:
191   case GlobalValue::AppendingLinkage:
192     // FIXME: appending linkage variables should go into a section of
193     // their name or something.  For now, just emit them as external.
194   case GlobalValue::ExternalLinkage:
195     // If external or appending, declare as a global symbol.
196     // .globl _foo
197     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
198     break;
199   case GlobalValue::PrivateLinkage:
200   case GlobalValue::InternalLinkage:
201     break;
202   default:
203     llvm_unreachable("Unknown linkage type!");
204   }
205 }
206
207
208 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
209 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
210   if (!GV->hasInitializer())   // External globals require no code.
211     return;
212   
213   // Check to see if this is a special global used by LLVM, if so, emit it.
214   if (EmitSpecialLLVMGlobal(GV))
215     return;
216
217   MCSymbol *GVSym = Mang->getSymbol(GV);
218   EmitVisibility(GVSym, GV->getVisibility());
219
220   if (MAI->hasDotTypeDotSizeDirective())
221     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
222   
223   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
224
225   const TargetData *TD = TM.getTargetData();
226   unsigned Size = TD->getTypeAllocSize(GV->getType()->getElementType());
227   unsigned AlignLog = TD->getPreferredAlignmentLog(GV);
228   
229   // Handle common and BSS local symbols (.lcomm).
230   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
231     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
232     
233     if (isVerbose()) {
234       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
235                      /*PrintType=*/false, GV->getParent());
236       OutStreamer.GetCommentOS() << '\n';
237     }
238     
239     // Handle common symbols.
240     if (GVKind.isCommon()) {
241       // .comm _foo, 42, 4
242       OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
243       return;
244     }
245     
246     // Handle local BSS symbols.
247     if (MAI->hasMachoZeroFillDirective()) {
248       const MCSection *TheSection =
249         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
250       // .zerofill __DATA, __bss, _foo, 400, 5
251       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
252       return;
253     }
254     
255     if (MAI->hasLCOMMDirective()) {
256       // .lcomm _foo, 42
257       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
258       return;
259     }
260     
261     // .local _foo
262     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
263     // .comm _foo, 42, 4
264     OutStreamer.EmitCommonSymbol(GVSym, Size, 1 << AlignLog);
265     return;
266   }
267   
268   const MCSection *TheSection =
269     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
270
271   // Handle the zerofill directive on darwin, which is a special form of BSS
272   // emission.
273   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
274     // .globl _foo
275     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
276     // .zerofill __DATA, __common, _foo, 400, 5
277     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
278     return;
279   }
280
281   OutStreamer.SwitchSection(TheSection);
282
283   EmitLinkage(GV->getLinkage(), GVSym);
284   EmitAlignment(AlignLog, GV);
285
286   if (isVerbose()) {
287     WriteAsOperand(OutStreamer.GetCommentOS(), GV,
288                    /*PrintType=*/false, GV->getParent());
289     OutStreamer.GetCommentOS() << '\n';
290   }
291   OutStreamer.EmitLabel(GVSym);
292
293   EmitGlobalConstant(GV->getInitializer());
294
295   if (MAI->hasDotTypeDotSizeDirective())
296     // .size foo, 42
297     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
298   
299   OutStreamer.AddBlankLine();
300 }
301
302 /// EmitFunctionHeader - This method emits the header for the current
303 /// function.
304 void AsmPrinter::EmitFunctionHeader() {
305   // Print out constants referenced by the function
306   EmitConstantPool();
307   
308   // Print the 'header' of function.
309   const Function *F = MF->getFunction();
310
311   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
312   EmitVisibility(CurrentFnSym, F->getVisibility());
313
314   EmitLinkage(F->getLinkage(), CurrentFnSym);
315   EmitAlignment(MF->getAlignment(), F);
316
317   if (MAI->hasDotTypeDotSizeDirective())
318     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
319
320   if (isVerbose()) {
321     WriteAsOperand(OutStreamer.GetCommentOS(), F,
322                    /*PrintType=*/false, F->getParent());
323     OutStreamer.GetCommentOS() << '\n';
324   }
325
326   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
327   // do their wild and crazy things as required.
328   EmitFunctionEntryLabel();
329   
330   // If the function had address-taken blocks that got deleted, then we have
331   // references to the dangling symbols.  Emit them at the start of the function
332   // so that we don't get references to undefined symbols.
333   std::vector<MCSymbol*> DeadBlockSyms;
334   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
335   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
336     OutStreamer.AddComment("Address taken block that was later removed");
337     OutStreamer.EmitLabel(DeadBlockSyms[i]);
338   }
339   
340   // Add some workaround for linkonce linkage on Cygwin\MinGW.
341   if (MAI->getLinkOnceDirective() != 0 &&
342       (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
343     // FIXME: What is this?
344     MCSymbol *FakeStub = 
345       OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
346                                    CurrentFnSym->getName());
347     OutStreamer.EmitLabel(FakeStub);
348   }
349   
350   // Emit pre-function debug and/or EH information.
351   if (DE) DE->BeginFunction(MF);
352   if (DD) DD->beginFunction(MF);
353 }
354
355 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
356 /// function.  This can be overridden by targets as required to do custom stuff.
357 void AsmPrinter::EmitFunctionEntryLabel() {
358   OutStreamer.EmitLabel(CurrentFnSym);
359 }
360
361
362 /// EmitComments - Pretty-print comments for instructions.
363 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
364   const MachineFunction *MF = MI.getParent()->getParent();
365   const TargetMachine &TM = MF->getTarget();
366   
367   DebugLoc DL = MI.getDebugLoc();
368   if (!DL.isUnknown()) {          // Print source line info.
369     DIScope Scope(DL.getScope(MF->getFunction()->getContext()));
370     // Omit the directory, because it's likely to be long and uninteresting.
371     if (Scope.Verify())
372       CommentOS << Scope.getFilename();
373     else
374       CommentOS << "<unknown>";
375     CommentOS << ':' << DL.getLine();
376     if (DL.getCol() != 0)
377       CommentOS << ':' << DL.getCol();
378     CommentOS << '\n';
379   }
380   
381   // Check for spills and reloads
382   int FI;
383   
384   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
385   
386   // We assume a single instruction only has a spill or reload, not
387   // both.
388   const MachineMemOperand *MMO;
389   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
390     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
391       MMO = *MI.memoperands_begin();
392       CommentOS << MMO->getSize() << "-byte Reload\n";
393     }
394   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
395     if (FrameInfo->isSpillSlotObjectIndex(FI))
396       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
397   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
398     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
399       MMO = *MI.memoperands_begin();
400       CommentOS << MMO->getSize() << "-byte Spill\n";
401     }
402   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
403     if (FrameInfo->isSpillSlotObjectIndex(FI))
404       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
405   }
406   
407   // Check for spill-induced copies
408   unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
409   if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg,
410                                      SrcSubIdx, DstSubIdx)) {
411     if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
412       CommentOS << " Reload Reuse\n";
413   }
414 }
415
416 /// EmitImplicitDef - This method emits the specified machine instruction
417 /// that is an implicit def.
418 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
419   unsigned RegNo = MI->getOperand(0).getReg();
420   AP.OutStreamer.AddComment(Twine("implicit-def: ") +
421                             AP.TM.getRegisterInfo()->getName(RegNo));
422   AP.OutStreamer.AddBlankLine();
423 }
424
425 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
426   std::string Str = "kill:";
427   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428     const MachineOperand &Op = MI->getOperand(i);
429     assert(Op.isReg() && "KILL instruction must have only register operands");
430     Str += ' ';
431     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
432     Str += (Op.isDef() ? "<def>" : "<kill>");
433   }
434   AP.OutStreamer.AddComment(Str);
435   AP.OutStreamer.AddBlankLine();
436 }
437
438
439
440 /// EmitFunctionBody - This method emits the body and trailer for a
441 /// function.
442 void AsmPrinter::EmitFunctionBody() {
443   // Emit target-specific gunk before the function body.
444   EmitFunctionBodyStart();
445   
446   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
447   
448   // Print out code for the function.
449   bool HasAnyRealCode = false;
450   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
451        I != E; ++I) {
452     // Print a label for the basic block.
453     EmitBasicBlockStart(I);
454     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
455          II != IE; ++II) {
456       // Print the assembly for the instruction.
457       if (!II->isLabel())
458         HasAnyRealCode = true;
459       
460       ++EmittedInsts;
461       
462       if (ShouldPrintDebugScopes)
463         DD->beginScope(II);
464       
465       if (isVerbose())
466         EmitComments(*II, OutStreamer.GetCommentOS());
467
468       switch (II->getOpcode()) {
469       case TargetOpcode::DBG_LABEL:
470       case TargetOpcode::EH_LABEL:
471       case TargetOpcode::GC_LABEL:
472         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
473         break;
474       case TargetOpcode::INLINEASM:
475         EmitInlineAsm(II);
476         break;
477       case TargetOpcode::IMPLICIT_DEF:
478         if (isVerbose()) EmitImplicitDef(II, *this);
479         break;
480       case TargetOpcode::KILL:
481         if (isVerbose()) EmitKill(II, *this);
482         break;
483       default:
484         EmitInstruction(II);
485         break;
486       }
487       
488       if (ShouldPrintDebugScopes)
489         DD->endScope(II);
490     }
491   }
492   
493   // If the function is empty and the object file uses .subsections_via_symbols,
494   // then we need to emit *something* to the function body to prevent the
495   // labels from collapsing together.  Just emit a 0 byte.
496   if (MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)
497     OutStreamer.EmitIntValue(0, 1, 0/*addrspace*/);
498   
499   // Emit target-specific gunk after the function body.
500   EmitFunctionBodyEnd();
501   
502   // If the target wants a .size directive for the size of the function, emit
503   // it.
504   if (MAI->hasDotTypeDotSizeDirective()) {
505     // Create a symbol for the end of function, so we can get the size as
506     // difference between the function label and the temp label.
507     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
508     OutStreamer.EmitLabel(FnEndLabel);
509     
510     const MCExpr *SizeExp =
511       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
512                               MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
513                               OutContext);
514     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
515   }
516   
517   // Emit post-function debug information.
518   if (DD) DD->endFunction(MF);
519   if (DE) DE->EndFunction();
520   MMI->EndFunction();
521   
522   // Print out jump tables referenced by the function.
523   EmitJumpTableInfo();
524   
525   OutStreamer.AddBlankLine();
526 }
527
528
529 bool AsmPrinter::doFinalization(Module &M) {
530   // Emit global variables.
531   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
532        I != E; ++I)
533     EmitGlobalVariable(I);
534   
535   // Finalize debug and EH information.
536   if (DE) {
537     DE->EndModule();
538     delete DE; DE = 0;
539   }
540   if (DD) {
541     DD->endModule();
542     delete DD; DD = 0;
543   }
544   
545   // If the target wants to know about weak references, print them all.
546   if (MAI->getWeakRefDirective()) {
547     // FIXME: This is not lazy, it would be nice to only print weak references
548     // to stuff that is actually used.  Note that doing so would require targets
549     // to notice uses in operands (due to constant exprs etc).  This should
550     // happen with the MC stuff eventually.
551
552     // Print out module-level global variables here.
553     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
554          I != E; ++I) {
555       if (!I->hasExternalWeakLinkage()) continue;
556       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
557     }
558     
559     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
560       if (!I->hasExternalWeakLinkage()) continue;
561       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
562     }
563   }
564
565   if (MAI->hasSetDirective()) {
566     OutStreamer.AddBlankLine();
567     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
568          I != E; ++I) {
569       MCSymbol *Name = Mang->getSymbol(I);
570
571       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
572       MCSymbol *Target = Mang->getSymbol(GV);
573
574       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
575         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
576       else if (I->hasWeakLinkage())
577         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
578       else
579         assert(I->hasLocalLinkage() && "Invalid alias linkage");
580
581       EmitVisibility(Name, I->getVisibility());
582
583       // Emit the directives as assignments aka .set:
584       OutStreamer.EmitAssignment(Name, 
585                                  MCSymbolRefExpr::Create(Target, OutContext));
586     }
587   }
588
589   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
590   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
591   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
592     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
593       MP->finishAssembly(*this);
594
595   // If we don't have any trampolines, then we don't require stack memory
596   // to be executable. Some targets have a directive to declare this.
597   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
598   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
599     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
600       OutStreamer.SwitchSection(S);
601   
602   // Allow the target to emit any magic that it wants at the end of the file,
603   // after everything else has gone out.
604   EmitEndOfAsmFile(M);
605   
606   delete Mang; Mang = 0;
607   MMI = 0;
608   
609   OutStreamer.Finish();
610   return false;
611 }
612
613 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
614   this->MF = &MF;
615   // Get the function symbol.
616   CurrentFnSym = Mang->getSymbol(MF.getFunction());
617
618   if (isVerbose())
619     LI = &getAnalysis<MachineLoopInfo>();
620 }
621
622 namespace {
623   // SectionCPs - Keep track the alignment, constpool entries per Section.
624   struct SectionCPs {
625     const MCSection *S;
626     unsigned Alignment;
627     SmallVector<unsigned, 4> CPEs;
628     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
629   };
630 }
631
632 /// EmitConstantPool - Print to the current output stream assembly
633 /// representations of the constants in the constant pool MCP. This is
634 /// used to print out constants which have been "spilled to memory" by
635 /// the code generator.
636 ///
637 void AsmPrinter::EmitConstantPool() {
638   const MachineConstantPool *MCP = MF->getConstantPool();
639   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
640   if (CP.empty()) return;
641
642   // Calculate sections for constant pool entries. We collect entries to go into
643   // the same section together to reduce amount of section switch statements.
644   SmallVector<SectionCPs, 4> CPSections;
645   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
646     const MachineConstantPoolEntry &CPE = CP[i];
647     unsigned Align = CPE.getAlignment();
648     
649     SectionKind Kind;
650     switch (CPE.getRelocationInfo()) {
651     default: llvm_unreachable("Unknown section kind");
652     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
653     case 1:
654       Kind = SectionKind::getReadOnlyWithRelLocal();
655       break;
656     case 0:
657     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
658     case 4:  Kind = SectionKind::getMergeableConst4(); break;
659     case 8:  Kind = SectionKind::getMergeableConst8(); break;
660     case 16: Kind = SectionKind::getMergeableConst16();break;
661     default: Kind = SectionKind::getMergeableConst(); break;
662     }
663     }
664
665     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
666     
667     // The number of sections are small, just do a linear search from the
668     // last section to the first.
669     bool Found = false;
670     unsigned SecIdx = CPSections.size();
671     while (SecIdx != 0) {
672       if (CPSections[--SecIdx].S == S) {
673         Found = true;
674         break;
675       }
676     }
677     if (!Found) {
678       SecIdx = CPSections.size();
679       CPSections.push_back(SectionCPs(S, Align));
680     }
681
682     if (Align > CPSections[SecIdx].Alignment)
683       CPSections[SecIdx].Alignment = Align;
684     CPSections[SecIdx].CPEs.push_back(i);
685   }
686
687   // Now print stuff into the calculated sections.
688   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
689     OutStreamer.SwitchSection(CPSections[i].S);
690     EmitAlignment(Log2_32(CPSections[i].Alignment));
691
692     unsigned Offset = 0;
693     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
694       unsigned CPI = CPSections[i].CPEs[j];
695       MachineConstantPoolEntry CPE = CP[CPI];
696
697       // Emit inter-object padding for alignment.
698       unsigned AlignMask = CPE.getAlignment() - 1;
699       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
700       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
701
702       const Type *Ty = CPE.getType();
703       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
704
705       // Emit the label with a comment on it.
706       if (isVerbose()) {
707         OutStreamer.GetCommentOS() << "constant pool ";
708         WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(),
709                           MF->getFunction()->getParent());
710         OutStreamer.GetCommentOS() << '\n';
711       }
712       OutStreamer.EmitLabel(GetCPISymbol(CPI));
713
714       if (CPE.isMachineConstantPoolEntry())
715         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
716       else
717         EmitGlobalConstant(CPE.Val.ConstVal);
718     }
719   }
720 }
721
722 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
723 /// by the current function to the current output stream.  
724 ///
725 void AsmPrinter::EmitJumpTableInfo() {
726   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
727   if (MJTI == 0) return;
728   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
729   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
730   if (JT.empty()) return;
731
732   // Pick the directive to use to print the jump table entries, and switch to 
733   // the appropriate section.
734   const Function *F = MF->getFunction();
735   bool JTInDiffSection = false;
736   if (// In PIC mode, we need to emit the jump table to the same section as the
737       // function body itself, otherwise the label differences won't make sense.
738       // FIXME: Need a better predicate for this: what about custom entries?
739       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
740       // We should also do if the section name is NULL or function is declared
741       // in discardable section
742       // FIXME: this isn't the right predicate, should be based on the MCSection
743       // for the function.
744       F->isWeakForLinker()) {
745     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
746   } else {
747     // Otherwise, drop it in the readonly section.
748     const MCSection *ReadOnlySection = 
749       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
750     OutStreamer.SwitchSection(ReadOnlySection);
751     JTInDiffSection = true;
752   }
753
754   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
755   
756   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
757     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
758     
759     // If this jump table was deleted, ignore it. 
760     if (JTBBs.empty()) continue;
761
762     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
763     // .set directive for each unique entry.  This reduces the number of
764     // relocations the assembler will generate for the jump table.
765     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
766         MAI->hasSetDirective()) {
767       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
768       const TargetLowering *TLI = TM.getTargetLowering();
769       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
770       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
771         const MachineBasicBlock *MBB = JTBBs[ii];
772         if (!EmittedSets.insert(MBB)) continue;
773         
774         // .set LJTSet, LBB32-base
775         const MCExpr *LHS =
776           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
777         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
778                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
779       }
780     }          
781     
782     // On some targets (e.g. Darwin) we want to emit two consequtive labels
783     // before each jump table.  The first label is never referenced, but tells
784     // the assembler and linker the extents of the jump table object.  The
785     // second label is actually referenced by the code.
786     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
787       // FIXME: This doesn't have to have any specific name, just any randomly
788       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
789       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
790
791     OutStreamer.EmitLabel(GetJTISymbol(JTI));
792
793     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
794       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
795   }
796 }
797
798 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
799 /// current stream.
800 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
801                                     const MachineBasicBlock *MBB,
802                                     unsigned UID) const {
803   const MCExpr *Value = 0;
804   switch (MJTI->getEntryKind()) {
805   case MachineJumpTableInfo::EK_Inline:
806     llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
807   case MachineJumpTableInfo::EK_Custom32:
808     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
809                                                               OutContext);
810     break;
811   case MachineJumpTableInfo::EK_BlockAddress:
812     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
813     //     .word LBB123
814     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
815     break;
816   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
817     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
818     // with a relocation as gp-relative, e.g.:
819     //     .gprel32 LBB123
820     MCSymbol *MBBSym = MBB->getSymbol();
821     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
822     return;
823   }
824
825   case MachineJumpTableInfo::EK_LabelDifference32: {
826     // EK_LabelDifference32 - Each entry is the address of the block minus
827     // the address of the jump table.  This is used for PIC jump tables where
828     // gprel32 is not supported.  e.g.:
829     //      .word LBB123 - LJTI1_2
830     // If the .set directive is supported, this is emitted as:
831     //      .set L4_5_set_123, LBB123 - LJTI1_2
832     //      .word L4_5_set_123
833     
834     // If we have emitted set directives for the jump table entries, print 
835     // them rather than the entries themselves.  If we're emitting PIC, then
836     // emit the table entries as differences between two text section labels.
837     if (MAI->hasSetDirective()) {
838       // If we used .set, reference the .set's symbol.
839       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
840                                       OutContext);
841       break;
842     }
843     // Otherwise, use the difference as the jump table entry.
844     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
845     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
846     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
847     break;
848   }
849   }
850   
851   assert(Value && "Unknown entry kind!");
852  
853   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
854   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
855 }
856
857
858 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
859 /// special global used by LLVM.  If so, emit it and return true, otherwise
860 /// do nothing and return false.
861 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
862   if (GV->getName() == "llvm.used") {
863     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
864       EmitLLVMUsedList(GV->getInitializer());
865     return true;
866   }
867
868   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
869   if (GV->getSection() == "llvm.metadata" ||
870       GV->hasAvailableExternallyLinkage())
871     return true;
872   
873   if (!GV->hasAppendingLinkage()) return false;
874
875   assert(GV->hasInitializer() && "Not a special LLVM global!");
876   
877   const TargetData *TD = TM.getTargetData();
878   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
879   if (GV->getName() == "llvm.global_ctors") {
880     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
881     EmitAlignment(Align, 0);
882     EmitXXStructorList(GV->getInitializer());
883     
884     if (TM.getRelocationModel() == Reloc::Static &&
885         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
886       StringRef Sym(".constructors_used");
887       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
888                                       MCSA_Reference);
889     }
890     return true;
891   } 
892   
893   if (GV->getName() == "llvm.global_dtors") {
894     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
895     EmitAlignment(Align, 0);
896     EmitXXStructorList(GV->getInitializer());
897
898     if (TM.getRelocationModel() == Reloc::Static &&
899         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
900       StringRef Sym(".destructors_used");
901       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
902                                       MCSA_Reference);
903     }
904     return true;
905   }
906   
907   return false;
908 }
909
910 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
911 /// global in the specified llvm.used list for which emitUsedDirectiveFor
912 /// is true, as being used with this directive.
913 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
914   // Should be an array of 'i8*'.
915   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
916   if (InitList == 0) return;
917   
918   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
919     const GlobalValue *GV =
920       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
921     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
922       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
923   }
924 }
925
926 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the 
927 /// function pointers, ignoring the init priority.
928 void AsmPrinter::EmitXXStructorList(Constant *List) {
929   // Should be an array of '{ int, void ()* }' structs.  The first value is the
930   // init priority, which we ignore.
931   if (!isa<ConstantArray>(List)) return;
932   ConstantArray *InitList = cast<ConstantArray>(List);
933   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
934     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
935       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
936
937       if (CS->getOperand(1)->isNullValue())
938         return;  // Found a null terminator, exit printing.
939       // Emit the function pointer.
940       EmitGlobalConstant(CS->getOperand(1));
941     }
942 }
943
944 //===--------------------------------------------------------------------===//
945 // Emission and print routines
946 //
947
948 /// EmitInt8 - Emit a byte directive and value.
949 ///
950 void AsmPrinter::EmitInt8(int Value) const {
951   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
952 }
953
954 /// EmitInt16 - Emit a short directive and value.
955 ///
956 void AsmPrinter::EmitInt16(int Value) const {
957   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
958 }
959
960 /// EmitInt32 - Emit a long directive and value.
961 ///
962 void AsmPrinter::EmitInt32(int Value) const {
963   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
964 }
965
966 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
967 /// in bytes of the directive is specified by Size and Hi/Lo specify the
968 /// labels.  This implicitly uses .set if it is available.
969 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
970                                      unsigned Size) const {
971   // Get the Hi-Lo expression.
972   const MCExpr *Diff = 
973     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
974                             MCSymbolRefExpr::Create(Lo, OutContext),
975                             OutContext);
976   
977   if (!MAI->hasSetDirective()) {
978     OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
979     return;
980   }
981
982   // Otherwise, emit with .set (aka assignment).
983   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
984   OutStreamer.EmitAssignment(SetLabel, Diff);
985   OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
986 }
987
988
989 //===----------------------------------------------------------------------===//
990
991 // EmitAlignment - Emit an alignment directive to the specified power of
992 // two boundary.  For example, if you pass in 3 here, you will get an 8
993 // byte alignment.  If a global value is specified, and if that global has
994 // an explicit alignment requested, it will unconditionally override the
995 // alignment request.  However, if ForcedAlignBits is specified, this value
996 // has final say: the ultimate alignment will be the max of ForcedAlignBits
997 // and the alignment computed with NumBits and the global.
998 //
999 // The algorithm is:
1000 //     Align = NumBits;
1001 //     if (GV && GV->hasalignment) Align = GV->getalignment();
1002 //     Align = std::max(Align, ForcedAlignBits);
1003 //
1004 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV,
1005                                unsigned ForcedAlignBits,
1006                                bool UseFillExpr) const {
1007   if (GV && GV->getAlignment())
1008     NumBits = Log2_32(GV->getAlignment());
1009   NumBits = std::max(NumBits, ForcedAlignBits);
1010   
1011   if (NumBits == 0) return;   // No need to emit alignment.
1012   
1013   if (getCurrentSection()->getKind().isText())
1014     OutStreamer.EmitCodeAlignment(1 << NumBits);
1015   else
1016     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1017 }
1018
1019 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1020 ///
1021 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1022   MCContext &Ctx = AP.OutContext;
1023   
1024   if (CV->isNullValue() || isa<UndefValue>(CV))
1025     return MCConstantExpr::Create(0, Ctx);
1026
1027   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1028     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1029   
1030   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1031     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1032   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1033     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1034   
1035   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1036   if (CE == 0) {
1037     llvm_unreachable("Unknown constant value to lower!");
1038     return MCConstantExpr::Create(0, Ctx);
1039   }
1040   
1041   switch (CE->getOpcode()) {
1042   default:
1043     // If the code isn't optimized, there may be outstanding folding
1044     // opportunities. Attempt to fold the expression using TargetData as a
1045     // last resort before giving up.
1046     if (Constant *C =
1047           ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1048       if (C != CE)
1049         return LowerConstant(C, AP);
1050 #ifndef NDEBUG
1051     CE->dump();
1052 #endif
1053     llvm_unreachable("FIXME: Don't support this constant expr");
1054   case Instruction::GetElementPtr: {
1055     const TargetData &TD = *AP.TM.getTargetData();
1056     // Generate a symbolic expression for the byte address
1057     const Constant *PtrVal = CE->getOperand(0);
1058     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1059     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1060                                          IdxVec.size());
1061     
1062     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1063     if (Offset == 0)
1064       return Base;
1065     
1066     // Truncate/sext the offset to the pointer size.
1067     if (TD.getPointerSizeInBits() != 64) {
1068       int SExtAmount = 64-TD.getPointerSizeInBits();
1069       Offset = (Offset << SExtAmount) >> SExtAmount;
1070     }
1071     
1072     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1073                                    Ctx);
1074   }
1075       
1076   case Instruction::Trunc:
1077     // We emit the value and depend on the assembler to truncate the generated
1078     // expression properly.  This is important for differences between
1079     // blockaddress labels.  Since the two labels are in the same function, it
1080     // is reasonable to treat their delta as a 32-bit value.
1081     // FALL THROUGH.
1082   case Instruction::BitCast:
1083     return LowerConstant(CE->getOperand(0), AP);
1084
1085   case Instruction::IntToPtr: {
1086     const TargetData &TD = *AP.TM.getTargetData();
1087     // Handle casts to pointers by changing them into casts to the appropriate
1088     // integer type.  This promotes constant folding and simplifies this code.
1089     Constant *Op = CE->getOperand(0);
1090     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1091                                       false/*ZExt*/);
1092     return LowerConstant(Op, AP);
1093   }
1094     
1095   case Instruction::PtrToInt: {
1096     const TargetData &TD = *AP.TM.getTargetData();
1097     // Support only foldable casts to/from pointers that can be eliminated by
1098     // changing the pointer to the appropriately sized integer type.
1099     Constant *Op = CE->getOperand(0);
1100     const Type *Ty = CE->getType();
1101
1102     const MCExpr *OpExpr = LowerConstant(Op, AP);
1103
1104     // We can emit the pointer value into this slot if the slot is an
1105     // integer slot equal to the size of the pointer.
1106     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1107       return OpExpr;
1108
1109     // Otherwise the pointer is smaller than the resultant integer, mask off
1110     // the high bits so we are sure to get a proper truncation if the input is
1111     // a constant expr.
1112     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1113     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1114     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1115   }
1116       
1117   // The MC library also has a right-shift operator, but it isn't consistently
1118   // signed or unsigned between different targets.
1119   case Instruction::Add:
1120   case Instruction::Sub:
1121   case Instruction::Mul:
1122   case Instruction::SDiv:
1123   case Instruction::SRem:
1124   case Instruction::Shl:
1125   case Instruction::And:
1126   case Instruction::Or:
1127   case Instruction::Xor: {
1128     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1129     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1130     switch (CE->getOpcode()) {
1131     default: llvm_unreachable("Unknown binary operator constant cast expr");
1132     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1133     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1134     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1135     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1136     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1137     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1138     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1139     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1140     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1141     }
1142   }
1143   }
1144 }
1145
1146 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1147                                     AsmPrinter &AP) {
1148   if (AddrSpace != 0 || !CA->isString()) {
1149     // Not a string.  Print the values in successive locations
1150     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1151       AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace);
1152     return;
1153   }
1154   
1155   // Otherwise, it can be emitted as .ascii.
1156   SmallVector<char, 128> TmpVec;
1157   TmpVec.reserve(CA->getNumOperands());
1158   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1159     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1160
1161   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1162 }
1163
1164 static void EmitGlobalConstantVector(const ConstantVector *CV,
1165                                      unsigned AddrSpace, AsmPrinter &AP) {
1166   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1167     AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace);
1168 }
1169
1170 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1171                                      unsigned AddrSpace, AsmPrinter &AP) {
1172   // Print the fields in successive locations. Pad to align if needed!
1173   const TargetData *TD = AP.TM.getTargetData();
1174   unsigned Size = TD->getTypeAllocSize(CS->getType());
1175   const StructLayout *Layout = TD->getStructLayout(CS->getType());
1176   uint64_t SizeSoFar = 0;
1177   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1178     const Constant *Field = CS->getOperand(i);
1179
1180     // Check if padding is needed and insert one or more 0s.
1181     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1182     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1183                         - Layout->getElementOffset(i)) - FieldSize;
1184     SizeSoFar += FieldSize + PadSize;
1185
1186     // Now print the actual field value.
1187     AP.EmitGlobalConstant(Field, AddrSpace);
1188
1189     // Insert padding - this may include padding to increase the size of the
1190     // current field up to the ABI size (if the struct is not packed) as well
1191     // as padding to ensure that the next field starts at the right offset.
1192     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1193   }
1194   assert(SizeSoFar == Layout->getSizeInBytes() &&
1195          "Layout of constant struct may be incorrect!");
1196 }
1197
1198 static void EmitGlobalConstantUnion(const ConstantUnion *CU, 
1199                                     unsigned AddrSpace, AsmPrinter &AP) {
1200   const TargetData *TD = AP.TM.getTargetData();
1201   unsigned Size = TD->getTypeAllocSize(CU->getType());
1202
1203   const Constant *Contents = CU->getOperand(0);
1204   unsigned FilledSize = TD->getTypeAllocSize(Contents->getType());
1205     
1206   // Print the actually filled part
1207   AP.EmitGlobalConstant(Contents, AddrSpace);
1208
1209   // And pad with enough zeroes
1210   AP.OutStreamer.EmitZeros(Size-FilledSize, AddrSpace);
1211 }
1212
1213 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1214                                  AsmPrinter &AP) {
1215   // FP Constants are printed as integer constants to avoid losing
1216   // precision.
1217   if (CFP->getType()->isDoubleTy()) {
1218     if (AP.isVerbose()) {
1219       double Val = CFP->getValueAPF().convertToDouble();
1220       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1221     }
1222
1223     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1224     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1225     return;
1226   }
1227   
1228   if (CFP->getType()->isFloatTy()) {
1229     if (AP.isVerbose()) {
1230       float Val = CFP->getValueAPF().convertToFloat();
1231       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1232     }
1233     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1234     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1235     return;
1236   }
1237   
1238   if (CFP->getType()->isX86_FP80Ty()) {
1239     // all long double variants are printed as hex
1240     // api needed to prevent premature destruction
1241     APInt API = CFP->getValueAPF().bitcastToAPInt();
1242     const uint64_t *p = API.getRawData();
1243     if (AP.isVerbose()) {
1244       // Convert to double so we can print the approximate val as a comment.
1245       APFloat DoubleVal = CFP->getValueAPF();
1246       bool ignored;
1247       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1248                         &ignored);
1249       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1250         << DoubleVal.convertToDouble() << '\n';
1251     }
1252     
1253     if (AP.TM.getTargetData()->isBigEndian()) {
1254       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1255       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1256     } else {
1257       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1258       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1259     }
1260     
1261     // Emit the tail padding for the long double.
1262     const TargetData &TD = *AP.TM.getTargetData();
1263     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1264                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1265     return;
1266   }
1267   
1268   assert(CFP->getType()->isPPC_FP128Ty() &&
1269          "Floating point constant type not handled");
1270   // All long double variants are printed as hex api needed to prevent
1271   // premature destruction.
1272   APInt API = CFP->getValueAPF().bitcastToAPInt();
1273   const uint64_t *p = API.getRawData();
1274   if (AP.TM.getTargetData()->isBigEndian()) {
1275     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1276     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1277   } else {
1278     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1279     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1280   }
1281 }
1282
1283 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1284                                        unsigned AddrSpace, AsmPrinter &AP) {
1285   const TargetData *TD = AP.TM.getTargetData();
1286   unsigned BitWidth = CI->getBitWidth();
1287   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1288
1289   // We don't expect assemblers to support integer data directives
1290   // for more than 64 bits, so we emit the data in at most 64-bit
1291   // quantities at a time.
1292   const uint64_t *RawData = CI->getValue().getRawData();
1293   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1294     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1295     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1296   }
1297 }
1298
1299 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1300 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1301   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1302     uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1303     if (Size == 0) Size = 1; // An empty "_foo:" followed by a section is undef.
1304     return OutStreamer.EmitZeros(Size, AddrSpace);
1305   }
1306
1307   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1308     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1309     switch (Size) {
1310     case 1:
1311     case 2:
1312     case 4:
1313     case 8:
1314       if (isVerbose())
1315         OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1316       OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1317       return;
1318     default:
1319       EmitGlobalConstantLargeInt(CI, AddrSpace, *this);
1320       return;
1321     }
1322   }
1323   
1324   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1325     return EmitGlobalConstantArray(CVA, AddrSpace, *this);
1326   
1327   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1328     return EmitGlobalConstantStruct(CVS, AddrSpace, *this);
1329
1330   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1331     return EmitGlobalConstantFP(CFP, AddrSpace, *this);
1332
1333   if (isa<ConstantPointerNull>(CV)) {
1334     unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1335     OutStreamer.EmitIntValue(0, Size, AddrSpace);
1336     return;
1337   }
1338   
1339   if (const ConstantUnion *CVU = dyn_cast<ConstantUnion>(CV))
1340     return EmitGlobalConstantUnion(CVU, AddrSpace, *this);
1341   
1342   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1343     return EmitGlobalConstantVector(V, AddrSpace, *this);
1344   
1345   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1346   // thread the streamer with EmitValue.
1347   OutStreamer.EmitValue(LowerConstant(CV, *this),
1348                         TM.getTargetData()->getTypeAllocSize(CV->getType()),
1349                         AddrSpace);
1350 }
1351
1352 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1353   // Target doesn't support this yet!
1354   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1355 }
1356
1357 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1358   if (Offset > 0)
1359     OS << '+' << Offset;
1360   else if (Offset < 0)
1361     OS << Offset;
1362 }
1363
1364 //===----------------------------------------------------------------------===//
1365 // Symbol Lowering Routines.
1366 //===----------------------------------------------------------------------===//
1367
1368 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1369 /// temporary label with the specified stem and unique ID.
1370 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1371   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1372                                       Name + Twine(ID));
1373 }
1374
1375 /// GetTempSymbol - Return an assembler temporary label with the specified
1376 /// stem.
1377 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1378   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1379                                       Name);
1380 }
1381
1382
1383 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1384   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1385 }
1386
1387 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1388   return MMI->getAddrLabelSymbol(BB);
1389 }
1390
1391 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1392 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1393   return OutContext.GetOrCreateSymbol
1394     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1395      + "_" + Twine(CPID));
1396 }
1397
1398 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1399 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1400   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1401 }
1402
1403 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1404 /// FIXME: privatize to AsmPrinter.
1405 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1406   return OutContext.GetOrCreateSymbol
1407   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1408    Twine(UID) + "_set_" + Twine(MBBID));
1409 }
1410
1411 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1412 /// global value name as its base, with the specified suffix, and where the
1413 /// symbol is forced to have private linkage if ForcePrivate is true.
1414 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1415                                                    StringRef Suffix,
1416                                                    bool ForcePrivate) const {
1417   SmallString<60> NameStr;
1418   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1419   NameStr.append(Suffix.begin(), Suffix.end());
1420   return OutContext.GetOrCreateSymbol(NameStr.str());
1421 }
1422
1423 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1424 /// ExternalSymbol.
1425 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1426   SmallString<60> NameStr;
1427   Mang->getNameWithPrefix(NameStr, Sym);
1428   return OutContext.GetOrCreateSymbol(NameStr.str());
1429 }  
1430
1431
1432
1433 /// PrintParentLoopComment - Print comments about parent loops of this one.
1434 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1435                                    unsigned FunctionNumber) {
1436   if (Loop == 0) return;
1437   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1438   OS.indent(Loop->getLoopDepth()*2)
1439     << "Parent Loop BB" << FunctionNumber << "_"
1440     << Loop->getHeader()->getNumber()
1441     << " Depth=" << Loop->getLoopDepth() << '\n';
1442 }
1443
1444
1445 /// PrintChildLoopComment - Print comments about child loops within
1446 /// the loop for this basic block, with nesting.
1447 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1448                                   unsigned FunctionNumber) {
1449   // Add child loop information
1450   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1451     OS.indent((*CL)->getLoopDepth()*2)
1452       << "Child Loop BB" << FunctionNumber << "_"
1453       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1454       << '\n';
1455     PrintChildLoopComment(OS, *CL, FunctionNumber);
1456   }
1457 }
1458
1459 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1460 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1461                                        const MachineLoopInfo *LI,
1462                                        const AsmPrinter &AP) {
1463   // Add loop depth information
1464   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1465   if (Loop == 0) return;
1466   
1467   MachineBasicBlock *Header = Loop->getHeader();
1468   assert(Header && "No header for loop");
1469   
1470   // If this block is not a loop header, just print out what is the loop header
1471   // and return.
1472   if (Header != &MBB) {
1473     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1474                               Twine(AP.getFunctionNumber())+"_" +
1475                               Twine(Loop->getHeader()->getNumber())+
1476                               " Depth="+Twine(Loop->getLoopDepth()));
1477     return;
1478   }
1479   
1480   // Otherwise, it is a loop header.  Print out information about child and
1481   // parent loops.
1482   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1483   
1484   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 
1485   
1486   OS << "=>";
1487   OS.indent(Loop->getLoopDepth()*2-2);
1488   
1489   OS << "This ";
1490   if (Loop->empty())
1491     OS << "Inner ";
1492   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1493   
1494   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1495 }
1496
1497
1498 /// EmitBasicBlockStart - This method prints the label for the specified
1499 /// MachineBasicBlock, an alignment (if present) and a comment describing
1500 /// it if appropriate.
1501 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1502   // Emit an alignment directive for this block, if needed.
1503   if (unsigned Align = MBB->getAlignment())
1504     EmitAlignment(Log2_32(Align));
1505
1506   // If the block has its address taken, emit any labels that were used to
1507   // reference the block.  It is possible that there is more than one label
1508   // here, because multiple LLVM BB's may have been RAUW'd to this block after
1509   // the references were generated.
1510   if (MBB->hasAddressTaken()) {
1511     const BasicBlock *BB = MBB->getBasicBlock();
1512     if (isVerbose())
1513       OutStreamer.AddComment("Block address taken");
1514     
1515     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1516
1517     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1518       OutStreamer.EmitLabel(Syms[i]);
1519   }
1520
1521   // Print the main label for the block.
1522   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1523     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1524       if (const BasicBlock *BB = MBB->getBasicBlock())
1525         if (BB->hasName())
1526           OutStreamer.AddComment("%" + BB->getName());
1527       
1528       EmitBasicBlockLoopComments(*MBB, LI, *this);
1529       
1530       // NOTE: Want this comment at start of line, don't emit with AddComment.
1531       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1532                               Twine(MBB->getNumber()) + ":");
1533     }
1534   } else {
1535     if (isVerbose()) {
1536       if (const BasicBlock *BB = MBB->getBasicBlock())
1537         if (BB->hasName())
1538           OutStreamer.AddComment("%" + BB->getName());
1539       EmitBasicBlockLoopComments(*MBB, LI, *this);
1540     }
1541
1542     OutStreamer.EmitLabel(MBB->getSymbol());
1543   }
1544 }
1545
1546 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const {
1547   MCSymbolAttr Attr = MCSA_Invalid;
1548   
1549   switch (Visibility) {
1550   default: break;
1551   case GlobalValue::HiddenVisibility:
1552     Attr = MAI->getHiddenVisibilityAttr();
1553     break;
1554   case GlobalValue::ProtectedVisibility:
1555     Attr = MAI->getProtectedVisibilityAttr();
1556     break;
1557   }
1558
1559   if (Attr != MCSA_Invalid)
1560     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1561 }
1562
1563 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1564 /// exactly one predecessor and the control transfer mechanism between
1565 /// the predecessor and this block is a fall-through.
1566 bool AsmPrinter::
1567 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1568   // If this is a landing pad, it isn't a fall through.  If it has no preds,
1569   // then nothing falls through to it.
1570   if (MBB->isLandingPad() || MBB->pred_empty())
1571     return false;
1572   
1573   // If there isn't exactly one predecessor, it can't be a fall through.
1574   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1575   ++PI2;
1576   if (PI2 != MBB->pred_end())
1577     return false;
1578   
1579   // The predecessor has to be immediately before this block.
1580   const MachineBasicBlock *Pred = *PI;
1581   
1582   if (!Pred->isLayoutSuccessor(MBB))
1583     return false;
1584   
1585   // If the block is completely empty, then it definitely does fall through.
1586   if (Pred->empty())
1587     return true;
1588   
1589   // Otherwise, check the last instruction.
1590   const MachineInstr &LastInst = Pred->back();
1591   return !LastInst.getDesc().isBarrier();
1592 }
1593
1594
1595
1596 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1597   if (!S->usesMetadata())
1598     return 0;
1599
1600   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1601   gcp_map_type::iterator GCPI = GCMap.find(S);
1602   if (GCPI != GCMap.end())
1603     return GCPI->second;
1604   
1605   const char *Name = S->getName().c_str();
1606   
1607   for (GCMetadataPrinterRegistry::iterator
1608          I = GCMetadataPrinterRegistry::begin(),
1609          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1610     if (strcmp(Name, I->getName()) == 0) {
1611       GCMetadataPrinter *GMP = I->instantiate();
1612       GMP->S = S;
1613       GCMap.insert(std::make_pair(S, GMP));
1614       return GMP;
1615     }
1616   
1617   llvm_report_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1618   return 0;
1619 }
1620