1 //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Assembly/Writer.h
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.
15 //===----------------------------------------------------------------------===//
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/DebugInfo.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Module.h"
29 #include "llvm/ValueSymbolTable.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/FormattedStream.h"
44 // Make virtual table appear in this compilation unit.
45 AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const Module *getModuleFromVal(const Value *V) {
52 if (const Argument *MA = dyn_cast<Argument>(V))
53 return MA->getParent() ? MA->getParent()->getParent() : 0;
55 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
56 return BB->getParent() ? BB->getParent()->getParent() : 0;
58 if (const Instruction *I = dyn_cast<Instruction>(V)) {
59 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
60 return M ? M->getParent() : 0;
63 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return GV->getParent();
68 // PrintEscapedString - Print each character of the specified string, escaping
69 // it if it is not printable or if it is an escape char.
70 static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
71 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
72 unsigned char C = Name[i];
73 if (isprint(C) && C != '\\' && C != '"')
76 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
87 /// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
88 /// prefixed with % (if the string only contains simple characters) or is
89 /// surrounded with ""'s (if it has special chars in it). Print it out.
90 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
91 assert(!Name.empty() && "Cannot get empty name!");
94 case GlobalPrefix: OS << '@'; break;
95 case LabelPrefix: break;
96 case LocalPrefix: OS << '%'; break;
99 // Scan the name to see if it needs quotes first.
100 bool NeedsQuotes = isdigit(Name[0]);
102 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
104 if (!isalnum(C) && C != '-' && C != '.' && C != '_') {
111 // If we didn't need any quotes, just write out the name in one blast.
117 // Okay, we need quotes. Output the quotes and escape any scary characters as
120 PrintEscapedString(Name, OS);
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.
127 static void PrintLLVMName(raw_ostream &OS, const Value *V) {
128 PrintLLVMName(OS, V->getName(),
129 isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
132 //===----------------------------------------------------------------------===//
133 // TypePrinting Class: Type printing machinery
134 //===----------------------------------------------------------------------===//
136 /// TypePrinting - Type printing machinery.
139 TypePrinting(const TypePrinting &); // DO NOT IMPLEMENT
140 void operator=(const TypePrinting&); // DO NOT IMPLEMENT
143 /// NamedTypes - The named types that are used by the current module.
144 std::vector<StructType*> NamedTypes;
146 /// NumberedTypes - The numbered types, along with their value.
147 DenseMap<StructType*, unsigned> NumberedTypes;
153 void incorporateTypes(const Module &M);
155 void print(Type *Ty, raw_ostream &OS);
157 void printStructBody(StructType *Ty, raw_ostream &OS);
159 } // end anonymous namespace.
162 void TypePrinting::incorporateTypes(const Module &M) {
163 M.findUsedStructTypes(NamedTypes);
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;
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;
173 // Ignore anonymous types.
174 if (STy->isLiteral())
177 if (STy->getName().empty())
178 NumberedTypes[STy] = NextNumber++;
183 NamedTypes.erase(NextToUse, NamedTypes.end());
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.
189 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
190 switch (Ty->getTypeID()) {
191 case Type::VoidTyID: OS << "void"; break;
192 case Type::HalfTyID: OS << "half"; break;
193 case Type::FloatTyID: OS << "float"; break;
194 case Type::DoubleTyID: OS << "double"; break;
195 case Type::X86_FP80TyID: OS << "x86_fp80"; break;
196 case Type::FP128TyID: OS << "fp128"; break;
197 case Type::PPC_FP128TyID: OS << "ppc_fp128"; break;
198 case Type::LabelTyID: OS << "label"; break;
199 case Type::MetadataTyID: OS << "metadata"; break;
200 case Type::X86_MMXTyID: OS << "x86_mmx"; break;
201 case Type::IntegerTyID:
202 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
205 case Type::FunctionTyID: {
206 FunctionType *FTy = cast<FunctionType>(Ty);
207 print(FTy->getReturnType(), OS);
209 for (FunctionType::param_iterator I = FTy->param_begin(),
210 E = FTy->param_end(); I != E; ++I) {
211 if (I != FTy->param_begin())
215 if (FTy->isVarArg()) {
216 if (FTy->getNumParams()) OS << ", ";
222 case Type::StructTyID: {
223 StructType *STy = cast<StructType>(Ty);
225 if (STy->isLiteral())
226 return printStructBody(STy, OS);
228 if (!STy->getName().empty())
229 return PrintLLVMName(OS, STy->getName(), LocalPrefix);
231 DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
232 if (I != NumberedTypes.end())
233 OS << '%' << I->second;
234 else // Not enumerated, print the hex address.
235 OS << "%\"type " << STy << '\"';
238 case Type::PointerTyID: {
239 PointerType *PTy = cast<PointerType>(Ty);
240 print(PTy->getElementType(), OS);
241 if (unsigned AddressSpace = PTy->getAddressSpace())
242 OS << " addrspace(" << AddressSpace << ')';
246 case Type::ArrayTyID: {
247 ArrayType *ATy = cast<ArrayType>(Ty);
248 OS << '[' << ATy->getNumElements() << " x ";
249 print(ATy->getElementType(), OS);
253 case Type::VectorTyID: {
254 VectorType *PTy = cast<VectorType>(Ty);
255 OS << "<" << PTy->getNumElements() << " x ";
256 print(PTy->getElementType(), OS);
261 OS << "<unrecognized-type>";
266 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
267 if (STy->isOpaque()) {
275 if (STy->getNumElements() == 0) {
278 StructType::element_iterator I = STy->element_begin();
281 for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
294 //===----------------------------------------------------------------------===//
295 // SlotTracker Class: Enumerate slot numbers for unnamed values
296 //===----------------------------------------------------------------------===//
300 /// This class provides computation of slot numbers for LLVM Assembly writing.
304 /// ValueMap - A mapping of Values to slot numbers.
305 typedef DenseMap<const Value*, unsigned> ValueMap;
308 /// TheModule - The module for which we are holding slot numbers.
309 const Module* TheModule;
311 /// TheFunction - The function for which we are holding slot numbers.
312 const Function* TheFunction;
313 bool FunctionProcessed;
315 /// mMap - The slot map for the module level data.
319 /// fMap - The slot map for the function level data.
323 /// mdnMap - Map for MDNodes.
324 DenseMap<const MDNode*, unsigned> mdnMap;
327 /// Construct from a module
328 explicit SlotTracker(const Module *M);
329 /// Construct from a function, starting out in incorp state.
330 explicit SlotTracker(const Function *F);
332 /// Return the slot number of the specified value in it's type
333 /// plane. If something is not in the SlotTracker, return -1.
334 int getLocalSlot(const Value *V);
335 int getGlobalSlot(const GlobalValue *V);
336 int getMetadataSlot(const MDNode *N);
338 /// If you'd like to deal with a function instead of just a module, use
339 /// this method to get its data into the SlotTracker.
340 void incorporateFunction(const Function *F) {
342 FunctionProcessed = false;
345 /// After calling incorporateFunction, use this method to remove the
346 /// most recently incorporated function from the SlotTracker. This
347 /// will reset the state of the machine back to just the module contents.
348 void purgeFunction();
350 /// MDNode map iterators.
351 typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
352 mdn_iterator mdn_begin() { return mdnMap.begin(); }
353 mdn_iterator mdn_end() { return mdnMap.end(); }
354 unsigned mdn_size() const { return mdnMap.size(); }
355 bool mdn_empty() const { return mdnMap.empty(); }
357 /// This function does the actual initialization.
358 inline void initialize();
360 // Implementation Details
362 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
363 void CreateModuleSlot(const GlobalValue *V);
365 /// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
366 void CreateMetadataSlot(const MDNode *N);
368 /// CreateFunctionSlot - Insert the specified Value* into the slot table.
369 void CreateFunctionSlot(const Value *V);
371 /// Add all of the module level global variables (and their initializers)
372 /// and function declarations, but not the contents of those functions.
373 void processModule();
375 /// Add all of the functions arguments, basic blocks, and instructions.
376 void processFunction();
378 SlotTracker(const SlotTracker &); // DO NOT IMPLEMENT
379 void operator=(const SlotTracker &); // DO NOT IMPLEMENT
382 } // end anonymous namespace
385 static SlotTracker *createSlotTracker(const Value *V) {
386 if (const Argument *FA = dyn_cast<Argument>(V))
387 return new SlotTracker(FA->getParent());
389 if (const Instruction *I = dyn_cast<Instruction>(V))
391 return new SlotTracker(I->getParent()->getParent());
393 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
394 return new SlotTracker(BB->getParent());
396 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
397 return new SlotTracker(GV->getParent());
399 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
400 return new SlotTracker(GA->getParent());
402 if (const Function *Func = dyn_cast<Function>(V))
403 return new SlotTracker(Func);
405 if (const MDNode *MD = dyn_cast<MDNode>(V)) {
406 if (!MD->isFunctionLocal())
407 return new SlotTracker(MD->getFunction());
409 return new SlotTracker((Function *)0);
416 #define ST_DEBUG(X) dbgs() << X
421 // Module level constructor. Causes the contents of the Module (sans functions)
422 // to be added to the slot table.
423 SlotTracker::SlotTracker(const Module *M)
424 : TheModule(M), TheFunction(0), FunctionProcessed(false),
425 mNext(0), fNext(0), mdnNext(0) {
428 // Function level constructor. Causes the contents of the Module and the one
429 // function provided to be added to the slot table.
430 SlotTracker::SlotTracker(const Function *F)
431 : TheModule(F ? F->getParent() : 0), TheFunction(F), FunctionProcessed(false),
432 mNext(0), fNext(0), mdnNext(0) {
435 inline void SlotTracker::initialize() {
438 TheModule = 0; ///< Prevent re-processing next time we're called.
441 if (TheFunction && !FunctionProcessed)
445 // Iterate through all the global variables, functions, and global
446 // variable initializers and create slots for them.
447 void SlotTracker::processModule() {
448 ST_DEBUG("begin processModule!\n");
450 // Add all of the unnamed global variables to the value table.
451 for (Module::const_global_iterator I = TheModule->global_begin(),
452 E = TheModule->global_end(); I != E; ++I) {
457 // Add metadata used by named metadata.
458 for (Module::const_named_metadata_iterator
459 I = TheModule->named_metadata_begin(),
460 E = TheModule->named_metadata_end(); I != E; ++I) {
461 const NamedMDNode *NMD = I;
462 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
463 CreateMetadataSlot(NMD->getOperand(i));
466 // Add all the unnamed functions to the table.
467 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
472 ST_DEBUG("end processModule!\n");
475 // Process the arguments, basic blocks, and instructions of a function.
476 void SlotTracker::processFunction() {
477 ST_DEBUG("begin processFunction!\n");
480 // Add all the function arguments with no names.
481 for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
482 AE = TheFunction->arg_end(); AI != AE; ++AI)
484 CreateFunctionSlot(AI);
486 ST_DEBUG("Inserting Instructions:\n");
488 SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
490 // Add all of the basic blocks and instructions with no names.
491 for (Function::const_iterator BB = TheFunction->begin(),
492 E = TheFunction->end(); BB != E; ++BB) {
494 CreateFunctionSlot(BB);
496 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E;
498 if (!I->getType()->isVoidTy() && !I->hasName())
499 CreateFunctionSlot(I);
501 // Intrinsics can directly use metadata. We allow direct calls to any
502 // llvm.foo function here, because the target may not be linked into the
504 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
505 if (Function *F = CI->getCalledFunction())
506 if (F->getName().startswith("llvm."))
507 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
508 if (MDNode *N = dyn_cast_or_null<MDNode>(I->getOperand(i)))
509 CreateMetadataSlot(N);
512 // Process metadata attached with this instruction.
513 I->getAllMetadata(MDForInst);
514 for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
515 CreateMetadataSlot(MDForInst[i].second);
520 FunctionProcessed = true;
522 ST_DEBUG("end processFunction!\n");
525 /// Clean up after incorporating a function. This is the only way to get out of
526 /// the function incorporation state that affects get*Slot/Create*Slot. Function
527 /// incorporation state is indicated by TheFunction != 0.
528 void SlotTracker::purgeFunction() {
529 ST_DEBUG("begin purgeFunction!\n");
530 fMap.clear(); // Simply discard the function level map
532 FunctionProcessed = false;
533 ST_DEBUG("end purgeFunction!\n");
536 /// getGlobalSlot - Get the slot number of a global value.
537 int SlotTracker::getGlobalSlot(const GlobalValue *V) {
538 // Check for uninitialized state and do lazy initialization.
541 // Find the value in the module map
542 ValueMap::iterator MI = mMap.find(V);
543 return MI == mMap.end() ? -1 : (int)MI->second;
546 /// getMetadataSlot - Get the slot number of a MDNode.
547 int SlotTracker::getMetadataSlot(const MDNode *N) {
548 // Check for uninitialized state and do lazy initialization.
551 // Find the MDNode in the module map
552 mdn_iterator MI = mdnMap.find(N);
553 return MI == mdnMap.end() ? -1 : (int)MI->second;
557 /// getLocalSlot - Get the slot number for a value that is local to a function.
558 int SlotTracker::getLocalSlot(const Value *V) {
559 assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
561 // Check for uninitialized state and do lazy initialization.
564 ValueMap::iterator FI = fMap.find(V);
565 return FI == fMap.end() ? -1 : (int)FI->second;
569 /// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
570 void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
571 assert(V && "Can't insert a null Value into SlotTracker!");
572 assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
573 assert(!V->hasName() && "Doesn't need a slot!");
575 unsigned DestSlot = mNext++;
578 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
580 // G = Global, F = Function, A = Alias, o = other
581 ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
582 (isa<Function>(V) ? 'F' :
583 (isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
586 /// CreateSlot - Create a new slot for the specified value if it has no name.
587 void SlotTracker::CreateFunctionSlot(const Value *V) {
588 assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
590 unsigned DestSlot = fNext++;
593 // G = Global, F = Function, o = other
594 ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
595 DestSlot << " [o]\n");
598 /// CreateModuleSlot - Insert the specified MDNode* into the slot table.
599 void SlotTracker::CreateMetadataSlot(const MDNode *N) {
600 assert(N && "Can't insert a null Value into SlotTracker!");
602 // Don't insert if N is a function-local metadata, these are always printed
604 if (!N->isFunctionLocal()) {
605 mdn_iterator I = mdnMap.find(N);
606 if (I != mdnMap.end())
609 unsigned DestSlot = mdnNext++;
610 mdnMap[N] = DestSlot;
613 // Recursively add any MDNodes referenced by operands.
614 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
615 if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
616 CreateMetadataSlot(Op);
619 //===----------------------------------------------------------------------===//
620 // AsmWriter Implementation
621 //===----------------------------------------------------------------------===//
623 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
624 TypePrinting *TypePrinter,
625 SlotTracker *Machine,
626 const Module *Context);
630 static const char *getPredicateText(unsigned predicate) {
631 const char * pred = "unknown";
633 case FCmpInst::FCMP_FALSE: pred = "false"; break;
634 case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
635 case FCmpInst::FCMP_OGT: pred = "ogt"; break;
636 case FCmpInst::FCMP_OGE: pred = "oge"; break;
637 case FCmpInst::FCMP_OLT: pred = "olt"; break;
638 case FCmpInst::FCMP_OLE: pred = "ole"; break;
639 case FCmpInst::FCMP_ONE: pred = "one"; break;
640 case FCmpInst::FCMP_ORD: pred = "ord"; break;
641 case FCmpInst::FCMP_UNO: pred = "uno"; break;
642 case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
643 case FCmpInst::FCMP_UGT: pred = "ugt"; break;
644 case FCmpInst::FCMP_UGE: pred = "uge"; break;
645 case FCmpInst::FCMP_ULT: pred = "ult"; break;
646 case FCmpInst::FCMP_ULE: pred = "ule"; break;
647 case FCmpInst::FCMP_UNE: pred = "une"; break;
648 case FCmpInst::FCMP_TRUE: pred = "true"; break;
649 case ICmpInst::ICMP_EQ: pred = "eq"; break;
650 case ICmpInst::ICMP_NE: pred = "ne"; break;
651 case ICmpInst::ICMP_SGT: pred = "sgt"; break;
652 case ICmpInst::ICMP_SGE: pred = "sge"; break;
653 case ICmpInst::ICMP_SLT: pred = "slt"; break;
654 case ICmpInst::ICMP_SLE: pred = "sle"; break;
655 case ICmpInst::ICMP_UGT: pred = "ugt"; break;
656 case ICmpInst::ICMP_UGE: pred = "uge"; break;
657 case ICmpInst::ICMP_ULT: pred = "ult"; break;
658 case ICmpInst::ICMP_ULE: pred = "ule"; break;
663 static void writeAtomicRMWOperation(raw_ostream &Out,
664 AtomicRMWInst::BinOp Op) {
666 default: Out << " <unknown operation " << Op << ">"; break;
667 case AtomicRMWInst::Xchg: Out << " xchg"; break;
668 case AtomicRMWInst::Add: Out << " add"; break;
669 case AtomicRMWInst::Sub: Out << " sub"; break;
670 case AtomicRMWInst::And: Out << " and"; break;
671 case AtomicRMWInst::Nand: Out << " nand"; break;
672 case AtomicRMWInst::Or: Out << " or"; break;
673 case AtomicRMWInst::Xor: Out << " xor"; break;
674 case AtomicRMWInst::Max: Out << " max"; break;
675 case AtomicRMWInst::Min: Out << " min"; break;
676 case AtomicRMWInst::UMax: Out << " umax"; break;
677 case AtomicRMWInst::UMin: Out << " umin"; break;
681 static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
682 if (const OverflowingBinaryOperator *OBO =
683 dyn_cast<OverflowingBinaryOperator>(U)) {
684 if (OBO->hasNoUnsignedWrap())
686 if (OBO->hasNoSignedWrap())
688 } else if (const PossiblyExactOperator *Div =
689 dyn_cast<PossiblyExactOperator>(U)) {
692 } else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
693 if (GEP->isInBounds())
698 static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
699 TypePrinting &TypePrinter,
700 SlotTracker *Machine,
701 const Module *Context) {
702 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
703 if (CI->getType()->isIntegerTy(1)) {
704 Out << (CI->getZExtValue() ? "true" : "false");
707 Out << CI->getValue();
711 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
712 if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
713 &CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
714 // We would like to output the FP constant value in exponential notation,
715 // but we cannot do this if doing so will lose precision. Check here to
716 // make sure that we only output it in exponential format if we can parse
717 // the value back and get the same value.
720 bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
721 bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
722 bool isInf = CFP->getValueAPF().isInfinity();
723 bool isNaN = CFP->getValueAPF().isNaN();
724 if (!isHalf && !isInf && !isNaN) {
725 double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
726 CFP->getValueAPF().convertToFloat();
727 SmallString<128> StrVal;
728 raw_svector_ostream(StrVal) << Val;
730 // Check to make sure that the stringized number is not some string like
731 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
732 // that the string matches the "[-+]?[0-9]" regex.
734 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
735 ((StrVal[0] == '-' || StrVal[0] == '+') &&
736 (StrVal[1] >= '0' && StrVal[1] <= '9'))) {
737 // Reparse stringized version!
738 if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
744 // Otherwise we could not reparse it to exactly the same value, so we must
745 // output the string in hexadecimal format! Note that loading and storing
746 // floating point types changes the bits of NaNs on some hosts, notably
747 // x86, so we must not use these types.
748 assert(sizeof(double) == sizeof(uint64_t) &&
749 "assuming that double is 64 bits!");
751 APFloat apf = CFP->getValueAPF();
752 // Halves and floats are represented in ASCII IR as double, convert.
754 apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
757 utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
762 // Either half, or some form of long double.
763 // These appear as a magic letter identifying the type, then a
764 // fixed number of hex digits.
766 // Bit position, in the current word, of the next nibble to print.
769 if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
771 // api needed to prevent premature destruction
772 APInt api = CFP->getValueAPF().bitcastToAPInt();
773 const uint64_t* p = api.getRawData();
774 uint64_t word = p[1];
776 int width = api.getBitWidth();
777 for (int j=0; j<width; j+=4, shiftcount-=4) {
778 unsigned int nibble = (word>>shiftcount) & 15;
780 Out << (unsigned char)(nibble + '0');
782 Out << (unsigned char)(nibble - 10 + 'A');
783 if (shiftcount == 0 && j+4 < width) {
787 shiftcount = width-j-4;
791 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
794 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
797 } else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
801 llvm_unreachable("Unsupported floating point type");
802 // api needed to prevent premature destruction
803 APInt api = CFP->getValueAPF().bitcastToAPInt();
804 const uint64_t* p = api.getRawData();
806 int width = api.getBitWidth();
807 for (int j=0; j<width; j+=4, shiftcount-=4) {
808 unsigned int nibble = (word>>shiftcount) & 15;
810 Out << (unsigned char)(nibble + '0');
812 Out << (unsigned char)(nibble - 10 + 'A');
813 if (shiftcount == 0 && j+4 < width) {
817 shiftcount = width-j-4;
823 if (isa<ConstantAggregateZero>(CV)) {
824 Out << "zeroinitializer";
828 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
829 Out << "blockaddress(";
830 WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
833 WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
839 if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
840 Type *ETy = CA->getType()->getElementType();
842 TypePrinter.print(ETy, Out);
844 WriteAsOperandInternal(Out, CA->getOperand(0),
845 &TypePrinter, Machine,
847 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
849 TypePrinter.print(ETy, Out);
851 WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
858 if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
859 // As a special case, print the array as a string if it is an array of
860 // i8 with ConstantInt values.
861 if (CA->isString()) {
863 PrintEscapedString(CA->getAsString(), Out);
868 Type *ETy = CA->getType()->getElementType();
870 TypePrinter.print(ETy, Out);
872 WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
873 &TypePrinter, Machine,
875 for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
877 TypePrinter.print(ETy, Out);
879 WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
887 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
888 if (CS->getType()->isPacked())
891 unsigned N = CS->getNumOperands();
894 TypePrinter.print(CS->getOperand(0)->getType(), Out);
897 WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
900 for (unsigned i = 1; i < N; i++) {
902 TypePrinter.print(CS->getOperand(i)->getType(), Out);
905 WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
912 if (CS->getType()->isPacked())
917 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
918 Type *ETy = CV->getType()->getVectorElementType();
920 TypePrinter.print(ETy, Out);
922 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
924 for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
926 TypePrinter.print(ETy, Out);
928 WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
935 if (isa<ConstantPointerNull>(CV)) {
940 if (isa<UndefValue>(CV)) {
945 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
946 Out << CE->getOpcodeName();
947 WriteOptimizationInfo(Out, CE);
949 Out << ' ' << getPredicateText(CE->getPredicate());
952 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
953 TypePrinter.print((*OI)->getType(), Out);
955 WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
956 if (OI+1 != CE->op_end())
960 if (CE->hasIndices()) {
961 ArrayRef<unsigned> Indices = CE->getIndices();
962 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
963 Out << ", " << Indices[i];
968 TypePrinter.print(CE->getType(), Out);
975 Out << "<placeholder or erroneous Constant>";
978 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
979 TypePrinting *TypePrinter,
980 SlotTracker *Machine,
981 const Module *Context) {
983 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
984 const Value *V = Node->getOperand(mi);
988 TypePrinter->print(V->getType(), Out);
990 WriteAsOperandInternal(Out, Node->getOperand(mi),
991 TypePrinter, Machine, Context);
1001 /// WriteAsOperand - Write the name of the specified value out to the specified
1002 /// ostream. This can be useful when you just want to print int %reg126, not
1003 /// the whole instruction that generated it.
1005 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
1006 TypePrinting *TypePrinter,
1007 SlotTracker *Machine,
1008 const Module *Context) {
1010 PrintLLVMName(Out, V);
1014 const Constant *CV = dyn_cast<Constant>(V);
1015 if (CV && !isa<GlobalValue>(CV)) {
1016 assert(TypePrinter && "Constants require TypePrinting!");
1017 WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
1021 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
1023 if (IA->hasSideEffects())
1024 Out << "sideeffect ";
1025 if (IA->isAlignStack())
1026 Out << "alignstack ";
1028 PrintEscapedString(IA->getAsmString(), Out);
1030 PrintEscapedString(IA->getConstraintString(), Out);
1035 if (const MDNode *N = dyn_cast<MDNode>(V)) {
1036 if (N->isFunctionLocal()) {
1037 // Print metadata inline, not via slot reference number.
1038 WriteMDNodeBodyInternal(Out, N, TypePrinter, Machine, Context);
1043 if (N->isFunctionLocal())
1044 Machine = new SlotTracker(N->getFunction());
1046 Machine = new SlotTracker(Context);
1048 int Slot = Machine->getMetadataSlot(N);
1056 if (const MDString *MDS = dyn_cast<MDString>(V)) {
1058 PrintEscapedString(MDS->getString(), Out);
1063 if (V->getValueID() == Value::PseudoSourceValueVal ||
1064 V->getValueID() == Value::FixedStackPseudoSourceValueVal) {
1071 // If we have a SlotTracker, use it.
1073 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1074 Slot = Machine->getGlobalSlot(GV);
1077 Slot = Machine->getLocalSlot(V);
1079 // If the local value didn't succeed, then we may be referring to a value
1080 // from a different function. Translate it, as this can happen when using
1081 // address of blocks.
1083 if ((Machine = createSlotTracker(V))) {
1084 Slot = Machine->getLocalSlot(V);
1088 } else if ((Machine = createSlotTracker(V))) {
1089 // Otherwise, create one to get the # and then destroy it.
1090 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1091 Slot = Machine->getGlobalSlot(GV);
1094 Slot = Machine->getLocalSlot(V);
1103 Out << Prefix << Slot;
1108 void llvm::WriteAsOperand(raw_ostream &Out, const Value *V,
1109 bool PrintType, const Module *Context) {
1111 // Fast path: Don't construct and populate a TypePrinting object if we
1112 // won't be needing any types printed.
1114 ((!isa<Constant>(V) && !isa<MDNode>(V)) ||
1115 V->hasName() || isa<GlobalValue>(V))) {
1116 WriteAsOperandInternal(Out, V, 0, 0, Context);
1120 if (Context == 0) Context = getModuleFromVal(V);
1122 TypePrinting TypePrinter;
1124 TypePrinter.incorporateTypes(*Context);
1126 TypePrinter.print(V->getType(), Out);
1130 WriteAsOperandInternal(Out, V, &TypePrinter, 0, Context);
1135 class AssemblyWriter {
1136 formatted_raw_ostream &Out;
1137 SlotTracker &Machine;
1138 const Module *TheModule;
1139 TypePrinting TypePrinter;
1140 AssemblyAnnotationWriter *AnnotationWriter;
1143 inline AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
1145 AssemblyAnnotationWriter *AAW)
1146 : Out(o), Machine(Mac), TheModule(M), AnnotationWriter(AAW) {
1148 TypePrinter.incorporateTypes(*M);
1151 void printMDNodeBody(const MDNode *MD);
1152 void printNamedMDNode(const NamedMDNode *NMD);
1154 void printModule(const Module *M);
1156 void writeOperand(const Value *Op, bool PrintType);
1157 void writeParamOperand(const Value *Operand, Attributes Attrs);
1158 void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
1160 void writeAllMDNodes();
1162 void printTypeIdentities();
1163 void printGlobal(const GlobalVariable *GV);
1164 void printAlias(const GlobalAlias *GV);
1165 void printFunction(const Function *F);
1166 void printArgument(const Argument *FA, Attributes Attrs);
1167 void printBasicBlock(const BasicBlock *BB);
1168 void printInstruction(const Instruction &I);
1171 // printInfoComment - Print a little comment after the instruction indicating
1172 // which slot it occupies.
1173 void printInfoComment(const Value &V);
1175 } // end of anonymous namespace
1177 void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
1179 Out << "<null operand!>";
1183 TypePrinter.print(Operand->getType(), Out);
1186 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1189 void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
1190 SynchronizationScope SynchScope) {
1191 if (Ordering == NotAtomic)
1194 switch (SynchScope) {
1195 case SingleThread: Out << " singlethread"; break;
1196 case CrossThread: break;
1200 default: Out << " <bad ordering " << int(Ordering) << ">"; break;
1201 case Unordered: Out << " unordered"; break;
1202 case Monotonic: Out << " monotonic"; break;
1203 case Acquire: Out << " acquire"; break;
1204 case Release: Out << " release"; break;
1205 case AcquireRelease: Out << " acq_rel"; break;
1206 case SequentiallyConsistent: Out << " seq_cst"; break;
1210 void AssemblyWriter::writeParamOperand(const Value *Operand,
1213 Out << "<null operand!>";
1218 TypePrinter.print(Operand->getType(), Out);
1219 // Print parameter attributes list
1220 if (Attrs != Attribute::None)
1221 Out << ' ' << Attribute::getAsString(Attrs);
1223 // Print the operand
1224 WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
1227 void AssemblyWriter::printModule(const Module *M) {
1228 if (!M->getModuleIdentifier().empty() &&
1229 // Don't print the ID if it will start a new line (which would
1230 // require a comment char before it).
1231 M->getModuleIdentifier().find('\n') == std::string::npos)
1232 Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
1234 if (!M->getDataLayout().empty())
1235 Out << "target datalayout = \"" << M->getDataLayout() << "\"\n";
1236 if (!M->getTargetTriple().empty())
1237 Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
1239 if (!M->getModuleInlineAsm().empty()) {
1240 // Split the string into lines, to make it easier to read the .ll file.
1241 std::string Asm = M->getModuleInlineAsm();
1243 size_t NewLine = Asm.find_first_of('\n', CurPos);
1245 while (NewLine != std::string::npos) {
1246 // We found a newline, print the portion of the asm string from the
1247 // last newline up to this newline.
1248 Out << "module asm \"";
1249 PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
1253 NewLine = Asm.find_first_of('\n', CurPos);
1255 std::string rest(Asm.begin()+CurPos, Asm.end());
1256 if (!rest.empty()) {
1257 Out << "module asm \"";
1258 PrintEscapedString(rest, Out);
1263 // Loop over the dependent libraries and emit them.
1264 Module::lib_iterator LI = M->lib_begin();
1265 Module::lib_iterator LE = M->lib_end();
1268 Out << "deplibs = [ ";
1270 Out << '"' << *LI << '"';
1278 printTypeIdentities();
1280 // Output all globals.
1281 if (!M->global_empty()) Out << '\n';
1282 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
1286 // Output all aliases.
1287 if (!M->alias_empty()) Out << "\n";
1288 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
1292 // Output all of the functions.
1293 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1296 // Output named metadata.
1297 if (!M->named_metadata_empty()) Out << '\n';
1299 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
1300 E = M->named_metadata_end(); I != E; ++I)
1301 printNamedMDNode(I);
1304 if (!Machine.mdn_empty()) {
1310 void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
1312 StringRef Name = NMD->getName();
1314 Out << "<empty name> ";
1316 if (isalpha(Name[0]) || Name[0] == '-' || Name[0] == '$' ||
1317 Name[0] == '.' || Name[0] == '_')
1320 Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
1321 for (unsigned i = 1, e = Name.size(); i != e; ++i) {
1322 unsigned char C = Name[i];
1323 if (isalnum(C) || C == '-' || C == '$' || C == '.' || C == '_')
1326 Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
1330 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1332 int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
1342 static void PrintLinkage(GlobalValue::LinkageTypes LT,
1343 formatted_raw_ostream &Out) {
1345 case GlobalValue::ExternalLinkage: break;
1346 case GlobalValue::PrivateLinkage: Out << "private "; break;
1347 case GlobalValue::LinkerPrivateLinkage: Out << "linker_private "; break;
1348 case GlobalValue::LinkerPrivateWeakLinkage:
1349 Out << "linker_private_weak ";
1351 case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
1352 Out << "linker_private_weak_def_auto ";
1354 case GlobalValue::InternalLinkage: Out << "internal "; break;
1355 case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
1356 case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
1357 case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
1358 case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
1359 case GlobalValue::CommonLinkage: Out << "common "; break;
1360 case GlobalValue::AppendingLinkage: Out << "appending "; break;
1361 case GlobalValue::DLLImportLinkage: Out << "dllimport "; break;
1362 case GlobalValue::DLLExportLinkage: Out << "dllexport "; break;
1363 case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
1364 case GlobalValue::AvailableExternallyLinkage:
1365 Out << "available_externally ";
1371 static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
1372 formatted_raw_ostream &Out) {
1374 case GlobalValue::DefaultVisibility: break;
1375 case GlobalValue::HiddenVisibility: Out << "hidden "; break;
1376 case GlobalValue::ProtectedVisibility: Out << "protected "; break;
1380 static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
1381 formatted_raw_ostream &Out) {
1383 case GlobalVariable::NotThreadLocal:
1385 case GlobalVariable::GeneralDynamicTLSModel:
1386 Out << "thread_local ";
1388 case GlobalVariable::LocalDynamicTLSModel:
1389 Out << "thread_local(localdynamic) ";
1391 case GlobalVariable::InitialExecTLSModel:
1392 Out << "thread_local(initialexec) ";
1394 case GlobalVariable::LocalExecTLSModel:
1395 Out << "thread_local(localexec) ";
1400 void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
1401 if (GV->isMaterializable())
1402 Out << "; Materializable\n";
1404 WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
1407 if (!GV->hasInitializer() && GV->hasExternalLinkage())
1410 PrintLinkage(GV->getLinkage(), Out);
1411 PrintVisibility(GV->getVisibility(), Out);
1412 PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
1414 if (unsigned AddressSpace = GV->getType()->getAddressSpace())
1415 Out << "addrspace(" << AddressSpace << ") ";
1416 if (GV->hasUnnamedAddr()) Out << "unnamed_addr ";
1417 Out << (GV->isConstant() ? "constant " : "global ");
1418 TypePrinter.print(GV->getType()->getElementType(), Out);
1420 if (GV->hasInitializer()) {
1422 writeOperand(GV->getInitializer(), false);
1425 if (GV->hasSection()) {
1426 Out << ", section \"";
1427 PrintEscapedString(GV->getSection(), Out);
1430 if (GV->getAlignment())
1431 Out << ", align " << GV->getAlignment();
1433 printInfoComment(*GV);
1437 void AssemblyWriter::printAlias(const GlobalAlias *GA) {
1438 if (GA->isMaterializable())
1439 Out << "; Materializable\n";
1441 // Don't crash when dumping partially built GA
1443 Out << "<<nameless>> = ";
1445 PrintLLVMName(Out, GA);
1448 PrintVisibility(GA->getVisibility(), Out);
1452 PrintLinkage(GA->getLinkage(), Out);
1454 const Constant *Aliasee = GA->getAliasee();
1457 TypePrinter.print(GA->getType(), Out);
1458 Out << " <<NULL ALIASEE>>";
1460 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
1463 printInfoComment(*GA);
1467 void AssemblyWriter::printTypeIdentities() {
1468 if (TypePrinter.NumberedTypes.empty() &&
1469 TypePrinter.NamedTypes.empty())
1474 // We know all the numbers that each type is used and we know that it is a
1475 // dense assignment. Convert the map to an index table.
1476 std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
1477 for (DenseMap<StructType*, unsigned>::iterator I =
1478 TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
1480 assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
1481 NumberedTypes[I->second] = I->first;
1484 // Emit all numbered types.
1485 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
1486 Out << '%' << i << " = type ";
1488 // Make sure we print out at least one level of the type structure, so
1489 // that we do not get %2 = type %2
1490 TypePrinter.printStructBody(NumberedTypes[i], Out);
1494 for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
1495 PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
1498 // Make sure we print out at least one level of the type structure, so
1499 // that we do not get %FILE = type %FILE
1500 TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
1505 /// printFunction - Print all aspects of a function.
1507 void AssemblyWriter::printFunction(const Function *F) {
1508 // Print out the return type and name.
1511 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
1513 if (F->isMaterializable())
1514 Out << "; Materializable\n";
1516 if (F->isDeclaration())
1521 PrintLinkage(F->getLinkage(), Out);
1522 PrintVisibility(F->getVisibility(), Out);
1524 // Print the calling convention.
1525 switch (F->getCallingConv()) {
1526 case CallingConv::C: break; // default
1527 case CallingConv::Fast: Out << "fastcc "; break;
1528 case CallingConv::Cold: Out << "coldcc "; break;
1529 case CallingConv::X86_StdCall: Out << "x86_stdcallcc "; break;
1530 case CallingConv::X86_FastCall: Out << "x86_fastcallcc "; break;
1531 case CallingConv::X86_ThisCall: Out << "x86_thiscallcc "; break;
1532 case CallingConv::ARM_APCS: Out << "arm_apcscc "; break;
1533 case CallingConv::ARM_AAPCS: Out << "arm_aapcscc "; break;
1534 case CallingConv::ARM_AAPCS_VFP:Out << "arm_aapcs_vfpcc "; break;
1535 case CallingConv::MSP430_INTR: Out << "msp430_intrcc "; break;
1536 case CallingConv::PTX_Kernel: Out << "ptx_kernel "; break;
1537 case CallingConv::PTX_Device: Out << "ptx_device "; break;
1538 default: Out << "cc" << F->getCallingConv() << " "; break;
1541 FunctionType *FT = F->getFunctionType();
1542 const AttrListPtr &Attrs = F->getAttributes();
1543 Attributes RetAttrs = Attrs.getRetAttributes();
1544 if (RetAttrs != Attribute::None)
1545 Out << Attribute::getAsString(Attrs.getRetAttributes()) << ' ';
1546 TypePrinter.print(F->getReturnType(), Out);
1548 WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
1550 Machine.incorporateFunction(F);
1552 // Loop over the arguments, printing them...
1555 if (!F->isDeclaration()) {
1556 // If this isn't a declaration, print the argument names as well.
1557 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1559 // Insert commas as we go... the first arg doesn't get a comma
1560 if (I != F->arg_begin()) Out << ", ";
1561 printArgument(I, Attrs.getParamAttributes(Idx));
1565 // Otherwise, print the types from the function type.
1566 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1567 // Insert commas as we go... the first arg doesn't get a comma
1571 TypePrinter.print(FT->getParamType(i), Out);
1573 Attributes ArgAttrs = Attrs.getParamAttributes(i+1);
1574 if (ArgAttrs != Attribute::None)
1575 Out << ' ' << Attribute::getAsString(ArgAttrs);
1579 // Finish printing arguments...
1580 if (FT->isVarArg()) {
1581 if (FT->getNumParams()) Out << ", ";
1582 Out << "..."; // Output varargs portion of signature!
1585 if (F->hasUnnamedAddr())
1586 Out << " unnamed_addr";
1587 Attributes FnAttrs = Attrs.getFnAttributes();
1588 if (FnAttrs != Attribute::None)
1589 Out << ' ' << Attribute::getAsString(Attrs.getFnAttributes());
1590 if (F->hasSection()) {
1591 Out << " section \"";
1592 PrintEscapedString(F->getSection(), Out);
1595 if (F->getAlignment())
1596 Out << " align " << F->getAlignment();
1598 Out << " gc \"" << F->getGC() << '"';
1599 if (F->isDeclaration()) {
1603 // Output all of the function's basic blocks.
1604 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1610 Machine.purgeFunction();
1613 /// printArgument - This member is called for every argument that is passed into
1614 /// the function. Simply print it out
1616 void AssemblyWriter::printArgument(const Argument *Arg,
1619 TypePrinter.print(Arg->getType(), Out);
1621 // Output parameter attributes list
1622 if (Attrs != Attribute::None)
1623 Out << ' ' << Attribute::getAsString(Attrs);
1625 // Output name, if available...
1626 if (Arg->hasName()) {
1628 PrintLLVMName(Out, Arg);
1632 /// printBasicBlock - This member is called for each basic block in a method.
1634 void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
1635 if (BB->hasName()) { // Print out the label if it exists...
1637 PrintLLVMName(Out, BB->getName(), LabelPrefix);
1639 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1640 Out << "\n; <label>:";
1641 int Slot = Machine.getLocalSlot(BB);
1648 if (BB->getParent() == 0) {
1649 Out.PadToColumn(50);
1650 Out << "; Error: Block without parent!";
1651 } else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
1652 // Output predecessors for the block.
1653 Out.PadToColumn(50);
1655 const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1658 Out << " No predecessors!";
1661 writeOperand(*PI, false);
1662 for (++PI; PI != PE; ++PI) {
1664 writeOperand(*PI, false);
1671 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
1673 // Output all of the instructions in the basic block...
1674 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1675 printInstruction(*I);
1679 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
1682 /// printInfoComment - Print a little comment after the instruction indicating
1683 /// which slot it occupies.
1685 void AssemblyWriter::printInfoComment(const Value &V) {
1686 if (AnnotationWriter) {
1687 AnnotationWriter->printInfoComment(V, Out);
1692 // This member is called for each Instruction in a function..
1693 void AssemblyWriter::printInstruction(const Instruction &I) {
1694 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
1696 // Print out indentation for an instruction.
1699 // Print out name if it exists...
1701 PrintLLVMName(Out, &I);
1703 } else if (!I.getType()->isVoidTy()) {
1704 // Print out the def slot taken.
1705 int SlotNum = Machine.getLocalSlot(&I);
1707 Out << "<badref> = ";
1709 Out << '%' << SlotNum << " = ";
1712 if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall())
1715 // Print out the opcode...
1716 Out << I.getOpcodeName();
1718 // If this is an atomic load or store, print out the atomic marker.
1719 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
1720 (isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
1723 // If this is a volatile operation, print out the volatile marker.
1724 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1725 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
1726 (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
1727 (isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
1730 // Print out optimization information.
1731 WriteOptimizationInfo(Out, &I);
1733 // Print out the compare instruction predicates
1734 if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
1735 Out << ' ' << getPredicateText(CI->getPredicate());
1737 // Print out the atomicrmw operation
1738 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
1739 writeAtomicRMWOperation(Out, RMWI->getOperation());
1741 // Print out the type of the operands...
1742 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1744 // Special case conditional branches to swizzle the condition out to the front
1745 if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
1746 BranchInst &BI(cast<BranchInst>(I));
1748 writeOperand(BI.getCondition(), true);
1750 writeOperand(BI.getSuccessor(0), true);
1752 writeOperand(BI.getSuccessor(1), true);
1754 } else if (isa<SwitchInst>(I)) {
1755 SwitchInst& SI(cast<SwitchInst>(I));
1756 // Special case switch instruction to get formatting nice and correct.
1758 writeOperand(SI.getCondition(), true);
1760 writeOperand(SI.getDefaultDest(), true);
1762 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1765 writeOperand(i.getCaseValue(), true);
1767 writeOperand(i.getCaseSuccessor(), true);
1770 } else if (isa<IndirectBrInst>(I)) {
1771 // Special case indirectbr instruction to get formatting nice and correct.
1773 writeOperand(Operand, true);
1776 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1779 writeOperand(I.getOperand(i), true);
1782 } else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
1784 TypePrinter.print(I.getType(), Out);
1787 for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
1788 if (op) Out << ", ";
1790 writeOperand(PN->getIncomingValue(op), false); Out << ", ";
1791 writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
1793 } else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
1795 writeOperand(I.getOperand(0), true);
1796 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1798 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
1800 writeOperand(I.getOperand(0), true); Out << ", ";
1801 writeOperand(I.getOperand(1), true);
1802 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1804 } else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
1806 TypePrinter.print(I.getType(), Out);
1807 Out << " personality ";
1808 writeOperand(I.getOperand(0), true); Out << '\n';
1810 if (LPI->isCleanup())
1813 for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
1814 if (i != 0 || LPI->isCleanup()) Out << "\n";
1815 if (LPI->isCatch(i))
1820 writeOperand(LPI->getClause(i), true);
1822 } else if (isa<ReturnInst>(I) && !Operand) {
1824 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1825 // Print the calling convention being used.
1826 switch (CI->getCallingConv()) {
1827 case CallingConv::C: break; // default
1828 case CallingConv::Fast: Out << " fastcc"; break;
1829 case CallingConv::Cold: Out << " coldcc"; break;
1830 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1831 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1832 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1833 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1834 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1835 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1836 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1837 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1838 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1839 default: Out << " cc" << CI->getCallingConv(); break;
1842 Operand = CI->getCalledValue();
1843 PointerType *PTy = cast<PointerType>(Operand->getType());
1844 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1845 Type *RetTy = FTy->getReturnType();
1846 const AttrListPtr &PAL = CI->getAttributes();
1848 if (PAL.getRetAttributes() != Attribute::None)
1849 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1851 // If possible, print out the short form of the call instruction. We can
1852 // only do this if the first argument is a pointer to a nonvararg function,
1853 // and if the return type is not a pointer to a function.
1856 if (!FTy->isVarArg() &&
1857 (!RetTy->isPointerTy() ||
1858 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1859 TypePrinter.print(RetTy, Out);
1861 writeOperand(Operand, false);
1863 writeOperand(Operand, true);
1866 for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
1869 writeParamOperand(CI->getArgOperand(op), PAL.getParamAttributes(op + 1));
1872 if (PAL.getFnAttributes() != Attribute::None)
1873 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1874 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1875 Operand = II->getCalledValue();
1876 PointerType *PTy = cast<PointerType>(Operand->getType());
1877 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1878 Type *RetTy = FTy->getReturnType();
1879 const AttrListPtr &PAL = II->getAttributes();
1881 // Print the calling convention being used.
1882 switch (II->getCallingConv()) {
1883 case CallingConv::C: break; // default
1884 case CallingConv::Fast: Out << " fastcc"; break;
1885 case CallingConv::Cold: Out << " coldcc"; break;
1886 case CallingConv::X86_StdCall: Out << " x86_stdcallcc"; break;
1887 case CallingConv::X86_FastCall: Out << " x86_fastcallcc"; break;
1888 case CallingConv::X86_ThisCall: Out << " x86_thiscallcc"; break;
1889 case CallingConv::ARM_APCS: Out << " arm_apcscc "; break;
1890 case CallingConv::ARM_AAPCS: Out << " arm_aapcscc "; break;
1891 case CallingConv::ARM_AAPCS_VFP:Out << " arm_aapcs_vfpcc "; break;
1892 case CallingConv::MSP430_INTR: Out << " msp430_intrcc "; break;
1893 case CallingConv::PTX_Kernel: Out << " ptx_kernel"; break;
1894 case CallingConv::PTX_Device: Out << " ptx_device"; break;
1895 default: Out << " cc" << II->getCallingConv(); break;
1898 if (PAL.getRetAttributes() != Attribute::None)
1899 Out << ' ' << Attribute::getAsString(PAL.getRetAttributes());
1901 // If possible, print out the short form of the invoke instruction. We can
1902 // only do this if the first argument is a pointer to a nonvararg function,
1903 // and if the return type is not a pointer to a function.
1906 if (!FTy->isVarArg() &&
1907 (!RetTy->isPointerTy() ||
1908 !cast<PointerType>(RetTy)->getElementType()->isFunctionTy())) {
1909 TypePrinter.print(RetTy, Out);
1911 writeOperand(Operand, false);
1913 writeOperand(Operand, true);
1916 for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
1919 writeParamOperand(II->getArgOperand(op), PAL.getParamAttributes(op + 1));
1923 if (PAL.getFnAttributes() != Attribute::None)
1924 Out << ' ' << Attribute::getAsString(PAL.getFnAttributes());
1927 writeOperand(II->getNormalDest(), true);
1929 writeOperand(II->getUnwindDest(), true);
1931 } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
1933 TypePrinter.print(AI->getType()->getElementType(), Out);
1934 if (!AI->getArraySize() || AI->isArrayAllocation()) {
1936 writeOperand(AI->getArraySize(), true);
1938 if (AI->getAlignment()) {
1939 Out << ", align " << AI->getAlignment();
1941 } else if (isa<CastInst>(I)) {
1944 writeOperand(Operand, true); // Work with broken code
1947 TypePrinter.print(I.getType(), Out);
1948 } else if (isa<VAArgInst>(I)) {
1951 writeOperand(Operand, true); // Work with broken code
1954 TypePrinter.print(I.getType(), Out);
1955 } else if (Operand) { // Print the normal way.
1957 // PrintAllTypes - Instructions who have operands of all the same type
1958 // omit the type from all but the first operand. If the instruction has
1959 // different type operands (for example br), then they are all printed.
1960 bool PrintAllTypes = false;
1961 Type *TheType = Operand->getType();
1963 // Select, Store and ShuffleVector always print all types.
1964 if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
1965 || isa<ReturnInst>(I)) {
1966 PrintAllTypes = true;
1968 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1969 Operand = I.getOperand(i);
1970 // note that Operand shouldn't be null, but the test helps make dump()
1971 // more tolerant of malformed IR
1972 if (Operand && Operand->getType() != TheType) {
1973 PrintAllTypes = true; // We have differing types! Print them all!
1979 if (!PrintAllTypes) {
1981 TypePrinter.print(TheType, Out);
1985 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1987 writeOperand(I.getOperand(i), PrintAllTypes);
1991 // Print atomic ordering/alignment for memory operations
1992 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1994 writeAtomic(LI->getOrdering(), LI->getSynchScope());
1995 if (LI->getAlignment())
1996 Out << ", align " << LI->getAlignment();
1997 } else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
1999 writeAtomic(SI->getOrdering(), SI->getSynchScope());
2000 if (SI->getAlignment())
2001 Out << ", align " << SI->getAlignment();
2002 } else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
2003 writeAtomic(CXI->getOrdering(), CXI->getSynchScope());
2004 } else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
2005 writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
2006 } else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
2007 writeAtomic(FI->getOrdering(), FI->getSynchScope());
2010 // Print Metadata info.
2011 SmallVector<std::pair<unsigned, MDNode*>, 4> InstMD;
2012 I.getAllMetadata(InstMD);
2013 if (!InstMD.empty()) {
2014 SmallVector<StringRef, 8> MDNames;
2015 I.getType()->getContext().getMDKindNames(MDNames);
2016 for (unsigned i = 0, e = InstMD.size(); i != e; ++i) {
2017 unsigned Kind = InstMD[i].first;
2018 if (Kind < MDNames.size()) {
2019 Out << ", !" << MDNames[Kind];
2021 Out << ", !<unknown kind #" << Kind << ">";
2024 WriteAsOperandInternal(Out, InstMD[i].second, &TypePrinter, &Machine,
2028 printInfoComment(I);
2031 static void WriteMDNodeComment(const MDNode *Node,
2032 formatted_raw_ostream &Out) {
2033 if (Node->getNumOperands() < 1)
2036 Value *Op = Node->getOperand(0);
2037 if (!Op || !isa<ConstantInt>(Op) || cast<ConstantInt>(Op)->getBitWidth() < 32)
2040 DIDescriptor Desc(Node);
2041 if (Desc.getVersion() < LLVMDebugVersion11)
2044 unsigned Tag = Desc.getTag();
2045 Out.PadToColumn(50);
2046 if (dwarf::TagString(Tag)) {
2049 } else if (Tag == dwarf::DW_TAG_user_base) {
2050 Out << "; [ DW_TAG_user_base ]";
2054 void AssemblyWriter::writeAllMDNodes() {
2055 SmallVector<const MDNode *, 16> Nodes;
2056 Nodes.resize(Machine.mdn_size());
2057 for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
2059 Nodes[I->second] = cast<MDNode>(I->first);
2061 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2062 Out << '!' << i << " = metadata ";
2063 printMDNodeBody(Nodes[i]);
2067 void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
2068 WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
2069 WriteMDNodeComment(Node, Out);
2073 //===----------------------------------------------------------------------===//
2074 // External Interface declarations
2075 //===----------------------------------------------------------------------===//
2077 void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2078 SlotTracker SlotTable(this);
2079 formatted_raw_ostream OS(ROS);
2080 AssemblyWriter W(OS, SlotTable, this, AAW);
2081 W.printModule(this);
2084 void NamedMDNode::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2085 SlotTracker SlotTable(getParent());
2086 formatted_raw_ostream OS(ROS);
2087 AssemblyWriter W(OS, SlotTable, getParent(), AAW);
2088 W.printNamedMDNode(this);
2091 void Type::print(raw_ostream &OS) const {
2093 OS << "<null Type>";
2097 TP.print(const_cast<Type*>(this), OS);
2099 // If the type is a named struct type, print the body as well.
2100 if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
2101 if (!STy->isLiteral()) {
2103 TP.printStructBody(STy, OS);
2107 void Value::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
2109 ROS << "printing a <null> value\n";
2112 formatted_raw_ostream OS(ROS);
2113 if (const Instruction *I = dyn_cast<Instruction>(this)) {
2114 const Function *F = I->getParent() ? I->getParent()->getParent() : 0;
2115 SlotTracker SlotTable(F);
2116 AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), AAW);
2117 W.printInstruction(*I);
2118 } else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
2119 SlotTracker SlotTable(BB->getParent());
2120 AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), AAW);
2121 W.printBasicBlock(BB);
2122 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
2123 SlotTracker SlotTable(GV->getParent());
2124 AssemblyWriter W(OS, SlotTable, GV->getParent(), AAW);
2125 if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
2127 else if (const Function *F = dyn_cast<Function>(GV))
2130 W.printAlias(cast<GlobalAlias>(GV));
2131 } else if (const MDNode *N = dyn_cast<MDNode>(this)) {
2132 const Function *F = N->getFunction();
2133 SlotTracker SlotTable(F);
2134 AssemblyWriter W(OS, SlotTable, F ? F->getParent() : 0, AAW);
2135 W.printMDNodeBody(N);
2136 } else if (const Constant *C = dyn_cast<Constant>(this)) {
2137 TypePrinting TypePrinter;
2138 TypePrinter.print(C->getType(), OS);
2140 WriteConstantInternal(OS, C, TypePrinter, 0, 0);
2141 } else if (isa<InlineAsm>(this) || isa<MDString>(this) ||
2142 isa<Argument>(this)) {
2143 WriteAsOperand(OS, this, true, 0);
2145 // Otherwise we don't know what it is. Call the virtual function to
2146 // allow a subclass to print itself.
2151 // Value::printCustom - subclasses should override this to implement printing.
2152 void Value::printCustom(raw_ostream &OS) const {
2153 llvm_unreachable("Unknown value to print out!");
2156 // Value::dump - allow easy printing of Values from the debugger.
2157 void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
2159 // Type::dump - allow easy printing of Types from the debugger.
2160 void Type::dump() const { print(dbgs()); }
2162 // Module::dump() - Allow printing of Modules from the debugger.
2163 void Module::dump() const { print(dbgs(), 0); }
2165 // NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
2166 void NamedMDNode::dump() const { print(dbgs(), 0); }