1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
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 library implements the functionality defined in llvm/Assembly/Writer.h
11 //
12 // Note that these routines must be extremely tolerant of various errors in the
13 // LLVM code, because it can be used for debugging transformations.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Module.h"
28 #include "llvm/ValueSymbolTable.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include <algorithm>
40 #include <cctype>
41 using namespace llvm;
42
43 // Make virtual table appear in this compilation unit.
~AssemblyAnnotationWriter()44 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
45
46 //===----------------------------------------------------------------------===//
47 // Helper Functions
48 //===----------------------------------------------------------------------===//
49
getModuleFromVal(const Value * V)50 static const Module *getModuleFromVal(const Value *V) {
51 if (const Argument *MA = dyn_cast<Argument>(V))
52 return MA->getParent() ? MA->getParent()->getParent() : 0;
53
54 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
55 return BB->getParent() ? BB->getParent()->getParent() : 0;
56
57 if (const Instruction *I = dyn_cast<Instruction>(V)) {
58 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
59 return M ? M->getParent() : 0;
60 }
61
62 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
63 return GV->getParent();
64 return 0;
65 }
66
67 // PrintEscapedString - Print each character of the specified string, escaping
68 // it if it is not printable or if it is an escape char.
PrintEscapedString(StringRef Name,raw_ostream & Out)69 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
70 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
71 unsigned char C = Name[i];
72 if (isprint(C) && C != '\\' && C != '"')
73 Out << C;
74 else
75 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
76 }
77 }
78
79 enum PrefixType {
80 GlobalPrefix,
81 LabelPrefix,
82 LocalPrefix,
83 NoPrefix
84 };
85
86 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
87 /// prefixed with % (if the string only contains simple characters) or is
88 /// surrounded with ""'s (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,StringRef Name,PrefixType Prefix)89 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
90 assert(!Name.empty() && "Cannot get empty name!");
91 switch (Prefix) {
92 default: llvm_unreachable("Bad prefix!");
93 case NoPrefix: break;
94 case GlobalPrefix: OS << '@'; break;
95 case LabelPrefix: break;
96 case LocalPrefix: OS << '%'; break;
97 }
98
99 // Scan the name to see if it needs quotes first.
100 bool NeedsQuotes = isdigit(Name[0]);
101 if (!NeedsQuotes) {
102 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
103 char C = Name[i];
104 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
105 NeedsQuotes = true;
106 break;
107 }
108 }
109 }
110
111 // If we didn't need any quotes, just write out the name in one blast.
112 if (!NeedsQuotes) {
113 OS << Name;
114 return;
115 }
116
117 // Okay, we need quotes. Output the quotes and escape any scary characters as
118 // needed.
119 OS << '"';
120 PrintEscapedString(Name, OS);
121 OS << '"';
122 }
123
124 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
125 /// prefixed with % (if the string only contains simple characters) or is
126 /// surrounded with ""'s (if it has special chars in it). Print it out.
PrintLLVMName(raw_ostream & OS,const Value * V)127 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
128 PrintLLVMName(OS, V->getName(),
129 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
130 }
131
132 //===----------------------------------------------------------------------===//
133 // TypePrinting Class: Type printing machinery
134 //===----------------------------------------------------------------------===//
135
136 /// TypePrinting - Type printing machinery.
137 namespace {
138 class TypePrinting {
139 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
140 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
141 public:
142
143 /// NamedTypes - The named types that are used by the current module.
144 std::vector<StructType*> NamedTypes;
145
146 /// NumberedTypes - The numbered types, along with their value.
147 DenseMap<StructType*, unsigned> NumberedTypes;
148
149
TypePrinting()150 TypePrinting() {}
~TypePrinting()151 ~TypePrinting() {}
152
153 void incorporateTypes(const Module &M);
154
155 void print(Type *Ty, raw_ostream &OS);
156
157 void printStructBody(StructType *Ty, raw_ostream &OS);
158 };
159 } // end anonymous namespace.
160
161
incorporateTypes(const Module & M)162 void TypePrinting::incorporateTypes(const Module &M) {
163 M.findUsedStructTypes(NamedTypes);
164
165 // The list of struct types we got back includes all the struct types, split
166 // the unnamed ones out to a numbering and remove the anonymous structs.
167 unsigned NextNumber = 0;
168
169 std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
170 for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
171 StructType *STy = *I;
172
173 // Ignore anonymous types.
174 if (STy->isLiteral())
175 continue;
176
177 if (STy->getName().empty())
178 NumberedTypes[STy] = NextNumber++;
179 else
180 *NextToUse++ = STy;
181 }
182
183 NamedTypes.erase(NextToUse, NamedTypes.end());
184 }
185
186
187 /// CalcTypeName - Write the specified type to the specified raw_ostream, making
188 /// use of type names or up references to shorten the type name where possible.
print(Type * Ty,raw_ostream & OS)189 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
190 switch (Ty->getTypeID()) {
191 case Type::VoidTyID: OS << "void"; break;
192 case Type::FloatTyID: OS << "float"; break;
193 case Type::DoubleTyID: OS << "double"; break;
194 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
195 case Type::FP128TyID: OS << "fp128"; break;
196 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
197 case Type::LabelTyID: OS << "label"; break;
198 case Type::MetadataTyID: OS << "metadata"; break;
199 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
200 case Type::IntegerTyID:
201 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
202 return;
203
204 case Type::FunctionTyID: {
205 FunctionType *FTy = cast<FunctionType>(Ty);
206 print(FTy->getReturnType(), OS);
207 OS << " (";
208 for (FunctionType::param_iterator I = FTy->param_begin(),
209 E = FTy->param_end(); I != E; ++I) {
210 if (I != FTy->param_begin())
211 OS << ", ";
212 print(*I, OS);
213 }
214 if (FTy->isVarArg()) {
215 if (FTy->getNumParams()) OS << ", ";
216 OS << "...";
217 }
218 OS << ')';
219 return;
220 }
221 case Type::StructTyID: {
222 StructType *STy = cast<StructType>(Ty);
223
224 if (STy->isLiteral())
225 return printStructBody(STy, OS);
226
227 if (!STy->getName().empty())
228 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
229
230 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
231 if (I != NumberedTypes.end())
232 OS << '%' << I->second;
233 else // Not enumerated, print the hex address.
234 OS << "%\"type 0x" << STy << '\"';
235 return;
236 }
237 case Type::PointerTyID: {
238 PointerType *PTy = cast<PointerType>(Ty);
239 print(PTy->getElementType(), OS);
240 if (unsigned AddressSpace = PTy->getAddressSpace())
241 OS << " addrspace(" << AddressSpace << ')';
242 OS << '*';
243 return;
244 }
245 case Type::ArrayTyID: {
246 ArrayType *ATy = cast<ArrayType>(Ty);
247 OS << '[' << ATy->getNumElements() << " x ";
248 print(ATy->getElementType(), OS);
249 OS << ']';
250 return;
251 }
252 case Type::VectorTyID: {
253 VectorType *PTy = cast<VectorType>(Ty);
254 OS << "<" << PTy->getNumElements() << " x ";
255 print(PTy->getElementType(), OS);
256 OS << '>';
257 return;
258 }
259 default:
260 OS << "<unrecognized-type>";
261 return;
262 }
263 }
264
printStructBody(StructType * STy,raw_ostream & OS)265 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
266 if (STy->isOpaque()) {
267 OS << "opaque";
268 return;
269 }
270
271 if (STy->isPacked())
272 OS << '<';
273
274 if (STy->getNumElements() == 0) {
275 OS << "{}";
276 } else {
277 StructType::element_iterator I = STy->element_begin();
278 OS << "{ ";
279 print(*I++, OS);
280 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
281 OS << ", ";
282 print(*I, OS);
283 }
284
285 OS << " }";
286 }
287 if (STy->isPacked())
288 OS << '>';
289 }
290
291
292
293 //===----------------------------------------------------------------------===//
294 // SlotTracker Class: Enumerate slot numbers for unnamed values
295 //===----------------------------------------------------------------------===//
296
297 namespace {
298
299 /// This class provides computation of slot numbers for LLVM Assembly writing.
300 ///
301 class SlotTracker {
302 public:
303 /// ValueMap - A mapping of Values to slot numbers.
304 typedef DenseMap<const Value*, unsigned> ValueMap;
305
306 private:
307 /// TheModule - The module for which we are holding slot numbers.
308 const Module* TheModule;
309
310 /// TheFunction - The function for which we are holding slot numbers.
311 const Function* TheFunction;
312 bool FunctionProcessed;
313
314 /// mMap - The slot map for the module level data.
315 ValueMap mMap;
316 unsigned mNext;
317
318 /// fMap - The slot map for the function level data.
319 ValueMap fMap;
320 unsigned fNext;
321
322 /// mdnMap - Map for MDNodes.
323 DenseMap<const MDNode*, unsigned> mdnMap;
324 unsigned mdnNext;
325 public:
326 /// Construct from a module
327 explicit SlotTracker(const Module *M);
328 /// Construct from a function, starting out in incorp state.
329 explicit SlotTracker(const Function *F);
330
331 /// Return the slot number of the specified value in it's type
332 /// plane. If something is not in the SlotTracker, return -1.
333 int getLocalSlot(const Value *V);
334 int getGlobalSlot(const GlobalValue *V);
335 int getMetadataSlot(const MDNode *N);
336
337 /// If you'd like to deal with a function instead of just a module, use
338 /// this method to get its data into the SlotTracker.
incorporateFunction(const Function * F)339 void incorporateFunction(const Function *F) {
340 TheFunction = F;
341 FunctionProcessed = false;
342 }
343
344 /// After calling incorporateFunction, use this method to remove the
345 /// most recently incorporated function from the SlotTracker. This
346 /// will reset the state of the machine back to just the module contents.
347 void purgeFunction();
348
349 /// MDNode map iterators.
350 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
mdn_begin()351 mdn_iterator mdn_begin() { return mdnMap.begin(); }
mdn_end()352 mdn_iterator mdn_end() { return mdnMap.end(); }
mdn_size() const353 unsigned mdn_size() const { return mdnMap.size(); }
mdn_empty() const354 bool mdn_empty() const { return mdnMap.empty(); }
355
356 /// This function does the actual initialization.
357 inline void initialize();
358
359 // Implementation Details
360 private:
361 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
362 void CreateModuleSlot(const GlobalValue *V);
363
364 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
365 void CreateMetadataSlot(const MDNode *N);
366
367 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
368 void CreateFunctionSlot(const Value *V);
369
370 /// Add all of the module level global variables (and their initializers)
371 /// and function declarations, but not the contents of those functions.
372 void processModule();
373
374 /// Add all of the functions arguments, basic blocks, and instructions.
375 void processFunction();
376
377 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
378 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
379 };
380
381 } // end anonymous namespace
382
383
createSlotTracker(const Value * V)384 static SlotTracker *createSlotTracker(const Value *V) {
385 if (const Argument *FA = dyn_cast<Argument>(V))
386 return new SlotTracker(FA->getParent());
387
388 if (const Instruction *I = dyn_cast<Instruction>(V))
389 if (I->getParent())
390 return new SlotTracker(I->getParent()->getParent());
391
392 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
393 return new SlotTracker(BB->getParent());
394
395 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
396 return new SlotTracker(GV->getParent());
397
398 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
399 return new SlotTracker(GA->getParent());
400
401 if (const Function *Func = dyn_cast<Function>(V))
402 return new SlotTracker(Func);
403
404 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
405 if (!MD->isFunctionLocal())
406 return new SlotTracker(MD->getFunction());
407
408 return new SlotTracker((Function *)0);
409 }
410
411 return 0;
412 }
413
414 #if 0
415 #define ST_DEBUG(X) dbgs() << X
416 #else
417 #define ST_DEBUG(X)
418 #endif
419
420 // Module level constructor. Causes the contents of the Module (sans functions)
421 // to be added to the slot table.
SlotTracker(const Module * M)422 SlotTracker::SlotTracker(const Module *M)
423 : TheModule(M), TheFunction(0), FunctionProcessed(false),
424 mNext(0), fNext(0), mdnNext(0) {
425 }
426
427 // Function level constructor. Causes the contents of the Module and the one
428 // function provided to be added to the slot table.
SlotTracker(const Function * F)429 SlotTracker::SlotTracker(const Function *F)
430 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
431 mNext(0), fNext(0), mdnNext(0) {
432 }
433
initialize()434 inline void SlotTracker::initialize() {
435 if (TheModule) {
436 processModule();
437 TheModule = 0; ///< Prevent re-processing next time we're called.
438 }
439
440 if (TheFunction && !FunctionProcessed)
441 processFunction();
442 }
443
444 // Iterate through all the global variables, functions, and global
445 // variable initializers and create slots for them.
processModule()446 void SlotTracker::processModule() {
447 ST_DEBUG("begin processModule!\n");
448
449 // Add all of the unnamed global variables to the value table.
450 for (Module::const_global_iterator I = TheModule->global_begin(),
451 E = TheModule->global_end(); I != E; ++I) {
452 if (!I->hasName())
453 CreateModuleSlot(I);
454 }
455
456 // Add metadata used by named metadata.
457 for (Module::const_named_metadata_iterator
458 I = TheModule->named_metadata_begin(),
459 E = TheModule->named_metadata_end(); I != E; ++I) {
460 const NamedMDNode *NMD = I;
461 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
462 CreateMetadataSlot(NMD->getOperand(i));
463 }
464
465 // Add all the unnamed functions to the table.
466 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
467 I != E; ++I)
468 if (!I->hasName())
469 CreateModuleSlot(I);
470
471 ST_DEBUG("end processModule!\n");
472 }
473
474 // Process the arguments, basic blocks, and instructions of a function.
processFunction()475 void SlotTracker::processFunction() {
476 ST_DEBUG("begin processFunction!\n");
477 fNext = 0;
478
479 // Add all the function arguments with no names.
480 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
481 AE = TheFunction->arg_end(); AI != AE; ++AI)
482 if (!AI->hasName())
483 CreateFunctionSlot(AI);
484
485 ST_DEBUG("Inserting Instructions:\n");
486
487 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
488
489 // Add all of the basic blocks and instructions with no names.
490 for (Function::const_iterator BB = TheFunction->begin(),
491 E = TheFunction->end(); BB != E; ++BB) {
492 if (!BB->hasName())
493 CreateFunctionSlot(BB);
494
495 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
496 ++I) {
497 if (!I->getType()->isVoidTy() && !I->hasName())
498 CreateFunctionSlot(I);
499
500 // Intrinsics can directly use metadata. We allow direct calls to any
501 // llvm.foo function here, because the target may not be linked into the
502 // optimizer.
503 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
504 if (Function *F = CI->getCalledFunction())
505 if (F->getName().startswith("llvm."))
506 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
507 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
508 CreateMetadataSlot(N);
509 }
510
511 // Process metadata attached with this instruction.
512 I->getAllMetadata(MDForInst);
513 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
514 CreateMetadataSlot(MDForInst[i].second);
515 MDForInst.clear();
516 }
517 }
518
519 FunctionProcessed = true;
520
521 ST_DEBUG("end processFunction!\n");
522 }
523
524 /// Clean up after incorporating a function. This is the only way to get out of
525 /// the function incorporation state that affects get*Slot/Create*Slot. Function
526 /// incorporation state is indicated by TheFunction != 0.
purgeFunction()527 void SlotTracker::purgeFunction() {
528 ST_DEBUG("begin purgeFunction!\n");
529 fMap.clear(); // Simply discard the function level map
530 TheFunction = 0;
531 FunctionProcessed = false;
532 ST_DEBUG("end purgeFunction!\n");
533 }
534
535 /// getGlobalSlot - Get the slot number of a global value.
getGlobalSlot(const GlobalValue * V)536 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
537 // Check for uninitialized state and do lazy initialization.
538 initialize();
539
540 // Find the value in the module map
541 ValueMap::iterator MI = mMap.find(V);
542 return MI == mMap.end() ? -1 : (int)MI->second;
543 }
544
545 /// getMetadataSlot - Get the slot number of a MDNode.
getMetadataSlot(const MDNode * N)546 int SlotTracker::getMetadataSlot(const MDNode *N) {
547 // Check for uninitialized state and do lazy initialization.
548 initialize();
549
550 // Find the MDNode in the module map
551 mdn_iterator MI = mdnMap.find(N);
552 return MI == mdnMap.end() ? -1 : (int)MI->second;
553 }
554
555
556 /// getLocalSlot - Get the slot number for a value that is local to a function.
getLocalSlot(const Value * V)557 int SlotTracker::getLocalSlot(const Value *V) {
558 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
559
560 // Check for uninitialized state and do lazy initialization.
561 initialize();
562
563 ValueMap::iterator FI = fMap.find(V);
564 return FI == fMap.end() ? -1 : (int)FI->second;
565 }
566
567
568 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
CreateModuleSlot(const GlobalValue * V)569 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
570 assert(V && "Can't insert a null Value into SlotTracker!");
571 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
572 assert(!V->hasName() && "Doesn't need a slot!");
573
574 unsigned DestSlot = mNext++;
575 mMap[V] = DestSlot;
576
577 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
578 DestSlot << " [");
579 // G = Global, F = Function, A = Alias, o = other
580 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
581 (isa<Function>(V) ? 'F' :
582 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
583 }
584
585 /// CreateSlot - Create a new slot for the specified value if it has no name.
CreateFunctionSlot(const Value * V)586 void SlotTracker::CreateFunctionSlot(const Value *V) {
587 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
588
589 unsigned DestSlot = fNext++;
590 fMap[V] = DestSlot;
591
592 // G = Global, F = Function, o = other
593 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
594 DestSlot << " [o]\n");
595 }
596
597 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
CreateMetadataSlot(const MDNode * N)598 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
599 assert(N && "Can't insert a null Value into SlotTracker!");
600
601 // Don't insert if N is a function-local metadata, these are always printed
602 // inline.
603 if (!N->isFunctionLocal()) {
604 mdn_iterator I = mdnMap.find(N);
605 if (I != mdnMap.end())
606 return;
607
608 unsigned DestSlot = mdnNext++;
609 mdnMap[N] = DestSlot;
610 }
611
612 // Recursively add any MDNodes referenced by operands.
613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
614 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
615 CreateMetadataSlot(Op);
616 }
617
618 //===----------------------------------------------------------------------===//
619 // AsmWriter Implementation
620 //===----------------------------------------------------------------------===//
621
622 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
623 TypePrinting *TypePrinter,
624 SlotTracker *Machine,
625 const Module *Context);
626
627
628
getPredicateText(unsigned predicate)629 static const char *getPredicateText(unsigned predicate) {
630 const char * pred = "unknown";
631 switch (predicate) {
632 case FCmpInst::FCMP_FALSE: pred = "false"; break;
633 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
634 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
635 case FCmpInst::FCMP_OGE: pred = "oge"; break;
636 case FCmpInst::FCMP_OLT: pred = "olt"; break;
637 case FCmpInst::FCMP_OLE: pred = "ole"; break;
638 case FCmpInst::FCMP_ONE: pred = "one"; break;
639 case FCmpInst::FCMP_ORD: pred = "ord"; break;
640 case FCmpInst::FCMP_UNO: pred = "uno"; break;
641 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
642 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
643 case FCmpInst::FCMP_UGE: pred = "uge"; break;
644 case FCmpInst::FCMP_ULT: pred = "ult"; break;
645 case FCmpInst::FCMP_ULE: pred = "ule"; break;
646 case FCmpInst::FCMP_UNE: pred = "une"; break;
647 case FCmpInst::FCMP_TRUE: pred = "true"; break;
648 case ICmpInst::ICMP_EQ: pred = "eq"; break;
649 case ICmpInst::ICMP_NE: pred = "ne"; break;
650 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
651 case ICmpInst::ICMP_SGE: pred = "sge"; break;
652 case ICmpInst::ICMP_SLT: pred = "slt"; break;
653 case ICmpInst::ICMP_SLE: pred = "sle"; break;
654 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
655 case ICmpInst::ICMP_UGE: pred = "uge"; break;
656 case ICmpInst::ICMP_ULT: pred = "ult"; break;
657 case ICmpInst::ICMP_ULE: pred = "ule"; break;
658 }
659 return pred;
660 }
661
writeAtomicRMWOperation(raw_ostream & Out,AtomicRMWInst::BinOp Op)662 static void writeAtomicRMWOperation(raw_ostream &Out,
663 AtomicRMWInst::BinOp Op) {
664 switch (Op) {
665 default: Out << " <unknown operation " << Op << ">"; break;
666 case AtomicRMWInst::Xchg: Out << " xchg"; break;
667 case AtomicRMWInst::Add: Out << " add"; break;
668 case AtomicRMWInst::Sub: Out << " sub"; break;
669 case AtomicRMWInst::And: Out << " and"; break;
670 case AtomicRMWInst::Nand: Out << " nand"; break;
671 case AtomicRMWInst::Or: Out << " or"; break;
672 case AtomicRMWInst::Xor: Out << " xor"; break;
673 case AtomicRMWInst::Max: Out << " max"; break;
674 case AtomicRMWInst::Min: Out << " min"; break;
675 case AtomicRMWInst::UMax: Out << " umax"; break;
676 case AtomicRMWInst::UMin: Out << " umin"; break;
677 }
678 }
679
WriteOptimizationInfo(raw_ostream & Out,const User * U)680 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
681 if (const OverflowingBinaryOperator *OBO =
682 dyn_cast<OverflowingBinaryOperator>(U)) {
683 if (OBO->hasNoUnsignedWrap())
684 Out << " nuw";
685 if (OBO->hasNoSignedWrap())
686 Out << " nsw";
687 } else if (const PossiblyExactOperator *Div =
688 dyn_cast<PossiblyExactOperator>(U)) {
689 if (Div->isExact())
690 Out << " exact";
691 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
692 if (GEP->isInBounds())
693 Out << " inbounds";
694 }
695 }
696
WriteConstantInternal(raw_ostream & Out,const Constant * CV,TypePrinting & TypePrinter,SlotTracker * Machine,const Module * Context)697 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
698 TypePrinting &TypePrinter,
699 SlotTracker *Machine,
700 const Module *Context) {
701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
702 if (CI->getType()->isIntegerTy(1)) {
703 Out << (CI->getZExtValue() ? "true" : "false");
704 return;
705 }
706 Out << CI->getValue();
707 return;
708 }
709
710 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
711 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble ||
712 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle) {
713 // We would like to output the FP constant value in exponential notation,
714 // but we cannot do this if doing so will lose precision. Check here to
715 // make sure that we only output it in exponential format if we can parse
716 // the value back and get the same value.
717 //
718 bool ignored;
719 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
720 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
721 CFP->getValueAPF().convertToFloat();
722 SmallString<128> StrVal;
723 raw_svector_ostream(StrVal) << Val;
724
725 // Check to make sure that the stringized number is not some string like
726 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
727 // that the string matches the "[-+]?[0-9]" regex.
728 //
729 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
730 ((StrVal[0] == '-' || StrVal[0] == '+') &&
731 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
732 // Reparse stringized version!
733 if (atof(StrVal.c_str()) == Val) {
734 Out << StrVal.str();
735 return;
736 }
737 }
738 // Otherwise we could not reparse it to exactly the same value, so we must
739 // output the string in hexadecimal format! Note that loading and storing
740 // floating point types changes the bits of NaNs on some hosts, notably
741 // x86, so we must not use these types.
742 assert(sizeof(double) == sizeof(uint64_t) &&
743 "assuming that double is 64 bits!");
744 char Buffer[40];
745 APFloat apf = CFP->getValueAPF();
746 // Floats are represented in ASCII IR as double, convert.
747 if (!isDouble)
748 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
749 &ignored);
750 Out << "0x" <<
751 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
752 Buffer+40);
753 return;
754 }
755
756 // Some form of long double. These appear as a magic letter identifying
757 // the type, then a fixed number of hex digits.
758 Out << "0x";
759 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
760 Out << 'K';
761 // api needed to prevent premature destruction
762 APInt api = CFP->getValueAPF().bitcastToAPInt();
763 const uint64_t* p = api.getRawData();
764 uint64_t word = p[1];
765 int shiftcount=12;
766 int width = api.getBitWidth();
767 for (int j=0; j<width; j+=4, shiftcount-=4) {
768 unsigned int nibble = (word>>shiftcount) & 15;
769 if (nibble < 10)
770 Out << (unsigned char)(nibble + '0');
771 else
772 Out << (unsigned char)(nibble - 10 + 'A');
773 if (shiftcount == 0 && j+4 < width) {
774 word = *p;
775 shiftcount = 64;
776 if (width-j-4 < 64)
777 shiftcount = width-j-4;
778 }
779 }
780 return;
781 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad)
782 Out << 'L';
783 else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble)
784 Out << 'M';
785 else
786 llvm_unreachable("Unsupported floating point type");
787 // api needed to prevent premature destruction
788 APInt api = CFP->getValueAPF().bitcastToAPInt();
789 const uint64_t* p = api.getRawData();
790 uint64_t word = *p;
791 int shiftcount=60;
792 int width = api.getBitWidth();
793 for (int j=0; j<width; j+=4, shiftcount-=4) {
794 unsigned int nibble = (word>>shiftcount) & 15;
795 if (nibble < 10)
796 Out << (unsigned char)(nibble + '0');
797 else
798 Out << (unsigned char)(nibble - 10 + 'A');
799 if (shiftcount == 0 && j+4 < width) {
800 word = *(++p);
801 shiftcount = 64;
802 if (width-j-4 < 64)
803 shiftcount = width-j-4;
804 }
805 }
806 return;
807 }
808
809 if (isa<ConstantAggregateZero>(CV)) {
810 Out << "zeroinitializer";
811 return;
812 }
813
814 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
815 Out << "blockaddress(";
816 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
817 Context);
818 Out << ", ";
819 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
820 Context);
821 Out << ")";
822 return;
823 }
824
825 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
826 // As a special case, print the array as a string if it is an array of
827 // i8 with ConstantInt values.
828 //
829 Type *ETy = CA->getType()->getElementType();
830 if (CA->isString()) {
831 Out << "c\"";
832 PrintEscapedString(CA->getAsString(), Out);
833 Out << '"';
834 } else { // Cannot output in string format...
835 Out << '[';
836 if (CA->getNumOperands()) {
837 TypePrinter.print(ETy, Out);
838 Out << ' ';
839 WriteAsOperandInternal(Out, CA->getOperand(0),
840 &TypePrinter, Machine,
841 Context);
842 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
843 Out << ", ";
844 TypePrinter.print(ETy, Out);
845 Out << ' ';
846 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
847 Context);
848 }
849 }
850 Out << ']';
851 }
852 return;
853 }
854
855 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
856 if (CS->getType()->isPacked())
857 Out << '<';
858 Out << '{';
859 unsigned N = CS->getNumOperands();
860 if (N) {
861 Out << ' ';
862 TypePrinter.print(CS->getOperand(0)->getType(), Out);
863 Out << ' ';
864
865 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
866 Context);
867
868 for (unsigned i = 1; i < N; i++) {
869 Out << ", ";
870 TypePrinter.print(CS->getOperand(i)->getType(), Out);
871 Out << ' ';
872
873 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
874 Context);
875 }
876 Out << ' ';
877 }
878
879 Out << '}';
880 if (CS->getType()->isPacked())
881 Out << '>';
882 return;
883 }
884
885 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
886 Type *ETy = CP->getType()->getElementType();
887 assert(CP->getNumOperands() > 0 &&
888 "Number of operands for a PackedConst must be > 0");
889 Out << '<';
890 TypePrinter.print(ETy, Out);
891 Out << ' ';
892 WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
893 Context);
894 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
895 Out << ", ";
896 TypePrinter.print(ETy, Out);
897 Out << ' ';
898 WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
899 Context);
900 }
901 Out << '>';
902 return;
903 }
904
905 if (isa<ConstantPointerNull>(CV)) {
906 Out << "null";
907 return;
908 }
909
910 if (isa<UndefValue>(CV)) {
911 Out << "undef";
912 return;
913 }
914
915 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
916 Out << CE->getOpcodeName();
917 WriteOptimizationInfo(Out, CE);
918 if (CE->isCompare())
919 Out << ' ' << getPredicateText(CE->getPredicate());
920 Out << " (";
921
922 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
923 TypePrinter.print((*OI)->getType(), Out);
924 Out << ' ';
925 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
926 if (OI+1 != CE->op_end())
927 Out << ", ";
928 }
929
930 if (CE->hasIndices()) {
931 ArrayRef<unsigned> Indices = CE->getIndices();
932 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
933 Out << ", " << Indices[i];
934 }
935
936 if (CE->isCast()) {
937 Out << " to ";
938 TypePrinter.print(CE->getType(), Out);
939 }
940
941 Out << ')';
942 return;
943 }
944
945 Out << "<placeholder or erroneous Constant>";
946 }
947
WriteMDNodeBodyInternal(raw_ostream & Out,const MDNode * Node,TypePrinting * TypePrinter,SlotTracker * Machine,const Module * Context)948 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
949 TypePrinting *TypePrinter,
950 SlotTracker *Machine,
951 const Module *Context) {
952 Out << "!{";
953 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
954 const Value *V = Node->getOperand(mi);
955 if (V == 0)
956 Out << "null";
957 else {
958 TypePrinter->print(V->getType(), Out);
959 Out << ' ';
960 WriteAsOperandInternal(Out, Node->getOperand(mi),
961 TypePrinter, Machine, Context);
962 }
963 if (mi + 1 != me)
964 Out << ", ";
965 }
966
967 Out << "}";
968 }
969
970
971 /// WriteAsOperand - Write the name of the specified value out to the specified
972 /// ostream. This can be useful when you just want to print int %reg126, not
973 /// the whole instruction that generated it.
974 ///
WriteAsOperandInternal(raw_ostream & Out,const Value * V,TypePrinting * TypePrinter,SlotTracker * Machine,const Module * Context)975 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
976 TypePrinting *TypePrinter,
977 SlotTracker *Machine,
978 const Module *Context) {
979 if (V->hasName()) {
980 PrintLLVMName(Out, V);
981 return;
982 }
983
984 const Constant *CV = dyn_cast<Constant>(V);
985 if (CV && !isa<GlobalValue>(CV)) {
986 assert(TypePrinter && "Constants require TypePrinting!");
987 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
988 return;
989 }
990
991 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
992 Out << "asm ";
993 if (IA->hasSideEffects())
994 Out << "sideeffect ";
995 if (IA->isAlignStack())
996 Out << "alignstack ";
997 Out << '"';
998 PrintEscapedString(IA->getAsmString(), Out);
999 Out << "\", \"";
1000 PrintEscapedString(IA->getConstraintString(), Out);
1001 Out << '"';
1002 return;
1003 }
1004
1005 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1006 if (N->isFunctionLocal()) {
1007 // Print metadata inline, not via slot reference number.
1008 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1009 return;
1010 }
1011
1012 if (!Machine) {
1013 if (N->isFunctionLocal())
1014 Machine = new SlotTracker(N->getFunction());
1015 else
1016 Machine = new SlotTracker(Context);
1017 }
1018 int Slot = Machine->getMetadataSlot(N);
1019 if (Slot == -1)
1020 Out << "<badref>";
1021 else
1022 Out << '!' << Slot;
1023 return;
1024 }
1025
1026 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1027 Out << "!\"";
1028 PrintEscapedString(MDS->getString(), Out);
1029 Out << '"';
1030 return;
1031 }
1032
1033 if (V->getValueID() == Value::PseudoSourceValueVal ||
1034 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1035 V->print(Out);
1036 return;
1037 }
1038
1039 char Prefix = '%';
1040 int Slot;
1041 // If we have a SlotTracker, use it.
1042 if (Machine) {
1043 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1044 Slot = Machine->getGlobalSlot(GV);
1045 Prefix = '@';
1046 } else {
1047 Slot = Machine->getLocalSlot(V);
1048
1049 // If the local value didn't succeed, then we may be referring to a value
1050 // from a different function. Translate it, as this can happen when using
1051 // address of blocks.
1052 if (Slot == -1)
1053 if ((Machine = createSlotTracker(V))) {
1054 Slot = Machine->getLocalSlot(V);
1055 delete Machine;
1056 }
1057 }
1058 } else if ((Machine = createSlotTracker(V))) {
1059 // Otherwise, create one to get the # and then destroy it.
1060 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1061 Slot = Machine->getGlobalSlot(GV);
1062 Prefix = '@';
1063 } else {
1064 Slot = Machine->getLocalSlot(V);
1065 }
1066 delete Machine;
1067 Machine = 0;
1068 } else {
1069 Slot = -1;
1070 }
1071
1072 if (Slot != -1)
1073 Out << Prefix << Slot;
1074 else
1075 Out << "<badref>";
1076 }
1077
WriteAsOperand(raw_ostream & Out,const Value * V,bool PrintType,const Module * Context)1078 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1079 bool PrintType, const Module *Context) {
1080
1081 // Fast path: Don't construct and populate a TypePrinting object if we
1082 // won't be needing any types printed.
1083 if (!PrintType &&
1084 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1085 V->hasName() || isa<GlobalValue>(V))) {
1086 WriteAsOperandInternal(Out, V, 0, 0, Context);
1087 return;
1088 }
1089
1090 if (Context == 0) Context = getModuleFromVal(V);
1091
1092 TypePrinting TypePrinter;
1093 if (Context)
1094 TypePrinter.incorporateTypes(*Context);
1095 if (PrintType) {
1096 TypePrinter.print(V->getType(), Out);
1097 Out << ' ';
1098 }
1099
1100 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1101 }
1102
1103 namespace {
1104
1105 class AssemblyWriter {
1106 formatted_raw_ostream &Out;
1107 SlotTracker &Machine;
1108 const Module *TheModule;
1109 TypePrinting TypePrinter;
1110 AssemblyAnnotationWriter *AnnotationWriter;
1111
1112 public:
AssemblyWriter(formatted_raw_ostream & o,SlotTracker & Mac,const Module * M,AssemblyAnnotationWriter * AAW)1113 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1114 const Module *M,
1115 AssemblyAnnotationWriter *AAW)
1116 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1117 if (M)
1118 TypePrinter.incorporateTypes(*M);
1119 }
1120
1121 void printMDNodeBody(const MDNode *MD);
1122 void printNamedMDNode(const NamedMDNode *NMD);
1123
1124 void printModule(const Module *M);
1125
1126 void writeOperand(const Value *Op, bool PrintType);
1127 void writeParamOperand(const Value *Operand, Attributes Attrs);
1128 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1129
1130 void writeAllMDNodes();
1131
1132 void printTypeIdentities();
1133 void printGlobal(const GlobalVariable *GV);
1134 void printAlias(const GlobalAlias *GV);
1135 void printFunction(const Function *F);
1136 void printArgument(const Argument *FA, Attributes Attrs);
1137 void printBasicBlock(const BasicBlock *BB);
1138 void printInstruction(const Instruction &I);
1139
1140 private:
1141 // printInfoComment - Print a little comment after the instruction indicating
1142 // which slot it occupies.
1143 void printInfoComment(const Value &V);
1144 };
1145 } // end of anonymous namespace
1146
writeOperand(const Value * Operand,bool PrintType)1147 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1148 if (Operand == 0) {
1149 Out << "<null operand!>";
1150 return;
1151 }
1152 if (PrintType) {
1153 TypePrinter.print(Operand->getType(), Out);
1154 Out << ' ';
1155 }
1156 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1157 }
1158
writeAtomic(AtomicOrdering Ordering,SynchronizationScope SynchScope)1159 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1160 SynchronizationScope SynchScope) {
1161 if (Ordering == NotAtomic)
1162 return;
1163
1164 switch (SynchScope) {
1165 default: Out << " <bad scope " << int(SynchScope) << ">"; break;
1166 case SingleThread: Out << " singlethread"; break;
1167 case CrossThread: break;
1168 }
1169
1170 switch (Ordering) {
1171 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1172 case Unordered: Out << " unordered"; break;
1173 case Monotonic: Out << " monotonic"; break;
1174 case Acquire: Out << " acquire"; break;
1175 case Release: Out << " release"; break;
1176 case AcquireRelease: Out << " acq_rel"; break;
1177 case SequentiallyConsistent: Out << " seq_cst"; break;
1178 }
1179 }
1180
writeParamOperand(const Value * Operand,Attributes Attrs)1181 void AssemblyWriter::writeParamOperand(const Value *Operand,
1182 Attributes Attrs) {
1183 if (Operand == 0) {
1184 Out << "<null operand!>";
1185 return;
1186 }
1187
1188 // Print the type
1189 TypePrinter.print(Operand->getType(), Out);
1190 // Print parameter attributes list
1191 if (Attrs != Attribute::None)
1192 Out << ' ' << Attribute::getAsString(Attrs);
1193 Out << ' ';
1194 // Print the operand
1195 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1196 }
1197
printModule(const Module * M)1198 void AssemblyWriter::printModule(const Module *M) {
1199 if (!M->getModuleIdentifier().empty() &&
1200 // Don't print the ID if it will start a new line (which would
1201 // require a comment char before it).
1202 M->getModuleIdentifier().find('\n') == std::string::npos)
1203 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1204
1205 if (!M->getDataLayout().empty())
1206 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1207 if (!M->getTargetTriple().empty())
1208 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1209
1210 if (!M->getModuleInlineAsm().empty()) {
1211 // Split the string into lines, to make it easier to read the .ll file.
1212 std::string Asm = M->getModuleInlineAsm();
1213 size_t CurPos = 0;
1214 size_t NewLine = Asm.find_first_of('\n', CurPos);
1215 Out << '\n';
1216 while (NewLine != std::string::npos) {
1217 // We found a newline, print the portion of the asm string from the
1218 // last newline up to this newline.
1219 Out << "module asm \"";
1220 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1221 Out);
1222 Out << "\"\n";
1223 CurPos = NewLine+1;
1224 NewLine = Asm.find_first_of('\n', CurPos);
1225 }
1226 std::string rest(Asm.begin()+CurPos, Asm.end());
1227 if (!rest.empty()) {
1228 Out << "module asm \"";
1229 PrintEscapedString(rest, Out);
1230 Out << "\"\n";
1231 }
1232 }
1233
1234 // Loop over the dependent libraries and emit them.
1235 Module::lib_iterator LI = M->lib_begin();
1236 Module::lib_iterator LE = M->lib_end();
1237 if (LI != LE) {
1238 Out << '\n';
1239 Out << "deplibs = [ ";
1240 while (LI != LE) {
1241 Out << '"' << *LI << '"';
1242 ++LI;
1243 if (LI != LE)
1244 Out << ", ";
1245 }
1246 Out << " ]";
1247 }
1248
1249 printTypeIdentities();
1250
1251 // Output all globals.
1252 if (!M->global_empty()) Out << '\n';
1253 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1254 I != E; ++I)
1255 printGlobal(I);
1256
1257 // Output all aliases.
1258 if (!M->alias_empty()) Out << "\n";
1259 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1260 I != E; ++I)
1261 printAlias(I);
1262
1263 // Output all of the functions.
1264 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1265 printFunction(I);
1266
1267 // Output named metadata.
1268 if (!M->named_metadata_empty()) Out << '\n';
1269
1270 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1271 E = M->named_metadata_end(); I != E; ++I)
1272 printNamedMDNode(I);
1273
1274 // Output metadata.
1275 if (!Machine.mdn_empty()) {
1276 Out << '\n';
1277 writeAllMDNodes();
1278 }
1279 }
1280
printNamedMDNode(const NamedMDNode * NMD)1281 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1282 Out << '!';
1283 StringRef Name = NMD->getName();
1284 if (Name.empty()) {
1285 Out << "<empty name> ";
1286 } else {
1287 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1288 Name[0] == '.' || Name[0] == '_')
1289 Out << Name[0];
1290 else
1291 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1292 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1293 unsigned char C = Name[i];
1294 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1295 Out << C;
1296 else
1297 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1298 }
1299 }
1300 Out << " = !{";
1301 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1302 if (i) Out << ", ";
1303 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1304 if (Slot == -1)
1305 Out << "<badref>";
1306 else
1307 Out << '!' << Slot;
1308 }
1309 Out << "}\n";
1310 }
1311
1312
PrintLinkage(GlobalValue::LinkageTypes LT,formatted_raw_ostream & Out)1313 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1314 formatted_raw_ostream &Out) {
1315 switch (LT) {
1316 case GlobalValue::ExternalLinkage: break;
1317 case GlobalValue::PrivateLinkage: Out << "private "; break;
1318 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1319 case GlobalValue::LinkerPrivateWeakLinkage:
1320 Out << "linker_private_weak ";
1321 break;
1322 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1323 Out << "linker_private_weak_def_auto ";
1324 break;
1325 case GlobalValue::InternalLinkage: Out << "internal "; break;
1326 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1327 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1328 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1329 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1330 case GlobalValue::CommonLinkage: Out << "common "; break;
1331 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1332 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1333 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1334 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1335 case GlobalValue::AvailableExternallyLinkage:
1336 Out << "available_externally ";
1337 break;
1338 }
1339 }
1340
1341
PrintVisibility(GlobalValue::VisibilityTypes Vis,formatted_raw_ostream & Out)1342 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1343 formatted_raw_ostream &Out) {
1344 switch (Vis) {
1345 case GlobalValue::DefaultVisibility: break;
1346 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1347 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1348 }
1349 }
1350
printGlobal(const GlobalVariable * GV)1351 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1352 if (GV->isMaterializable())
1353 Out << "; Materializable\n";
1354
1355 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1356 Out << " = ";
1357
1358 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1359 Out << "external ";
1360
1361 PrintLinkage(GV->getLinkage(), Out);
1362 PrintVisibility(GV->getVisibility(), Out);
1363
1364 if (GV->isThreadLocal()) Out << "thread_local ";
1365 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1366 Out << "addrspace(" << AddressSpace << ") ";
1367 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1368 Out << (GV->isConstant() ? "constant " : "global ");
1369 TypePrinter.print(GV->getType()->getElementType(), Out);
1370
1371 if (GV->hasInitializer()) {
1372 Out << ' ';
1373 writeOperand(GV->getInitializer(), false);
1374 }
1375
1376 if (GV->hasSection()) {
1377 Out << ", section \"";
1378 PrintEscapedString(GV->getSection(), Out);
1379 Out << '"';
1380 }
1381 if (GV->getAlignment())
1382 Out << ", align " << GV->getAlignment();
1383
1384 printInfoComment(*GV);
1385 Out << '\n';
1386 }
1387
printAlias(const GlobalAlias * GA)1388 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1389 if (GA->isMaterializable())
1390 Out << "; Materializable\n";
1391
1392 // Don't crash when dumping partially built GA
1393 if (!GA->hasName())
1394 Out << "<<nameless>> = ";
1395 else {
1396 PrintLLVMName(Out, GA);
1397 Out << " = ";
1398 }
1399 PrintVisibility(GA->getVisibility(), Out);
1400
1401 Out << "alias ";
1402
1403 PrintLinkage(GA->getLinkage(), Out);
1404
1405 const Constant *Aliasee = GA->getAliasee();
1406
1407 if (Aliasee == 0) {
1408 TypePrinter.print(GA->getType(), Out);
1409 Out << " <<NULL ALIASEE>>";
1410 } else {
1411 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1412 }
1413
1414 printInfoComment(*GA);
1415 Out << '\n';
1416 }
1417
printTypeIdentities()1418 void AssemblyWriter::printTypeIdentities() {
1419 if (TypePrinter.NumberedTypes.empty() &&
1420 TypePrinter.NamedTypes.empty())
1421 return;
1422
1423 Out << '\n';
1424
1425 // We know all the numbers that each type is used and we know that it is a
1426 // dense assignment. Convert the map to an index table.
1427 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1428 for (DenseMap<StructType*, unsigned>::iterator I =
1429 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1430 I != E; ++I) {
1431 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1432 NumberedTypes[I->second] = I->first;
1433 }
1434
1435 // Emit all numbered types.
1436 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1437 Out << '%' << i << " = type ";
1438
1439 // Make sure we print out at least one level of the type structure, so
1440 // that we do not get %2 = type %2
1441 TypePrinter.printStructBody(NumberedTypes[i], Out);
1442 Out << '\n';
1443 }
1444
1445 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1446 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1447 Out << " = type ";
1448
1449 // Make sure we print out at least one level of the type structure, so
1450 // that we do not get %FILE = type %FILE
1451 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1452 Out << '\n';
1453 }
1454 }
1455
1456 /// printFunction - Print all aspects of a function.
1457 ///
printFunction(const Function * F)1458 void AssemblyWriter::printFunction(const Function *F) {
1459 // Print out the return type and name.
1460 Out << '\n';
1461
1462 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1463
1464 if (F->isMaterializable())
1465 Out << "; Materializable\n";
1466
1467 if (F->isDeclaration())
1468 Out << "declare ";
1469 else
1470 Out << "define ";
1471
1472 PrintLinkage(F->getLinkage(), Out);
1473 PrintVisibility(F->getVisibility(), Out);
1474
1475 // Print the calling convention.
1476 switch (F->getCallingConv()) {
1477 case CallingConv::C: break; // default
1478 case CallingConv::Fast: Out << "fastcc "; break;
1479 case CallingConv::Cold: Out << "coldcc "; break;
1480 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1481 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1482 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1483 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1484 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1485 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1486 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1487 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1488 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1489 default: Out << "cc" << F->getCallingConv() << " "; break;
1490 }
1491
1492 FunctionType *FT = F->getFunctionType();
1493 const AttrListPtr &Attrs = F->getAttributes();
1494 Attributes RetAttrs = Attrs.getRetAttributes();
1495 if (RetAttrs != Attribute::None)
1496 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1497 TypePrinter.print(F->getReturnType(), Out);
1498 Out << ' ';
1499 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1500 Out << '(';
1501 Machine.incorporateFunction(F);
1502
1503 // Loop over the arguments, printing them...
1504
1505 unsigned Idx = 1;
1506 if (!F->isDeclaration()) {
1507 // If this isn't a declaration, print the argument names as well.
1508 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1509 I != E; ++I) {
1510 // Insert commas as we go... the first arg doesn't get a comma
1511 if (I != F->arg_begin()) Out << ", ";
1512 printArgument(I, Attrs.getParamAttributes(Idx));
1513 Idx++;
1514 }
1515 } else {
1516 // Otherwise, print the types from the function type.
1517 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1518 // Insert commas as we go... the first arg doesn't get a comma
1519 if (i) Out << ", ";
1520
1521 // Output type...
1522 TypePrinter.print(FT->getParamType(i), Out);
1523
1524 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1525 if (ArgAttrs != Attribute::None)
1526 Out << ' ' << Attribute::getAsString(ArgAttrs);
1527 }
1528 }
1529
1530 // Finish printing arguments...
1531 if (FT->isVarArg()) {
1532 if (FT->getNumParams()) Out << ", ";
1533 Out << "..."; // Output varargs portion of signature!
1534 }
1535 Out << ')';
1536 if (F->hasUnnamedAddr())
1537 Out << " unnamed_addr";
1538 Attributes FnAttrs = Attrs.getFnAttributes();
1539 if (FnAttrs != Attribute::None)
1540 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1541 if (F->hasSection()) {
1542 Out << " section \"";
1543 PrintEscapedString(F->getSection(), Out);
1544 Out << '"';
1545 }
1546 if (F->getAlignment())
1547 Out << " align " << F->getAlignment();
1548 if (F->hasGC())
1549 Out << " gc \"" << F->getGC() << '"';
1550 if (F->isDeclaration()) {
1551 Out << '\n';
1552 } else {
1553 Out << " {";
1554 // Output all of the function's basic blocks.
1555 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1556 printBasicBlock(I);
1557
1558 Out << "}\n";
1559 }
1560
1561 Machine.purgeFunction();
1562 }
1563
1564 /// printArgument - This member is called for every argument that is passed into
1565 /// the function. Simply print it out
1566 ///
printArgument(const Argument * Arg,Attributes Attrs)1567 void AssemblyWriter::printArgument(const Argument *Arg,
1568 Attributes Attrs) {
1569 // Output type...
1570 TypePrinter.print(Arg->getType(), Out);
1571
1572 // Output parameter attributes list
1573 if (Attrs != Attribute::None)
1574 Out << ' ' << Attribute::getAsString(Attrs);
1575
1576 // Output name, if available...
1577 if (Arg->hasName()) {
1578 Out << ' ';
1579 PrintLLVMName(Out, Arg);
1580 }
1581 }
1582
1583 /// printBasicBlock - This member is called for each basic block in a method.
1584 ///
printBasicBlock(const BasicBlock * BB)1585 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1586 if (BB->hasName()) { // Print out the label if it exists...
1587 Out << "\n";
1588 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1589 Out << ':';
1590 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1591 Out << "\n; <label>:";
1592 int Slot = Machine.getLocalSlot(BB);
1593 if (Slot != -1)
1594 Out << Slot;
1595 else
1596 Out << "<badref>";
1597 }
1598
1599 if (BB->getParent() == 0) {
1600 Out.PadToColumn(50);
1601 Out << "; Error: Block without parent!";
1602 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1603 // Output predecessors for the block.
1604 Out.PadToColumn(50);
1605 Out << ";";
1606 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1607
1608 if (PI == PE) {
1609 Out << " No predecessors!";
1610 } else {
1611 Out << " preds = ";
1612 writeOperand(*PI, false);
1613 for (++PI; PI != PE; ++PI) {
1614 Out << ", ";
1615 writeOperand(*PI, false);
1616 }
1617 }
1618 }
1619
1620 Out << "\n";
1621
1622 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1623
1624 // Output all of the instructions in the basic block...
1625 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1626 printInstruction(*I);
1627 Out << '\n';
1628 }
1629
1630 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1631 }
1632
1633 /// printInfoComment - Print a little comment after the instruction indicating
1634 /// which slot it occupies.
1635 ///
printInfoComment(const Value & V)1636 void AssemblyWriter::printInfoComment(const Value &V) {
1637 if (AnnotationWriter) {
1638 AnnotationWriter->printInfoComment(V, Out);
1639 return;
1640 }
1641 }
1642
1643 // This member is called for each Instruction in a function..
printInstruction(const Instruction & I)1644 void AssemblyWriter::printInstruction(const Instruction &I) {
1645 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1646
1647 // Print out indentation for an instruction.
1648 Out << " ";
1649
1650 // Print out name if it exists...
1651 if (I.hasName()) {
1652 PrintLLVMName(Out, &I);
1653 Out << " = ";
1654 } else if (!I.getType()->isVoidTy()) {
1655 // Print out the def slot taken.
1656 int SlotNum = Machine.getLocalSlot(&I);
1657 if (SlotNum == -1)
1658 Out << "<badref> = ";
1659 else
1660 Out << '%' << SlotNum << " = ";
1661 }
1662
1663 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1664 Out << "tail ";
1665
1666 // Print out the opcode...
1667 Out << I.getOpcodeName();
1668
1669 // If this is an atomic load or store, print out the atomic marker.
1670 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1671 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1672 Out << " atomic";
1673
1674 // If this is a volatile operation, print out the volatile marker.
1675 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1676 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1677 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1678 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1679 Out << " volatile";
1680
1681 // Print out optimization information.
1682 WriteOptimizationInfo(Out, &I);
1683
1684 // Print out the compare instruction predicates
1685 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1686 Out << ' ' << getPredicateText(CI->getPredicate());
1687
1688 // Print out the atomicrmw operation
1689 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1690 writeAtomicRMWOperation(Out, RMWI->getOperation());
1691
1692 // Print out the type of the operands...
1693 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1694
1695 // Special case conditional branches to swizzle the condition out to the front
1696 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1697 BranchInst &BI(cast<BranchInst>(I));
1698 Out << ' ';
1699 writeOperand(BI.getCondition(), true);
1700 Out << ", ";
1701 writeOperand(BI.getSuccessor(0), true);
1702 Out << ", ";
1703 writeOperand(BI.getSuccessor(1), true);
1704
1705 } else if (isa<SwitchInst>(I)) {
1706 SwitchInst& SI(cast<SwitchInst>(I));
1707 // Special case switch instruction to get formatting nice and correct.
1708 Out << ' ';
1709 writeOperand(SI.getCondition(), true);
1710 Out << ", ";
1711 writeOperand(SI.getDefaultDest(), true);
1712 Out << " [";
1713 // Skip the first item since that's the default case.
1714 unsigned NumCases = SI.getNumCases();
1715 for (unsigned i = 1; i < NumCases; ++i) {
1716 Out << "\n ";
1717 writeOperand(SI.getCaseValue(i), true);
1718 Out << ", ";
1719 writeOperand(SI.getSuccessor(i), true);
1720 }
1721 Out << "\n ]";
1722 } else if (isa<IndirectBrInst>(I)) {
1723 // Special case indirectbr instruction to get formatting nice and correct.
1724 Out << ' ';
1725 writeOperand(Operand, true);
1726 Out << ", [";
1727
1728 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1729 if (i != 1)
1730 Out << ", ";
1731 writeOperand(I.getOperand(i), true);
1732 }
1733 Out << ']';
1734 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1735 Out << ' ';
1736 TypePrinter.print(I.getType(), Out);
1737 Out << ' ';
1738
1739 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1740 if (op) Out << ", ";
1741 Out << "[ ";
1742 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1743 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1744 }
1745 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1746 Out << ' ';
1747 writeOperand(I.getOperand(0), true);
1748 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1749 Out << ", " << *i;
1750 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1751 Out << ' ';
1752 writeOperand(I.getOperand(0), true); Out << ", ";
1753 writeOperand(I.getOperand(1), true);
1754 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1755 Out << ", " << *i;
1756 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1757 Out << ' ';
1758 TypePrinter.print(I.getType(), Out);
1759 Out << " personality ";
1760 writeOperand(I.getOperand(0), true); Out << '\n';
1761
1762 if (LPI->isCleanup())
1763 Out << " cleanup";
1764
1765 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1766 if (i != 0 || LPI->isCleanup()) Out << "\n";
1767 if (LPI->isCatch(i))
1768 Out << " catch ";
1769 else
1770 Out << " filter ";
1771
1772 writeOperand(LPI->getClause(i), true);
1773 }
1774 } else if (isa<ReturnInst>(I) && !Operand) {
1775 Out << " void";
1776 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1777 // Print the calling convention being used.
1778 switch (CI->getCallingConv()) {
1779 case CallingConv::C: break; // default
1780 case CallingConv::Fast: Out << " fastcc"; break;
1781 case CallingConv::Cold: Out << " coldcc"; break;
1782 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1783 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1784 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1785 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1786 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1787 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1788 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1789 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1790 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1791 default: Out << " cc" << CI->getCallingConv(); break;
1792 }
1793
1794 Operand = CI->getCalledValue();
1795 PointerType *PTy = cast<PointerType>(Operand->getType());
1796 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1797 Type *RetTy = FTy->getReturnType();
1798 const AttrListPtr &PAL = CI->getAttributes();
1799
1800 if (PAL.getRetAttributes() != Attribute::None)
1801 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1802
1803 // If possible, print out the short form of the call instruction. We can
1804 // only do this if the first argument is a pointer to a nonvararg function,
1805 // and if the return type is not a pointer to a function.
1806 //
1807 Out << ' ';
1808 if (!FTy->isVarArg() &&
1809 (!RetTy->isPointerTy() ||
1810 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1811 TypePrinter.print(RetTy, Out);
1812 Out << ' ';
1813 writeOperand(Operand, false);
1814 } else {
1815 writeOperand(Operand, true);
1816 }
1817 Out << '(';
1818 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1819 if (op > 0)
1820 Out << ", ";
1821 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1822 }
1823 Out << ')';
1824 if (PAL.getFnAttributes() != Attribute::None)
1825 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1826 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1827 Operand = II->getCalledValue();
1828 PointerType *PTy = cast<PointerType>(Operand->getType());
1829 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1830 Type *RetTy = FTy->getReturnType();
1831 const AttrListPtr &PAL = II->getAttributes();
1832
1833 // Print the calling convention being used.
1834 switch (II->getCallingConv()) {
1835 case CallingConv::C: break; // default
1836 case CallingConv::Fast: Out << " fastcc"; break;
1837 case CallingConv::Cold: Out << " coldcc"; break;
1838 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1839 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1840 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1841 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1842 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1843 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1844 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1845 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1846 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1847 default: Out << " cc" << II->getCallingConv(); break;
1848 }
1849
1850 if (PAL.getRetAttributes() != Attribute::None)
1851 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1852
1853 // If possible, print out the short form of the invoke instruction. We can
1854 // only do this if the first argument is a pointer to a nonvararg function,
1855 // and if the return type is not a pointer to a function.
1856 //
1857 Out << ' ';
1858 if (!FTy->isVarArg() &&
1859 (!RetTy->isPointerTy() ||
1860 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1861 TypePrinter.print(RetTy, Out);
1862 Out << ' ';
1863 writeOperand(Operand, false);
1864 } else {
1865 writeOperand(Operand, true);
1866 }
1867 Out << '(';
1868 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1869 if (op)
1870 Out << ", ";
1871 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1872 }
1873
1874 Out << ')';
1875 if (PAL.getFnAttributes() != Attribute::None)
1876 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1877
1878 Out << "\n to ";
1879 writeOperand(II->getNormalDest(), true);
1880 Out << " unwind ";
1881 writeOperand(II->getUnwindDest(), true);
1882
1883 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1884 Out << ' ';
1885 TypePrinter.print(AI->getType()->getElementType(), Out);
1886 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1887 Out << ", ";
1888 writeOperand(AI->getArraySize(), true);
1889 }
1890 if (AI->getAlignment()) {
1891 Out << ", align " << AI->getAlignment();
1892 }
1893 } else if (isa<CastInst>(I)) {
1894 if (Operand) {
1895 Out << ' ';
1896 writeOperand(Operand, true); // Work with broken code
1897 }
1898 Out << " to ";
1899 TypePrinter.print(I.getType(), Out);
1900 } else if (isa<VAArgInst>(I)) {
1901 if (Operand) {
1902 Out << ' ';
1903 writeOperand(Operand, true); // Work with broken code
1904 }
1905 Out << ", ";
1906 TypePrinter.print(I.getType(), Out);
1907 } else if (Operand) { // Print the normal way.
1908
1909 // PrintAllTypes - Instructions who have operands of all the same type
1910 // omit the type from all but the first operand. If the instruction has
1911 // different type operands (for example br), then they are all printed.
1912 bool PrintAllTypes = false;
1913 Type *TheType = Operand->getType();
1914
1915 // Select, Store and ShuffleVector always print all types.
1916 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1917 || isa<ReturnInst>(I)) {
1918 PrintAllTypes = true;
1919 } else {
1920 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1921 Operand = I.getOperand(i);
1922 // note that Operand shouldn't be null, but the test helps make dump()
1923 // more tolerant of malformed IR
1924 if (Operand && Operand->getType() != TheType) {
1925 PrintAllTypes = true; // We have differing types! Print them all!
1926 break;
1927 }
1928 }
1929 }
1930
1931 if (!PrintAllTypes) {
1932 Out << ' ';
1933 TypePrinter.print(TheType, Out);
1934 }
1935
1936 Out << ' ';
1937 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1938 if (i) Out << ", ";
1939 writeOperand(I.getOperand(i), PrintAllTypes);
1940 }
1941 }
1942
1943 // Print atomic ordering/alignment for memory operations
1944 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1945 if (LI->isAtomic())
1946 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1947 if (LI->getAlignment())
1948 Out << ", align " << LI->getAlignment();
1949 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1950 if (SI->isAtomic())
1951 writeAtomic(SI->getOrdering(), SI->getSynchScope());
1952 if (SI->getAlignment())
1953 Out << ", align " << SI->getAlignment();
1954 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
1955 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
1956 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
1957 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
1958 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
1959 writeAtomic(FI->getOrdering(), FI->getSynchScope());
1960 }
1961
1962 // Print Metadata info.
1963 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
1964 I.getAllMetadata(InstMD);
1965 if (!InstMD.empty()) {
1966 SmallVector<StringRef, 8> MDNames;
1967 I.getType()->getContext().getMDKindNames(MDNames);
1968 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
1969 unsigned Kind = InstMD[i].first;
1970 if (Kind < MDNames.size()) {
1971 Out << ", !" << MDNames[Kind];
1972 } else {
1973 Out << ", !<unknown kind #" << Kind << ">";
1974 }
1975 Out << ' ';
1976 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
1977 TheModule);
1978 }
1979 }
1980 printInfoComment(I);
1981 }
1982
WriteMDNodeComment(const MDNode * Node,formatted_raw_ostream & Out)1983 static void WriteMDNodeComment(const MDNode *Node,
1984 formatted_raw_ostream &Out) {
1985 if (Node->getNumOperands() < 1)
1986 return;
1987 ConstantInt *CI = dyn_cast_or_null<ConstantInt>(Node->getOperand(0));
1988 if (!CI) return;
1989 APInt Val = CI->getValue();
1990 APInt Tag = Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
1991 if (Val.ult(LLVMDebugVersion))
1992 return;
1993
1994 Out.PadToColumn(50);
1995 if (Tag == dwarf::DW_TAG_user_base)
1996 Out << "; [ DW_TAG_user_base ]";
1997 else if (Tag.isIntN(32)) {
1998 if (const char *TagName = dwarf::TagString(Tag.getZExtValue()))
1999 Out << "; [ " << TagName << " ]";
2000 }
2001 }
2002
writeAllMDNodes()2003 void AssemblyWriter::writeAllMDNodes() {
2004 SmallVector<const MDNode *, 16> Nodes;
2005 Nodes.resize(Machine.mdn_size());
2006 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2007 I != E; ++I)
2008 Nodes[I->second] = cast<MDNode>(I->first);
2009
2010 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2011 Out << '!' << i << " = metadata ";
2012 printMDNodeBody(Nodes[i]);
2013 }
2014 }
2015
printMDNodeBody(const MDNode * Node)2016 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2017 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2018 WriteMDNodeComment(Node, Out);
2019 Out << "\n";
2020 }
2021
2022 //===----------------------------------------------------------------------===//
2023 // External Interface declarations
2024 //===----------------------------------------------------------------------===//
2025
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW) const2026 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2027 SlotTracker SlotTable(this);
2028 formatted_raw_ostream OS(ROS);
2029 AssemblyWriter W(OS, SlotTable, this, AAW);
2030 W.printModule(this);
2031 }
2032
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW) const2033 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2034 SlotTracker SlotTable(getParent());
2035 formatted_raw_ostream OS(ROS);
2036 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2037 W.printNamedMDNode(this);
2038 }
2039
print(raw_ostream & OS) const2040 void Type::print(raw_ostream &OS) const {
2041 TypePrinting TP;
2042 TP.print(const_cast<Type*>(this), OS);
2043
2044 // If the type is a named struct type, print the body as well.
2045 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2046 if (!STy->isLiteral()) {
2047 OS << " = type ";
2048 TP.printStructBody(STy, OS);
2049 }
2050 }
2051
print(raw_ostream & ROS,AssemblyAnnotationWriter * AAW) const2052 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2053 formatted_raw_ostream OS(ROS);
2054 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2055 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2056 SlotTracker SlotTable(F);
2057 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2058 W.printInstruction(*I);
2059 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2060 SlotTracker SlotTable(BB->getParent());
2061 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2062 W.printBasicBlock(BB);
2063 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2064 SlotTracker SlotTable(GV->getParent());
2065 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2066 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2067 W.printGlobal(V);
2068 else if (const Function *F = dyn_cast<Function>(GV))
2069 W.printFunction(F);
2070 else
2071 W.printAlias(cast<GlobalAlias>(GV));
2072 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2073 const Function *F = N->getFunction();
2074 SlotTracker SlotTable(F);
2075 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2076 W.printMDNodeBody(N);
2077 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2078 TypePrinting TypePrinter;
2079 TypePrinter.print(C->getType(), OS);
2080 OS << ' ';
2081 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2082 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2083 isa<Argument>(this)) {
2084 WriteAsOperand(OS, this, true, 0);
2085 } else {
2086 // Otherwise we don't know what it is. Call the virtual function to
2087 // allow a subclass to print itself.
2088 printCustom(OS);
2089 }
2090 }
2091
2092 // Value::printCustom - subclasses should override this to implement printing.
printCustom(raw_ostream & OS) const2093 void Value::printCustom(raw_ostream &OS) const {
2094 llvm_unreachable("Unknown value to print out!");
2095 }
2096
2097 // Value::dump - allow easy printing of Values from the debugger.
dump() const2098 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2099
2100 // Type::dump - allow easy printing of Types from the debugger.
dump() const2101 void Type::dump() const { print(dbgs()); }
2102
2103 // Module::dump() - Allow printing of Modules from the debugger.
dump() const2104 void Module::dump() const { print(dbgs(), 0); }
2105