blob: 54a28e9f83314614f4e7d333959ca8e034d738da [file] [log] [blame]
Reid Spencerfb0c0dc2006-05-29 00:57:22 +00001//===-- CppWriter.cpp - Printing LLVM IR as a C++ Source File -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the writing of the LLVM IR as a set of C++ calls to the
11// LLVM IR interface. The input module is assumed to be verified.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CallingConv.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instruction.h"
20#include "llvm/Instructions.h"
21#include "llvm/Module.h"
22#include "llvm/SymbolTable.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/Support/MathExtras.h"
27#include <algorithm>
28#include <iostream>
29
30using namespace llvm;
31
32namespace {
33/// This class provides computation of slot numbers for LLVM Assembly writing.
34/// @brief LLVM Assembly Writing Slot Computation.
35class SlotMachine {
36
37/// @name Types
38/// @{
39public:
40
41 /// @brief A mapping of Values to slot numbers
42 typedef std::map<const Value*, unsigned> ValueMap;
43 typedef std::map<const Type*, unsigned> TypeMap;
44
45 /// @brief A plane with next slot number and ValueMap
46 struct ValuePlane {
47 unsigned next_slot; ///< The next slot number to use
48 ValueMap map; ///< The map of Value* -> unsigned
49 ValuePlane() { next_slot = 0; } ///< Make sure we start at 0
50 };
51
52 struct TypePlane {
53 unsigned next_slot;
54 TypeMap map;
55 TypePlane() { next_slot = 0; }
56 void clear() { map.clear(); next_slot = 0; }
57 };
58
59 /// @brief The map of planes by Type
60 typedef std::map<const Type*, ValuePlane> TypedPlanes;
61
62/// @}
63/// @name Constructors
64/// @{
65public:
66 /// @brief Construct from a module
67 SlotMachine(const Module *M );
68
69/// @}
70/// @name Accessors
71/// @{
72public:
73 /// Return the slot number of the specified value in it's type
74 /// plane. Its an error to ask for something not in the SlotMachine.
75 /// Its an error to ask for a Type*
76 int getSlot(const Value *V);
77 int getSlot(const Type*Ty);
78
79 /// Determine if a Value has a slot or not
80 bool hasSlot(const Value* V);
81 bool hasSlot(const Type* Ty);
82
83/// @}
84/// @name Mutators
85/// @{
86public:
87 /// If you'd like to deal with a function instead of just a module, use
88 /// this method to get its data into the SlotMachine.
89 void incorporateFunction(const Function *F) {
90 TheFunction = F;
91 FunctionProcessed = false;
92 }
93
94 /// After calling incorporateFunction, use this method to remove the
95 /// most recently incorporated function from the SlotMachine. This
96 /// will reset the state of the machine back to just the module contents.
97 void purgeFunction();
98
99/// @}
100/// @name Implementation Details
101/// @{
102private:
103 /// Values can be crammed into here at will. If they haven't
104 /// been inserted already, they get inserted, otherwise they are ignored.
105 /// Either way, the slot number for the Value* is returned.
106 unsigned createSlot(const Value *V);
107 unsigned createSlot(const Type* Ty);
108
109 /// Insert a value into the value table. Return the slot number
110 /// that it now occupies. BadThings(TM) will happen if you insert a
111 /// Value that's already been inserted.
112 unsigned insertValue( const Value *V );
113 unsigned insertValue( const Type* Ty);
114
115 /// Add all of the module level global variables (and their initializers)
116 /// and function declarations, but not the contents of those functions.
117 void processModule();
118
119 /// Add all of the functions arguments, basic blocks, and instructions
120 void processFunction();
121
122 SlotMachine(const SlotMachine &); // DO NOT IMPLEMENT
123 void operator=(const SlotMachine &); // DO NOT IMPLEMENT
124
125/// @}
126/// @name Data
127/// @{
128public:
129
130 /// @brief The module for which we are holding slot numbers
131 const Module* TheModule;
132
133 /// @brief The function for which we are holding slot numbers
134 const Function* TheFunction;
135 bool FunctionProcessed;
136
137 /// @brief The TypePlanes map for the module level data
138 TypedPlanes mMap;
139 TypePlane mTypes;
140
141 /// @brief The TypePlanes map for the function level data
142 TypedPlanes fMap;
143 TypePlane fTypes;
144
145/// @}
146
147};
148
149typedef std::vector<const Type*> TypeList;
150typedef std::map<const Type*,std::string> TypeMap;
151typedef std::map<const Value*,std::string> ValueMap;
152
153void WriteAsOperandInternal(std::ostream &Out, const Value *V,
154 bool PrintName, TypeMap &TypeTable,
155 SlotMachine *Machine);
156
157void WriteAsOperandInternal(std::ostream &Out, const Type *T,
158 bool PrintName, TypeMap& TypeTable,
159 SlotMachine *Machine);
160
161const Module *getModuleFromVal(const Value *V) {
162 if (const Argument *MA = dyn_cast<Argument>(V))
163 return MA->getParent() ? MA->getParent()->getParent() : 0;
164 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
165 return BB->getParent() ? BB->getParent()->getParent() : 0;
166 else if (const Instruction *I = dyn_cast<Instruction>(V)) {
167 const Function *M = I->getParent() ? I->getParent()->getParent() : 0;
168 return M ? M->getParent() : 0;
169 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
170 return GV->getParent();
171 return 0;
172}
173
174// getLLVMName - Turn the specified string into an 'LLVM name', which is either
175// prefixed with % (if the string only contains simple characters) or is
176// surrounded with ""'s (if it has special chars in it).
177std::string getLLVMName(const std::string &Name,
178 bool prefixName = true) {
179 assert(!Name.empty() && "Cannot get empty name!");
180
181 // First character cannot start with a number...
182 if (Name[0] >= '0' && Name[0] <= '9')
183 return "\"" + Name + "\"";
184
185 // Scan to see if we have any characters that are not on the "white list"
186 for (unsigned i = 0, e = Name.size(); i != e; ++i) {
187 char C = Name[i];
188 assert(C != '"' && "Illegal character in LLVM value name!");
189 if ((C < 'a' || C > 'z') && (C < 'A' || C > 'Z') && (C < '0' || C > '9') &&
190 C != '-' && C != '.' && C != '_')
191 return "\"" + Name + "\"";
192 }
193
194 // If we get here, then the identifier is legal to use as a "VarID".
195 if (prefixName)
196 return "%"+Name;
197 else
198 return Name;
199}
200
201
202/// fillTypeNameTable - If the module has a symbol table, take all global types
203/// and stuff their names into the TypeNames map.
204///
205void fillTypeNameTable(const Module *M, TypeMap& TypeNames) {
206 if (!M) return;
207 const SymbolTable &ST = M->getSymbolTable();
208 SymbolTable::type_const_iterator TI = ST.type_begin();
209 for (; TI != ST.type_end(); ++TI ) {
210 // As a heuristic, don't insert pointer to primitive types, because
211 // they are used too often to have a single useful name.
212 //
213 const Type *Ty = cast<Type>(TI->second);
214 if (!isa<PointerType>(Ty) ||
215 !cast<PointerType>(Ty)->getElementType()->isPrimitiveType() ||
216 isa<OpaqueType>(cast<PointerType>(Ty)->getElementType()))
217 TypeNames.insert(std::make_pair(Ty, getLLVMName(TI->first)));
218 }
219}
220
221void calcTypeName(const Type *Ty,
222 std::vector<const Type *> &TypeStack,
223 TypeMap& TypeNames,
224 std::string & Result){
225 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty)) {
226 Result += Ty->getDescription(); // Base case
227 return;
228 }
229
230 // Check to see if the type is named.
231 TypeMap::iterator I = TypeNames.find(Ty);
232 if (I != TypeNames.end()) {
233 Result += I->second;
234 return;
235 }
236
237 if (isa<OpaqueType>(Ty)) {
238 Result += "opaque";
239 return;
240 }
241
242 // Check to see if the Type is already on the stack...
243 unsigned Slot = 0, CurSize = TypeStack.size();
244 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
245
246 // This is another base case for the recursion. In this case, we know
247 // that we have looped back to a type that we have previously visited.
248 // Generate the appropriate upreference to handle this.
249 if (Slot < CurSize) {
250 Result += "\\" + utostr(CurSize-Slot); // Here's the upreference
251 return;
252 }
253
254 TypeStack.push_back(Ty); // Recursive case: Add us to the stack..
255
256 switch (Ty->getTypeID()) {
257 case Type::FunctionTyID: {
258 const FunctionType *FTy = cast<FunctionType>(Ty);
259 calcTypeName(FTy->getReturnType(), TypeStack, TypeNames, Result);
260 Result += " (";
261 for (FunctionType::param_iterator I = FTy->param_begin(),
262 E = FTy->param_end(); I != E; ++I) {
263 if (I != FTy->param_begin())
264 Result += ", ";
265 calcTypeName(*I, TypeStack, TypeNames, Result);
266 }
267 if (FTy->isVarArg()) {
268 if (FTy->getNumParams()) Result += ", ";
269 Result += "...";
270 }
271 Result += ")";
272 break;
273 }
274 case Type::StructTyID: {
275 const StructType *STy = cast<StructType>(Ty);
276 Result += "{ ";
277 for (StructType::element_iterator I = STy->element_begin(),
278 E = STy->element_end(); I != E; ++I) {
279 if (I != STy->element_begin())
280 Result += ", ";
281 calcTypeName(*I, TypeStack, TypeNames, Result);
282 }
283 Result += " }";
284 break;
285 }
286 case Type::PointerTyID:
287 calcTypeName(cast<PointerType>(Ty)->getElementType(),
288 TypeStack, TypeNames, Result);
289 Result += "*";
290 break;
291 case Type::ArrayTyID: {
292 const ArrayType *ATy = cast<ArrayType>(Ty);
293 Result += "[" + utostr(ATy->getNumElements()) + " x ";
294 calcTypeName(ATy->getElementType(), TypeStack, TypeNames, Result);
295 Result += "]";
296 break;
297 }
298 case Type::PackedTyID: {
299 const PackedType *PTy = cast<PackedType>(Ty);
300 Result += "<" + utostr(PTy->getNumElements()) + " x ";
301 calcTypeName(PTy->getElementType(), TypeStack, TypeNames, Result);
302 Result += ">";
303 break;
304 }
305 case Type::OpaqueTyID:
306 Result += "opaque";
307 break;
308 default:
309 Result += "<unrecognized-type>";
310 }
311
312 TypeStack.pop_back(); // Remove self from stack...
313 return;
314}
315
316
317/// printTypeInt - The internal guts of printing out a type that has a
318/// potentially named portion.
319///
320std::ostream &printTypeInt(std::ostream &Out, const Type *Ty,TypeMap&TypeNames){
321 // Primitive types always print out their description, regardless of whether
322 // they have been named or not.
323 //
324 if (Ty->isPrimitiveType() && !isa<OpaqueType>(Ty))
325 return Out << Ty->getDescription();
326
327 // Check to see if the type is named.
328 TypeMap::iterator I = TypeNames.find(Ty);
329 if (I != TypeNames.end()) return Out << I->second;
330
331 // Otherwise we have a type that has not been named but is a derived type.
332 // Carefully recurse the type hierarchy to print out any contained symbolic
333 // names.
334 //
335 std::vector<const Type *> TypeStack;
336 std::string TypeName;
337 calcTypeName(Ty, TypeStack, TypeNames, TypeName);
338 TypeNames.insert(std::make_pair(Ty, TypeName));//Cache type name for later use
339 return (Out << TypeName);
340}
341
342
343/// WriteTypeSymbolic - This attempts to write the specified type as a symbolic
344/// type, iff there is an entry in the modules symbol table for the specified
345/// type or one of it's component types. This is slower than a simple x << Type
346///
347std::ostream &WriteTypeSymbolic(std::ostream &Out, const Type *Ty,
348 const Module *M) {
349 Out << ' ';
350
351 // If they want us to print out a type, attempt to make it symbolic if there
352 // is a symbol table in the module...
353 if (M) {
354 TypeMap TypeNames;
355 fillTypeNameTable(M, TypeNames);
356
357 return printTypeInt(Out, Ty, TypeNames);
358 } else {
359 return Out << Ty->getDescription();
360 }
361}
362
363// PrintEscapedString - Print each character of the specified string, escaping
364// it if it is not printable or if it is an escape char.
365void PrintEscapedString(const std::string &Str, std::ostream &Out) {
366 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
367 unsigned char C = Str[i];
368 if (isprint(C) && C != '"' && C != '\\') {
369 Out << C;
370 } else {
371 Out << '\\'
372 << (char) ((C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
373 << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
374 }
375 }
376}
377
378/// @brief Internal constant writer.
379void WriteConstantInternal(std::ostream &Out, const Constant *CV,
380 bool PrintName,
381 TypeMap& TypeTable,
382 SlotMachine *Machine) {
383 const int IndentSize = 4;
384 static std::string Indent = "\n";
385 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
386 Out << (CB == ConstantBool::True ? "true" : "false");
387 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
388 Out << CI->getValue();
389 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
390 Out << CI->getValue();
391 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
392 // We would like to output the FP constant value in exponential notation,
393 // but we cannot do this if doing so will lose precision. Check here to
394 // make sure that we only output it in exponential format if we can parse
395 // the value back and get the same value.
396 //
397 std::string StrVal = ftostr(CFP->getValue());
398
399 // Check to make sure that the stringized number is not some string like
400 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
401 // the string matches the "[-+]?[0-9]" regex.
402 //
403 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
404 ((StrVal[0] == '-' || StrVal[0] == '+') &&
405 (StrVal[1] >= '0' && StrVal[1] <= '9')))
406 // Reparse stringized version!
407 if (atof(StrVal.c_str()) == CFP->getValue()) {
408 Out << StrVal;
409 return;
410 }
411
412 // Otherwise we could not reparse it to exactly the same value, so we must
413 // output the string in hexadecimal format!
414 assert(sizeof(double) == sizeof(uint64_t) &&
415 "assuming that double is 64 bits!");
416 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue()));
417
418 } else if (isa<ConstantAggregateZero>(CV)) {
419 Out << "zeroinitializer";
420 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
421 // As a special case, print the array as a string if it is an array of
422 // ubytes or an array of sbytes with positive values.
423 //
424 const Type *ETy = CA->getType()->getElementType();
425 if (CA->isString()) {
426 Out << "c\"";
427 PrintEscapedString(CA->getAsString(), Out);
428 Out << "\"";
429
430 } else { // Cannot output in string format...
431 Out << '[';
432 if (CA->getNumOperands()) {
433 Out << ' ';
434 printTypeInt(Out, ETy, TypeTable);
435 WriteAsOperandInternal(Out, CA->getOperand(0),
436 PrintName, TypeTable, Machine);
437 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
438 Out << ", ";
439 printTypeInt(Out, ETy, TypeTable);
440 WriteAsOperandInternal(Out, CA->getOperand(i), PrintName,
441 TypeTable, Machine);
442 }
443 }
444 Out << " ]";
445 }
446 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
447 Out << '{';
448 unsigned N = CS->getNumOperands();
449 if (N) {
450 if (N > 2) {
451 Indent += std::string(IndentSize, ' ');
452 Out << Indent;
453 } else {
454 Out << ' ';
455 }
456 printTypeInt(Out, CS->getOperand(0)->getType(), TypeTable);
457
458 WriteAsOperandInternal(Out, CS->getOperand(0),
459 PrintName, TypeTable, Machine);
460
461 for (unsigned i = 1; i < N; i++) {
462 Out << ", ";
463 if (N > 2) Out << Indent;
464 printTypeInt(Out, CS->getOperand(i)->getType(), TypeTable);
465
466 WriteAsOperandInternal(Out, CS->getOperand(i),
467 PrintName, TypeTable, Machine);
468 }
469 if (N > 2) Indent.resize(Indent.size() - IndentSize);
470 }
471
472 Out << " }";
473 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
474 const Type *ETy = CP->getType()->getElementType();
475 assert(CP->getNumOperands() > 0 &&
476 "Number of operands for a PackedConst must be > 0");
477 Out << '<';
478 Out << ' ';
479 printTypeInt(Out, ETy, TypeTable);
480 WriteAsOperandInternal(Out, CP->getOperand(0),
481 PrintName, TypeTable, Machine);
482 for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
483 Out << ", ";
484 printTypeInt(Out, ETy, TypeTable);
485 WriteAsOperandInternal(Out, CP->getOperand(i), PrintName,
486 TypeTable, Machine);
487 }
488 Out << " >";
489 } else if (isa<ConstantPointerNull>(CV)) {
490 Out << "null";
491
492 } else if (isa<UndefValue>(CV)) {
493 Out << "undef";
494
495 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
496 Out << CE->getOpcodeName() << " (";
497
498 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
499 printTypeInt(Out, (*OI)->getType(), TypeTable);
500 WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
501 if (OI+1 != CE->op_end())
502 Out << ", ";
503 }
504
505 if (CE->getOpcode() == Instruction::Cast) {
506 Out << " to ";
507 printTypeInt(Out, CE->getType(), TypeTable);
508 }
509 Out << ')';
510
511 } else {
512 Out << "<placeholder or erroneous Constant>";
513 }
514}
515
516
517/// WriteAsOperand - Write the name of the specified value out to the specified
518/// ostream. This can be useful when you just want to print int %reg126, not
519/// the whole instruction that generated it.
520///
521void WriteAsOperandInternal(std::ostream &Out, const Value *V,
522 bool PrintName, TypeMap& TypeTable,
523 SlotMachine *Machine) {
524 Out << ' ';
525 if ((PrintName || isa<GlobalValue>(V)) && V->hasName())
526 Out << getLLVMName(V->getName());
527 else {
528 const Constant *CV = dyn_cast<Constant>(V);
529 if (CV && !isa<GlobalValue>(CV)) {
530 WriteConstantInternal(Out, CV, PrintName, TypeTable, Machine);
531 } else if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
532 Out << "asm ";
533 if (IA->hasSideEffects())
534 Out << "sideeffect ";
535 Out << '"';
536 PrintEscapedString(IA->getAsmString(), Out);
537 Out << "\", \"";
538 PrintEscapedString(IA->getConstraintString(), Out);
539 Out << '"';
540 } else {
541 int Slot = Machine->getSlot(V);
542 if (Slot != -1)
543 Out << '%' << Slot;
544 else
545 Out << "<badref>";
546 }
547 }
548}
549
550/// WriteAsOperand - Write the name of the specified value out to the specified
551/// ostream. This can be useful when you just want to print int %reg126, not
552/// the whole instruction that generated it.
553///
554std::ostream &WriteAsOperand(std::ostream &Out, const Value *V,
555 bool PrintType, bool PrintName,
556 const Module *Context) {
557 TypeMap TypeNames;
558 if (Context == 0) Context = getModuleFromVal(V);
559
560 if (Context)
561 fillTypeNameTable(Context, TypeNames);
562
563 if (PrintType)
564 printTypeInt(Out, V->getType(), TypeNames);
565
566 WriteAsOperandInternal(Out, V, PrintName, TypeNames, 0);
567 return Out;
568}
569
570/// WriteAsOperandInternal - Write the name of the specified value out to
571/// the specified ostream. This can be useful when you just want to print
572/// int %reg126, not the whole instruction that generated it.
573///
574void WriteAsOperandInternal(std::ostream &Out, const Type *T,
575 bool PrintName, TypeMap& TypeTable,
576 SlotMachine *Machine) {
577 Out << ' ';
578 int Slot = Machine->getSlot(T);
579 if (Slot != -1)
580 Out << '%' << Slot;
581 else
582 Out << "<badref>";
583}
584
585/// WriteAsOperand - Write the name of the specified value out to the specified
586/// ostream. This can be useful when you just want to print int %reg126, not
587/// the whole instruction that generated it.
588///
589std::ostream &WriteAsOperand(std::ostream &Out, const Type *Ty,
590 bool PrintType, bool PrintName,
591 const Module *Context) {
592 TypeMap TypeNames;
593 assert(Context != 0 && "Can't write types as operand without module context");
594
595 fillTypeNameTable(Context, TypeNames);
596
597 // if (PrintType)
598 // printTypeInt(Out, V->getType(), TypeNames);
599
600 printTypeInt(Out, Ty, TypeNames);
601
602 WriteAsOperandInternal(Out, Ty, PrintName, TypeNames, 0);
603 return Out;
604}
605
606class CppWriter {
607 std::ostream &Out;
608 SlotMachine &Machine;
609 const Module *TheModule;
610 unsigned long uniqueNum;
611 TypeMap TypeNames;
612 ValueMap ValueNames;
613 TypeMap UnresolvedTypes;
614 TypeList TypeStack;
615
616public:
617 inline CppWriter(std::ostream &o, SlotMachine &Mac, const Module *M)
618 : Out(o), Machine(Mac), TheModule(M), uniqueNum(0), TypeNames(),
619 ValueNames(), UnresolvedTypes(), TypeStack() { }
620
621 inline void write(const Module *M) { printModule(M); }
622 inline void write(const GlobalVariable *G) { printGlobal(G); }
623 inline void write(const Function *F) { printFunction(F); }
624 inline void write(const BasicBlock *BB) { printBasicBlock(BB); }
625 inline void write(const Instruction *I) { printInstruction(*I); }
626 inline void write(const Constant *CPV) { printConstant(CPV); }
627 inline void write(const Type *Ty) { printType(Ty); }
628
629 void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
630
631 const Module* getModule() { return TheModule; }
632
633private:
634 void printModule(const Module *M);
635 void printTypes(const Module* M);
636 void printConstants(const Module* M);
637 void printConstant(const Constant *CPV);
638 void printGlobal(const GlobalVariable *GV);
639 void printFunction(const Function *F);
640 void printArgument(const Argument *FA);
641 void printBasicBlock(const BasicBlock *BB);
642 void printInstruction(const Instruction &I);
643 void printSymbolTable(const SymbolTable &ST);
644 void printLinkageType(GlobalValue::LinkageTypes LT);
645 void printCallingConv(unsigned cc);
646
647
648 // printType - Go to extreme measures to attempt to print out a short,
649 // symbolic version of a type name.
650 //
651 std::ostream &printType(const Type *Ty) {
652 return printTypeInt(Out, Ty, TypeNames);
653 }
654
655 // printTypeAtLeastOneLevel - Print out one level of the possibly complex type
656 // without considering any symbolic types that we may have equal to it.
657 //
658 std::ostream &printTypeAtLeastOneLevel(const Type *Ty);
659
660 // printInfoComment - Print a little comment after the instruction indicating
661 // which slot it occupies.
662 void printInfoComment(const Value &V);
663
664 std::string getCppName(const Type* val);
665 std::string getCppName(const Value* val);
666 inline void printCppName(const Value* val);
667 inline void printCppName(const Type* val);
668 bool isOnStack(const Type*) const;
669 inline void printTypeDef(const Type* Ty);
670 bool printTypeDefInternal(const Type* Ty);
671};
672
673std::string
674CppWriter::getCppName(const Value* val) {
675 std::string name;
676 ValueMap::iterator I = ValueNames.find(val);
677 if (I != ValueNames.end()) {
678 name = I->second;
679 } else {
680 const char* prefix;
681 switch (val->getType()->getTypeID()) {
682 case Type::VoidTyID: prefix = "void_"; break;
683 case Type::BoolTyID: prefix = "bool_"; break;
684 case Type::UByteTyID: prefix = "ubyte_"; break;
685 case Type::SByteTyID: prefix = "sbyte_"; break;
686 case Type::UShortTyID: prefix = "ushort_"; break;
687 case Type::ShortTyID: prefix = "short_"; break;
688 case Type::UIntTyID: prefix = "uint_"; break;
689 case Type::IntTyID: prefix = "int_"; break;
690 case Type::ULongTyID: prefix = "ulong_"; break;
691 case Type::LongTyID: prefix = "long_"; break;
692 case Type::FloatTyID: prefix = "float_"; break;
693 case Type::DoubleTyID: prefix = "double_"; break;
694 case Type::LabelTyID: prefix = "label_"; break;
695 case Type::FunctionTyID: prefix = "func_"; break;
696 case Type::StructTyID: prefix = "struct_"; break;
697 case Type::ArrayTyID: prefix = "array_"; break;
698 case Type::PointerTyID: prefix = "ptr_"; break;
699 case Type::PackedTyID: prefix = "packed_"; break;
700 default: prefix = "other_"; break;
701 }
702 name = ValueNames[val] = std::string(prefix) +
703 (val->hasName() ? val->getName() : utostr(uniqueNum++));
704 }
705 return name;
706}
707
708void
709CppWriter::printCppName(const Value* val) {
710 PrintEscapedString(getCppName(val),Out);
711}
712
713void
714CppWriter::printCppName(const Type* Ty)
715{
716 PrintEscapedString(getCppName(Ty),Out);
717}
718
719// Gets the C++ name for a type. Returns true if we already saw the type,
720// false otherwise.
721//
722inline const std::string*
723findTypeName(const SymbolTable& ST, const Type* Ty)
724{
725 SymbolTable::type_const_iterator TI = ST.type_begin();
726 SymbolTable::type_const_iterator TE = ST.type_end();
727 for (;TI != TE; ++TI)
728 if (TI->second == Ty)
729 return &(TI->first);
730 return 0;
731}
732
733std::string
734CppWriter::getCppName(const Type* Ty)
735{
736 // First, handle the primitive types .. easy
737 if (Ty->isPrimitiveType()) {
738 switch (Ty->getTypeID()) {
739 case Type::VoidTyID: return "Type::VoidTy";
740 case Type::BoolTyID: return "Type::BoolTy";
741 case Type::UByteTyID: return "Type::UByteTy";
742 case Type::SByteTyID: return "Type::SByteTy";
743 case Type::UShortTyID: return "Type::UShortTy";
744 case Type::ShortTyID: return "Type::ShortTy";
745 case Type::UIntTyID: return "Type::UIntTy";
746 case Type::IntTyID: return "Type::IntTy";
747 case Type::ULongTyID: return "Type::ULongTy";
748 case Type::LongTyID: return "Type::LongTy";
749 case Type::FloatTyID: return "Type::FloatTy";
750 case Type::DoubleTyID: return "Type::DoubleTy";
751 case Type::LabelTyID: return "Type::LabelTy";
752 default:
753 assert(!"Can't get here");
754 break;
755 }
756 return "Type::VoidTy"; // shouldn't be returned, but make it sensible
757 }
758
759 // Now, see if we've seen the type before and return that
760 TypeMap::iterator I = TypeNames.find(Ty);
761 if (I != TypeNames.end())
762 return I->second;
763
764 // Okay, let's build a new name for this type. Start with a prefix
765 const char* prefix = 0;
766 switch (Ty->getTypeID()) {
767 case Type::FunctionTyID: prefix = "FuncTy_"; break;
768 case Type::StructTyID: prefix = "StructTy_"; break;
769 case Type::ArrayTyID: prefix = "ArrayTy_"; break;
770 case Type::PointerTyID: prefix = "PointerTy_"; break;
771 case Type::OpaqueTyID: prefix = "OpaqueTy_"; break;
772 case Type::PackedTyID: prefix = "PackedTy_"; break;
773 default: prefix = "OtherTy_"; break; // prevent breakage
774 }
775
776 // See if the type has a name in the symboltable and build accordingly
777 const std::string* tName = findTypeName(TheModule->getSymbolTable(), Ty);
778 std::string name;
779 if (tName)
780 name = std::string(prefix) + *tName;
781 else
782 name = std::string(prefix) + utostr(uniqueNum++);
783
784 // Save the name
785 return TypeNames[Ty] = name;
786}
787
788/// printTypeAtLeastOneLevel - Print out one level of the possibly complex type
789/// without considering any symbolic types that we may have equal to it.
790///
791std::ostream &CppWriter::printTypeAtLeastOneLevel(const Type *Ty) {
792 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
793 printType(FTy->getReturnType()) << " (";
794 for (FunctionType::param_iterator I = FTy->param_begin(),
795 E = FTy->param_end(); I != E; ++I) {
796 if (I != FTy->param_begin())
797 Out << ", ";
798 printType(*I);
799 }
800 if (FTy->isVarArg()) {
801 if (FTy->getNumParams()) Out << ", ";
802 Out << "...";
803 }
804 Out << ')';
805 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
806 Out << "{ ";
807 for (StructType::element_iterator I = STy->element_begin(),
808 E = STy->element_end(); I != E; ++I) {
809 if (I != STy->element_begin())
810 Out << ", ";
811 printType(*I);
812 }
813 Out << " }";
814 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
815 printType(PTy->getElementType()) << '*';
816 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
817 Out << '[' << ATy->getNumElements() << " x ";
818 printType(ATy->getElementType()) << ']';
819 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
820 Out << '<' << PTy->getNumElements() << " x ";
821 printType(PTy->getElementType()) << '>';
822 }
823 else if (const OpaqueType *OTy = dyn_cast<OpaqueType>(Ty)) {
824 Out << "opaque";
825 } else {
826 if (!Ty->isPrimitiveType())
827 Out << "<unknown derived type>";
828 printType(Ty);
829 }
830 return Out;
831}
832
833
834void CppWriter::writeOperand(const Value *Operand, bool PrintType,
835 bool PrintName) {
836 if (Operand != 0) {
837 if (PrintType) { Out << ' '; printType(Operand->getType()); }
838 WriteAsOperandInternal(Out, Operand, PrintName, TypeNames, &Machine);
839 } else {
840 Out << "<null operand!>";
841 }
842}
843
844
845void CppWriter::printModule(const Module *M) {
846 Out << "\n// Module Construction\n";
847 Out << "Module* mod = new Module(\"";
848 PrintEscapedString(M->getModuleIdentifier(),Out);
849 Out << "\");\n";
850 Out << "mod->setEndianness(";
851 switch (M->getEndianness()) {
852 case Module::LittleEndian: Out << "Module::LittleEndian);\n"; break;
853 case Module::BigEndian: Out << "Module::BigEndian);\n"; break;
854 case Module::AnyEndianness:Out << "Module::AnyEndianness);\n"; break;
855 }
856 Out << "mod->setPointerSize(";
857 switch (M->getPointerSize()) {
858 case Module::Pointer32: Out << "Module::Pointer32);\n"; break;
859 case Module::Pointer64: Out << "Module::Pointer64);\n"; break;
860 case Module::AnyPointerSize: Out << "Module::AnyPointerSize);\n"; break;
861 }
862 if (!M->getTargetTriple().empty())
863 Out << "mod->setTargetTriple(\"" << M->getTargetTriple() << "\");\n";
864
865 if (!M->getModuleInlineAsm().empty()) {
866 Out << "mod->setModuleInlineAsm(\"";
867 PrintEscapedString(M->getModuleInlineAsm(),Out);
868 Out << "\");\n";
869 }
870
871 // Loop over the dependent libraries and emit them.
872 Module::lib_iterator LI = M->lib_begin();
873 Module::lib_iterator LE = M->lib_end();
874 while (LI != LE) {
875 Out << "mod->addLibrary(\"" << *LI << "\");\n";
876 ++LI;
877 }
878
879 // Print out all the type definitions
880 Out << "\n// Type Definitions\n";
881 printTypes(M);
882
883 // Print out all the constants declarations
884 Out << "\n// Constants Construction\n";
885 printConstants(M);
886
887 // Process the global variables
888 Out << "\n// Global Variable Construction\n";
889 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
890 I != E; ++I) {
891 printGlobal(I);
892 }
893
894 // Output all of the functions.
895 Out << "\n// Function Construction\n";
896 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
897 printFunction(I);
898}
899
900void
901CppWriter::printCallingConv(unsigned cc){
902 // Print the calling convention.
903 switch (cc) {
904 default:
905 case CallingConv::C: Out << "CallingConv::C"; break;
906 case CallingConv::CSRet: Out << "CallingConv::CSRet"; break;
907 case CallingConv::Fast: Out << "CallingConv::Fast"; break;
908 case CallingConv::Cold: Out << "CallingConv::Cold"; break;
909 case CallingConv::FirstTargetCC: Out << "CallingConv::FirstTargetCC"; break;
910 }
911}
912
913void
914CppWriter::printLinkageType(GlobalValue::LinkageTypes LT) {
915 switch (LT) {
916 case GlobalValue::InternalLinkage:
917 Out << "GlobalValue::InternalLinkage"; break;
918 case GlobalValue::LinkOnceLinkage:
919 Out << "GlobalValue::LinkOnceLinkage "; break;
920 case GlobalValue::WeakLinkage:
921 Out << "GlobalValue::WeakLinkage"; break;
922 case GlobalValue::AppendingLinkage:
923 Out << "GlobalValue::AppendingLinkage"; break;
924 case GlobalValue::ExternalLinkage:
925 Out << "GlobalValue::ExternalLinkage"; break;
926 case GlobalValue::GhostLinkage:
927 Out << "GlobalValue::GhostLinkage"; break;
928 }
929}
930void CppWriter::printGlobal(const GlobalVariable *GV) {
931 Out << "\n";
932 Out << "GlobalVariable* ";
933 printCppName(GV);
934 Out << " = new GlobalVariable(\n";
935 Out << " /*Type=*/";
936 printCppName(GV->getType()->getElementType());
937 Out << ",\n";
938 Out << " /*isConstant=*/" << (GV->isConstant()?"true":"false")
939 << ",\n /*Linkage=*/";
940 printLinkageType(GV->getLinkage());
941 Out << ",\n /*Initializer=*/";
942 if (GV->hasInitializer()) {
943 printCppName(GV->getInitializer());
944 } else {
945 Out << "0";
946 }
947 Out << ",\n /*Name=*/\"";
948 PrintEscapedString(GV->getName(),Out);
949 Out << "\",\n mod);\n";
950
951 if (GV->hasSection()) {
952 printCppName(GV);
953 Out << "->setSection(\"";
954 PrintEscapedString(GV->getSection(),Out);
955 Out << "\");\n";
956 }
957 if (GV->getAlignment()) {
958 printCppName(GV);
959 Out << "->setAlignment(" << utostr(GV->getAlignment()) << ");\n";
960 };
961}
962
963bool
964CppWriter::isOnStack(const Type* Ty) const {
965 TypeList::const_iterator TI =
966 std::find(TypeStack.begin(),TypeStack.end(),Ty);
967 return TI != TypeStack.end();
968}
969
970// Prints a type definition. Returns true if it could not resolve all the types
971// in the definition but had to use a forward reference.
972void
973CppWriter::printTypeDef(const Type* Ty) {
974 assert(TypeStack.empty());
975 TypeStack.clear();
976 printTypeDefInternal(Ty);
977 assert(TypeStack.empty());
978 // early resolve as many unresolved types as possible. Search the unresolved
979 // types map for the type we just printed. Now that its definition is complete
980 // we can resolve any preview references to it. This prevents a cascade of
981 // unresolved types.
982 TypeMap::iterator I = UnresolvedTypes.find(Ty);
983 if (I != UnresolvedTypes.end()) {
984 Out << "cast<OpaqueType>(" << I->second
985 << "_fwd.get())->refineAbstractTypeTo(" << I->second << ");\n";
986 Out << I->second << " = cast<";
987 switch (Ty->getTypeID()) {
988 case Type::FunctionTyID: Out << "FunctionType"; break;
989 case Type::ArrayTyID: Out << "ArrayType"; break;
990 case Type::StructTyID: Out << "StructType"; break;
991 case Type::PackedTyID: Out << "PackedType"; break;
992 case Type::PointerTyID: Out << "PointerType"; break;
993 case Type::OpaqueTyID: Out << "OpaqueType"; break;
994 default: Out << "NoSuchDerivedType"; break;
995 }
996 Out << ">(" << I->second << "_fwd.get());\n";
997 UnresolvedTypes.erase(I);
998 }
999 Out << "\n";
1000}
1001
1002bool
1003CppWriter::printTypeDefInternal(const Type* Ty) {
1004 // We don't print definitions for primitive types
1005 if (Ty->isPrimitiveType())
1006 return false;
1007
1008 // Determine if the name is in the name list before we modify that list.
1009 TypeMap::const_iterator TNI = TypeNames.find(Ty);
1010
1011 // Everything below needs the name for the type so get it now
1012 std::string typeName(getCppName(Ty));
1013
1014 // Search the type stack for recursion. If we find it, then generate this
1015 // as an OpaqueType, but make sure not to do this multiple times because
1016 // the type could appear in multiple places on the stack. Once the opaque
1017 // definition is issues, it must not be re-issued. Consequently we have to
1018 // check the UnresolvedTypes list as well.
1019 if (isOnStack(Ty)) {
1020 TypeMap::const_iterator I = UnresolvedTypes.find(Ty);
1021 if (I == UnresolvedTypes.end()) {
1022 Out << "PATypeHolder " << typeName << "_fwd = OpaqueType::get();\n";
1023 UnresolvedTypes[Ty] = typeName;
1024 return true;
1025 }
1026 }
1027
1028 // Avoid printing things we have already printed. Since TNI was obtained
1029 // before the name was inserted with getCppName and because we know the name
1030 // is not on the stack (currently being defined), we can surmise here that if
1031 // we got the name we've also already emitted its definition.
1032 if (TNI != TypeNames.end())
1033 return false;
1034
1035 // We're going to print a derived type which, by definition, contains other
1036 // types. So, push this one we're printing onto the type stack to assist with
1037 // recursive definitions.
1038 TypeStack.push_back(Ty); // push on type stack
1039 bool didRecurse = false;
1040
1041 // Print the type definition
1042 switch (Ty->getTypeID()) {
1043 case Type::FunctionTyID: {
1044 const FunctionType* FT = cast<FunctionType>(Ty);
1045 Out << "std::vector<const Type*>" << typeName << "_args;\n";
1046 FunctionType::param_iterator PI = FT->param_begin();
1047 FunctionType::param_iterator PE = FT->param_end();
1048 for (; PI != PE; ++PI) {
1049 const Type* argTy = static_cast<const Type*>(*PI);
1050 bool isForward = printTypeDefInternal(argTy);
1051 std::string argName(getCppName(argTy));
1052 Out << typeName << "_args.push_back(" << argName;
1053 if (isForward)
1054 Out << "_fwd";
1055 Out << ");\n";
1056 }
1057 bool isForward = printTypeDefInternal(FT->getReturnType());
1058 std::string retTypeName(getCppName(FT->getReturnType()));
1059 Out << "FunctionType* " << typeName << " = FunctionType::get(\n"
1060 << " /*Result=*/" << retTypeName;
1061 if (isForward)
1062 Out << "_fwd";
1063 Out << ",\n /*Params=*/" << typeName << "_args,\n /*isVarArg=*/"
1064 << (FT->isVarArg() ? "true" : "false") << ");\n";
1065 break;
1066 }
1067 case Type::StructTyID: {
1068 const StructType* ST = cast<StructType>(Ty);
1069 Out << "std::vector<const Type*>" << typeName << "_fields;\n";
1070 StructType::element_iterator EI = ST->element_begin();
1071 StructType::element_iterator EE = ST->element_end();
1072 for (; EI != EE; ++EI) {
1073 const Type* fieldTy = static_cast<const Type*>(*EI);
1074 bool isForward = printTypeDefInternal(fieldTy);
1075 std::string fieldName(getCppName(fieldTy));
1076 Out << typeName << "_fields.push_back(" << fieldName;
1077 if (isForward)
1078 Out << "_fwd";
1079 Out << ");\n";
1080 }
1081 Out << "StructType* " << typeName << " = StructType::get("
1082 << typeName << "_fields);\n";
1083 break;
1084 }
1085 case Type::ArrayTyID: {
1086 const ArrayType* AT = cast<ArrayType>(Ty);
1087 const Type* ET = AT->getElementType();
1088 bool isForward = printTypeDefInternal(ET);
1089 std::string elemName(getCppName(ET));
1090 Out << "ArrayType* " << typeName << " = ArrayType::get("
1091 << elemName << (isForward ? "_fwd" : "")
1092 << ", " << utostr(AT->getNumElements()) << ");\n";
1093 break;
1094 }
1095 case Type::PointerTyID: {
1096 const PointerType* PT = cast<PointerType>(Ty);
1097 const Type* ET = PT->getElementType();
1098 bool isForward = printTypeDefInternal(ET);
1099 std::string elemName(getCppName(ET));
1100 Out << "PointerType* " << typeName << " = PointerType::get("
1101 << elemName << (isForward ? "_fwd" : "") << ");\n";
1102 break;
1103 }
1104 case Type::PackedTyID: {
1105 const PackedType* PT = cast<PackedType>(Ty);
1106 const Type* ET = PT->getElementType();
1107 bool isForward = printTypeDefInternal(ET);
1108 std::string elemName(getCppName(ET));
1109 Out << "PackedType* " << typeName << " = PackedType::get("
1110 << elemName << (isForward ? "_fwd" : "")
1111 << ", " << utostr(PT->getNumElements()) << ");\n";
1112 break;
1113 }
1114 case Type::OpaqueTyID: {
1115 const OpaqueType* OT = cast<OpaqueType>(Ty);
1116 Out << "OpaqueType* " << typeName << " = OpaqueType::get();\n";
1117 break;
1118 }
1119 default:
1120 assert(!"Invalid TypeID");
1121 }
1122
1123 // Pop us off the type stack
1124 TypeStack.pop_back();
1125
1126 // We weren't a recursive type
1127 return false;
1128}
1129
1130void
1131CppWriter::printTypes(const Module* M) {
1132 // Add all of the global variables to the value table...
1133 for (Module::const_global_iterator I = TheModule->global_begin(),
1134 E = TheModule->global_end(); I != E; ++I) {
1135 if (I->hasInitializer())
1136 printTypeDef(I->getInitializer()->getType());
1137 printTypeDef(I->getType());
1138 }
1139
1140 // Add all the functions to the table
1141 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
1142 FI != FE; ++FI) {
1143 printTypeDef(FI->getReturnType());
1144 printTypeDef(FI->getFunctionType());
1145 // Add all the function arguments
1146 for(Function::const_arg_iterator AI = FI->arg_begin(),
1147 AE = FI->arg_end(); AI != AE; ++AI) {
1148 printTypeDef(AI->getType());
1149 }
1150
1151 // Add all of the basic blocks and instructions
1152 for (Function::const_iterator BB = FI->begin(),
1153 E = FI->end(); BB != E; ++BB) {
1154 printTypeDef(BB->getType());
1155 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
1156 ++I) {
1157 printTypeDef(I->getType());
1158 }
1159 }
1160 }
1161}
1162
1163void
1164CppWriter::printConstants(const Module* M) {
1165 const SymbolTable& ST = M->getSymbolTable();
1166
1167 // Print the constants, in type plane order.
1168 for (SymbolTable::plane_const_iterator PI = ST.plane_begin();
1169 PI != ST.plane_end(); ++PI ) {
1170 SymbolTable::value_const_iterator VI = ST.value_begin(PI->first);
1171 SymbolTable::value_const_iterator VE = ST.value_end(PI->first);
1172
1173 for (; VI != VE; ++VI) {
1174 const Value* V = VI->second;
1175 const Constant *CPV = dyn_cast<Constant>(V) ;
1176 if (CPV && !isa<GlobalValue>(V)) {
1177 printConstant(CPV);
1178 }
1179 }
1180 }
1181
1182 // Add all of the global variables to the value table...
1183 for (Module::const_global_iterator I = TheModule->global_begin(),
1184 E = TheModule->global_end(); I != E; ++I)
1185 if (I->hasInitializer())
1186 printConstant(I->getInitializer());
1187}
1188
1189// printSymbolTable - Run through symbol table looking for constants
1190// and types. Emit their declarations.
1191void CppWriter::printSymbolTable(const SymbolTable &ST) {
1192
1193 // Print the types.
1194 for (SymbolTable::type_const_iterator TI = ST.type_begin();
1195 TI != ST.type_end(); ++TI ) {
1196 Out << "\t" << getLLVMName(TI->first) << " = type ";
1197
1198 // Make sure we print out at least one level of the type structure, so
1199 // that we do not get %FILE = type %FILE
1200 //
1201 printTypeAtLeastOneLevel(TI->second) << "\n";
1202 }
1203
1204}
1205
1206
1207/// printConstant - Print out a constant pool entry...
1208///
1209void CppWriter::printConstant(const Constant *CV) {
1210 const int IndentSize = 2;
1211 static std::string Indent = "\n";
1212 std::string constName(getCppName(CV));
1213 std::string typeName(getCppName(CV->getType()));
1214 if (CV->isNullValue()) {
1215 Out << "Constant* " << constName << " = Constant::getNullValue("
1216 << typeName << ");\n";
1217 return;
1218 }
1219 if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
1220 Out << "Constant* " << constName << " = ConstantBool::get("
1221 << (CB == ConstantBool::True ? "true" : "false")
1222 << ");";
1223 } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV)) {
1224 Out << "Constant* " << constName << " = ConstantSInt::get("
1225 << typeName << ", " << CI->getValue() << ");";
1226 } else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV)) {
1227 Out << "Constant* " << constName << " = ConstantUInt::get("
1228 << typeName << ", " << CI->getValue() << ");";
1229 } else if (isa<ConstantAggregateZero>(CV)) {
1230 Out << "Constant* " << constName << " = ConstantAggregateZero::get("
1231 << typeName << ");";
1232 } else if (isa<ConstantPointerNull>(CV)) {
1233 Out << "Constant* " << constName << " = ConstanPointerNull::get("
1234 << typeName << ");";
1235 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1236 Out << "ConstantFP::get(" << typeName << ", ";
1237 // We would like to output the FP constant value in exponential notation,
1238 // but we cannot do this if doing so will lose precision. Check here to
1239 // make sure that we only output it in exponential format if we can parse
1240 // the value back and get the same value.
1241 //
1242 std::string StrVal = ftostr(CFP->getValue());
1243
1244 // Check to make sure that the stringized number is not some string like
1245 // "Inf" or NaN, that atof will accept, but the lexer will not. Check that
1246 // the string matches the "[-+]?[0-9]" regex.
1247 //
1248 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
1249 ((StrVal[0] == '-' || StrVal[0] == '+') &&
1250 (StrVal[1] >= '0' && StrVal[1] <= '9')))
1251 // Reparse stringized version!
1252 if (atof(StrVal.c_str()) == CFP->getValue()) {
1253 Out << StrVal;
1254 return;
1255 }
1256
1257 // Otherwise we could not reparse it to exactly the same value, so we must
1258 // output the string in hexadecimal format!
1259 assert(sizeof(double) == sizeof(uint64_t) &&
1260 "assuming that double is 64 bits!");
1261 Out << "0x" << utohexstr(DoubleToBits(CFP->getValue())) << ");";
1262 } else if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1263 if (CA->isString()) {
1264 Out << "Constant* " << constName << " = ConstantArray::get(\"";
1265 PrintEscapedString(CA->getAsString(),Out);
1266 Out << "\");";
1267 } else {
1268 Out << "std::vector<Constant*> " << constName << "_elems;\n";
1269 unsigned N = CA->getNumOperands();
1270 for (unsigned i = 0; i < N; ++i) {
1271 printConstant(CA->getOperand(i));
1272 Out << constName << "_elems.push_back("
1273 << getCppName(CA->getOperand(i)) << ");\n";
1274 }
1275 Out << "Constant* " << constName << " = ConstantArray::get("
1276 << typeName << ", " << constName << "_elems);";
1277 }
1278 } else if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
1279 Out << "std::vector<Constant*> " << constName << "_fields;\n";
1280 unsigned N = CS->getNumOperands();
1281 for (unsigned i = 0; i < N; i++) {
1282 printConstant(CS->getOperand(i));
1283 Out << constName << "_fields.push_back("
1284 << getCppName(CA->getOperand(i)) << ");\n";
1285 }
1286 Out << "Constant* " << constName << " = ConstantStruct::get("
1287 << typeName << ", " << constName << "_fields);";
1288 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(CV)) {
1289 Out << "std::vector<Constant*> " << constName << "_elems;\n";
1290 unsigned N = CP->getNumOperands();
1291 for (unsigned i = 0; i < N; ++i) {
1292 printConstant(CP->getOperand(i));
1293 Out << constName << "_elems.push_back("
1294 << getCppName(CP->getOperand(i)) << ");\n";
1295 }
1296 Out << "Constant* " << constName << " = ConstantPacked::get("
1297 << typeName << ", " << constName << "_elems);";
1298 } else if (isa<UndefValue>(CV)) {
1299 Out << "Constant* " << constName << " = UndefValue::get("
1300 << typeName << ");\n";
1301 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1302 Out << CE->getOpcodeName() << " (";
1303
1304 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1305 //printTypeInt(Out, (*OI)->getType(), TypeTable);
1306 //WriteAsOperandInternal(Out, *OI, PrintName, TypeTable, Machine);
1307 if (OI+1 != CE->op_end())
1308 Out << ", ";
1309 }
1310
1311 if (CE->getOpcode() == Instruction::Cast) {
1312 Out << " to ";
1313 // printTypeInt(Out, CE->getType(), TypeTable);
1314 }
1315 Out << ')';
1316
1317 } else {
1318 Out << "<placeholder or erroneous Constant>";
1319 }
1320 Out << "\n";
1321}
1322
1323/// printFunction - Print all aspects of a function.
1324///
1325void CppWriter::printFunction(const Function *F) {
1326 std::string funcTypeName(getCppName(F->getFunctionType()));
1327
1328 Out << "Function* ";
1329 printCppName(F);
1330 Out << " = new Function(" << funcTypeName << ", " ;
1331 printLinkageType(F->getLinkage());
1332 Out << ", \"" << F->getName() << "\", mod);\n";
1333 printCppName(F);
1334 Out << "->setCallingConv(";
1335 printCallingConv(F->getCallingConv());
1336 Out << ");\n";
1337 if (F->hasSection()) {
1338 printCppName(F);
1339 Out << "->setSection(" << F->getSection() << ");\n";
1340 }
1341 if (F->getAlignment()) {
1342 printCppName(F);
1343 Out << "->setAlignment(" << F->getAlignment() << ");\n";
1344 }
1345
1346 Machine.incorporateFunction(F);
1347
1348 if (!F->isExternal()) {
1349 Out << "{";
1350 // Output all of its basic blocks... for the function
1351 for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
1352 printBasicBlock(I);
1353 Out << "}\n";
1354 }
1355
1356 Machine.purgeFunction();
1357}
1358
1359/// printArgument - This member is called for every argument that is passed into
1360/// the function. Simply print it out
1361///
1362void CppWriter::printArgument(const Argument *Arg) {
1363 // Insert commas as we go... the first arg doesn't get a comma
1364 if (Arg != Arg->getParent()->arg_begin()) Out << ", ";
1365
1366 // Output type...
1367 printType(Arg->getType());
1368
1369 // Output name, if available...
1370 if (Arg->hasName())
1371 Out << ' ' << getLLVMName(Arg->getName());
1372}
1373
1374/// printBasicBlock - This member is called for each basic block in a method.
1375///
1376void CppWriter::printBasicBlock(const BasicBlock *BB) {
1377 if (BB->hasName()) { // Print out the label if it exists...
1378 Out << "\n" << getLLVMName(BB->getName(), false) << ':';
1379 } else if (!BB->use_empty()) { // Don't print block # of no uses...
1380 Out << "\n; <label>:";
1381 int Slot = Machine.getSlot(BB);
1382 if (Slot != -1)
1383 Out << Slot;
1384 else
1385 Out << "<badref>";
1386 }
1387
1388 if (BB->getParent() == 0)
1389 Out << "\t\t; Error: Block without parent!";
1390 else {
1391 if (BB != &BB->getParent()->front()) { // Not the entry block?
1392 // Output predecessors for the block...
1393 Out << "\t\t;";
1394 pred_const_iterator PI = pred_begin(BB), PE = pred_end(BB);
1395
1396 if (PI == PE) {
1397 Out << " No predecessors!";
1398 } else {
1399 Out << " preds =";
1400 writeOperand(*PI, false, true);
1401 for (++PI; PI != PE; ++PI) {
1402 Out << ',';
1403 writeOperand(*PI, false, true);
1404 }
1405 }
1406 }
1407 }
1408
1409 Out << "\n";
1410
1411 // Output all of the instructions in the basic block...
1412 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1413 printInstruction(*I);
1414}
1415
1416
1417/// printInfoComment - Print a little comment after the instruction indicating
1418/// which slot it occupies.
1419///
1420void CppWriter::printInfoComment(const Value &V) {
1421 if (V.getType() != Type::VoidTy) {
1422 Out << "\t\t; <";
1423 printType(V.getType()) << '>';
1424
1425 if (!V.hasName()) {
1426 int SlotNum = Machine.getSlot(&V);
1427 if (SlotNum == -1)
1428 Out << ":<badref>";
1429 else
1430 Out << ':' << SlotNum; // Print out the def slot taken.
1431 }
1432 Out << " [#uses=" << V.getNumUses() << ']'; // Output # uses
1433 }
1434}
1435
1436/// printInstruction - This member is called for each Instruction in a function..
1437///
1438void CppWriter::printInstruction(const Instruction &I) {
1439 Out << "\t";
1440
1441 // Print out name if it exists...
1442 if (I.hasName())
1443 Out << getLLVMName(I.getName()) << " = ";
1444
1445 // If this is a volatile load or store, print out the volatile marker.
1446 if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
1447 (isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile())) {
1448 Out << "volatile ";
1449 } else if (isa<CallInst>(I) && cast<CallInst>(I).isTailCall()) {
1450 // If this is a call, check if it's a tail call.
1451 Out << "tail ";
1452 }
1453
1454 // Print out the opcode...
1455 Out << I.getOpcodeName();
1456
1457 // Print out the type of the operands...
1458 const Value *Operand = I.getNumOperands() ? I.getOperand(0) : 0;
1459
1460 // Special case conditional branches to swizzle the condition out to the front
1461 if (isa<BranchInst>(I) && I.getNumOperands() > 1) {
1462 writeOperand(I.getOperand(2), true);
1463 Out << ',';
1464 writeOperand(Operand, true);
1465 Out << ',';
1466 writeOperand(I.getOperand(1), true);
1467
1468 } else if (isa<SwitchInst>(I)) {
1469 // Special case switch statement to get formatting nice and correct...
1470 writeOperand(Operand , true); Out << ',';
1471 writeOperand(I.getOperand(1), true); Out << " [";
1472
1473 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; op += 2) {
1474 Out << "\n\t\t";
1475 writeOperand(I.getOperand(op ), true); Out << ',';
1476 writeOperand(I.getOperand(op+1), true);
1477 }
1478 Out << "\n\t]";
1479 } else if (isa<PHINode>(I)) {
1480 Out << ' ';
1481 printType(I.getType());
1482 Out << ' ';
1483
1484 for (unsigned op = 0, Eop = I.getNumOperands(); op < Eop; op += 2) {
1485 if (op) Out << ", ";
1486 Out << '[';
1487 writeOperand(I.getOperand(op ), false); Out << ',';
1488 writeOperand(I.getOperand(op+1), false); Out << " ]";
1489 }
1490 } else if (isa<ReturnInst>(I) && !Operand) {
1491 Out << " void";
1492 } else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
1493 // Print the calling convention being used.
1494 switch (CI->getCallingConv()) {
1495 case CallingConv::C: break; // default
1496 case CallingConv::CSRet: Out << " csretcc"; break;
1497 case CallingConv::Fast: Out << " fastcc"; break;
1498 case CallingConv::Cold: Out << " coldcc"; break;
1499 default: Out << " cc" << CI->getCallingConv(); break;
1500 }
1501
1502 const PointerType *PTy = cast<PointerType>(Operand->getType());
1503 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1504 const Type *RetTy = FTy->getReturnType();
1505
1506 // If possible, print out the short form of the call instruction. We can
1507 // only do this if the first argument is a pointer to a nonvararg function,
1508 // and if the return type is not a pointer to a function.
1509 //
1510 if (!FTy->isVarArg() &&
1511 (!isa<PointerType>(RetTy) ||
1512 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1513 Out << ' '; printType(RetTy);
1514 writeOperand(Operand, false);
1515 } else {
1516 writeOperand(Operand, true);
1517 }
1518 Out << '(';
1519 if (CI->getNumOperands() > 1) writeOperand(CI->getOperand(1), true);
1520 for (unsigned op = 2, Eop = I.getNumOperands(); op < Eop; ++op) {
1521 Out << ',';
1522 writeOperand(I.getOperand(op), true);
1523 }
1524
1525 Out << " )";
1526 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
1527 const PointerType *PTy = cast<PointerType>(Operand->getType());
1528 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1529 const Type *RetTy = FTy->getReturnType();
1530
1531 // Print the calling convention being used.
1532 switch (II->getCallingConv()) {
1533 case CallingConv::C: break; // default
1534 case CallingConv::CSRet: Out << " csretcc"; break;
1535 case CallingConv::Fast: Out << " fastcc"; break;
1536 case CallingConv::Cold: Out << " coldcc"; break;
1537 default: Out << " cc" << II->getCallingConv(); break;
1538 }
1539
1540 // If possible, print out the short form of the invoke instruction. We can
1541 // only do this if the first argument is a pointer to a nonvararg function,
1542 // and if the return type is not a pointer to a function.
1543 //
1544 if (!FTy->isVarArg() &&
1545 (!isa<PointerType>(RetTy) ||
1546 !isa<FunctionType>(cast<PointerType>(RetTy)->getElementType()))) {
1547 Out << ' '; printType(RetTy);
1548 writeOperand(Operand, false);
1549 } else {
1550 writeOperand(Operand, true);
1551 }
1552
1553 Out << '(';
1554 if (I.getNumOperands() > 3) writeOperand(I.getOperand(3), true);
1555 for (unsigned op = 4, Eop = I.getNumOperands(); op < Eop; ++op) {
1556 Out << ',';
1557 writeOperand(I.getOperand(op), true);
1558 }
1559
1560 Out << " )\n\t\t\tto";
1561 writeOperand(II->getNormalDest(), true);
1562 Out << " unwind";
1563 writeOperand(II->getUnwindDest(), true);
1564
1565 } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(&I)) {
1566 Out << ' ';
1567 printType(AI->getType()->getElementType());
1568 if (AI->isArrayAllocation()) {
1569 Out << ',';
1570 writeOperand(AI->getArraySize(), true);
1571 }
1572 if (AI->getAlignment()) {
1573 Out << ", align " << AI->getAlignment();
1574 }
1575 } else if (isa<CastInst>(I)) {
1576 if (Operand) writeOperand(Operand, true); // Work with broken code
1577 Out << " to ";
1578 printType(I.getType());
1579 } else if (isa<VAArgInst>(I)) {
1580 if (Operand) writeOperand(Operand, true); // Work with broken code
1581 Out << ", ";
1582 printType(I.getType());
1583 } else if (Operand) { // Print the normal way...
1584
1585 // PrintAllTypes - Instructions who have operands of all the same type
1586 // omit the type from all but the first operand. If the instruction has
1587 // different type operands (for example br), then they are all printed.
1588 bool PrintAllTypes = false;
1589 const Type *TheType = Operand->getType();
1590
1591 // Shift Left & Right print both types even for Ubyte LHS, and select prints
1592 // types even if all operands are bools.
1593 if (isa<ShiftInst>(I) || isa<SelectInst>(I) || isa<StoreInst>(I) ||
1594 isa<ShuffleVectorInst>(I)) {
1595 PrintAllTypes = true;
1596 } else {
1597 for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
1598 Operand = I.getOperand(i);
1599 if (Operand->getType() != TheType) {
1600 PrintAllTypes = true; // We have differing types! Print them all!
1601 break;
1602 }
1603 }
1604 }
1605
1606 if (!PrintAllTypes) {
1607 Out << ' ';
1608 printType(TheType);
1609 }
1610
1611 for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
1612 if (i) Out << ',';
1613 writeOperand(I.getOperand(i), PrintAllTypes);
1614 }
1615 }
1616
1617 printInfoComment(I);
1618 Out << "\n";
1619}
1620
1621
1622//===----------------------------------------------------------------------===//
1623// External Interface declarations
1624//===----------------------------------------------------------------------===//
1625
1626
1627//===----------------------------------------------------------------------===//
1628//===-- SlotMachine Implementation
1629//===----------------------------------------------------------------------===//
1630
1631#if 0
1632#define SC_DEBUG(X) std::cerr << X
1633#else
1634#define SC_DEBUG(X)
1635#endif
1636
1637// Module level constructor. Causes the contents of the Module (sans functions)
1638// to be added to the slot table.
1639SlotMachine::SlotMachine(const Module *M)
1640 : TheModule(M) ///< Saved for lazy initialization.
1641 , mMap()
1642 , mTypes()
1643 , fMap()
1644 , fTypes()
1645{
1646 assert(M != 0 && "Invalid Module");
1647 processModule();
1648}
1649
1650// Iterate through all the global variables, functions, and global
1651// variable initializers and create slots for them.
1652void SlotMachine::processModule() {
1653 // Add all of the global variables to the value table...
1654 for (Module::const_global_iterator I = TheModule->global_begin(), E = TheModule->global_end();
1655 I != E; ++I)
1656 createSlot(I);
1657
1658 // Add all the functions to the table
1659 for (Module::const_iterator FI = TheModule->begin(), FE = TheModule->end();
1660 FI != FE; ++FI) {
1661 createSlot(FI);
1662 // Add all the function arguments
1663 for(Function::const_arg_iterator AI = FI->arg_begin(),
1664 AE = FI->arg_end(); AI != AE; ++AI)
1665 createSlot(AI);
1666
1667 // Add all of the basic blocks and instructions
1668 for (Function::const_iterator BB = FI->begin(),
1669 E = FI->end(); BB != E; ++BB) {
1670 createSlot(BB);
1671 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;
1672 ++I) {
1673 createSlot(I);
1674 }
1675 }
1676 }
1677}
1678
1679// Process the arguments, basic blocks, and instructions of a function.
1680void SlotMachine::processFunction() {
1681
1682}
1683
1684// Clean up after incorporating a function. This is the only way
1685// to get out of the function incorporation state that affects the
1686// getSlot/createSlot lock. Function incorporation state is indicated
1687// by TheFunction != 0.
1688void SlotMachine::purgeFunction() {
1689 SC_DEBUG("begin purgeFunction!\n");
1690 fMap.clear(); // Simply discard the function level map
1691 fTypes.clear();
1692 TheFunction = 0;
1693 FunctionProcessed = false;
1694 SC_DEBUG("end purgeFunction!\n");
1695}
1696
1697/// Get the slot number for a value. This function will assert if you
1698/// ask for a Value that hasn't previously been inserted with createSlot.
1699/// Types are forbidden because Type does not inherit from Value (any more).
1700int SlotMachine::getSlot(const Value *V) {
1701 assert( V && "Can't get slot for null Value" );
1702 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1703 "Can't insert a non-GlobalValue Constant into SlotMachine");
1704
1705 // Get the type of the value
1706 const Type* VTy = V->getType();
1707
1708 // Find the type plane in the module map
1709 TypedPlanes::const_iterator MI = mMap.find(VTy);
1710
1711 if ( TheFunction ) {
1712 // Lookup the type in the function map too
1713 TypedPlanes::const_iterator FI = fMap.find(VTy);
1714 // If there is a corresponding type plane in the function map
1715 if ( FI != fMap.end() ) {
1716 // Lookup the Value in the function map
1717 ValueMap::const_iterator FVI = FI->second.map.find(V);
1718 // If the value doesn't exist in the function map
1719 if ( FVI == FI->second.map.end() ) {
1720 // Look up the value in the module map.
1721 if (MI == mMap.end()) return -1;
1722 ValueMap::const_iterator MVI = MI->second.map.find(V);
1723 // If we didn't find it, it wasn't inserted
1724 if (MVI == MI->second.map.end()) return -1;
1725 assert( MVI != MI->second.map.end() && "Value not found");
1726 // We found it only at the module level
1727 return MVI->second;
1728
1729 // else the value exists in the function map
1730 } else {
1731 // Return the slot number as the module's contribution to
1732 // the type plane plus the index in the function's contribution
1733 // to the type plane.
1734 if (MI != mMap.end())
1735 return MI->second.next_slot + FVI->second;
1736 else
1737 return FVI->second;
1738 }
1739 }
1740 }
1741
1742 // N.B. Can get here only if either !TheFunction or the function doesn't
1743 // have a corresponding type plane for the Value
1744
1745 // Make sure the type plane exists
1746 if (MI == mMap.end()) return -1;
1747 // Lookup the value in the module's map
1748 ValueMap::const_iterator MVI = MI->second.map.find(V);
1749 // Make sure we found it.
1750 if (MVI == MI->second.map.end()) return -1;
1751 // Return it.
1752 return MVI->second;
1753}
1754
1755/// Get the slot number for a type. This function will assert if you
1756/// ask for a Type that hasn't previously been inserted with createSlot.
1757int SlotMachine::getSlot(const Type *Ty) {
1758 assert( Ty && "Can't get slot for null Type" );
1759
1760 if ( TheFunction ) {
1761 // Lookup the Type in the function map
1762 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1763 // If the Type doesn't exist in the function map
1764 if ( FTI == fTypes.map.end() ) {
1765 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1766 // If we didn't find it, it wasn't inserted
1767 if (MTI == mTypes.map.end())
1768 return -1;
1769 // We found it only at the module level
1770 return MTI->second;
1771
1772 // else the value exists in the function map
1773 } else {
1774 // Return the slot number as the module's contribution to
1775 // the type plane plus the index in the function's contribution
1776 // to the type plane.
1777 return mTypes.next_slot + FTI->second;
1778 }
1779 }
1780
1781 // N.B. Can get here only if !TheFunction
1782
1783 // Lookup the value in the module's map
1784 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1785 // Make sure we found it.
1786 if (MTI == mTypes.map.end()) return -1;
1787 // Return it.
1788 return MTI->second;
1789}
1790
1791// Create a new slot, or return the existing slot if it is already
1792// inserted. Note that the logic here parallels getSlot but instead
1793// of asserting when the Value* isn't found, it inserts the value.
1794unsigned SlotMachine::createSlot(const Value *V) {
1795 assert( V && "Can't insert a null Value to SlotMachine");
1796 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1797 "Can't insert a non-GlobalValue Constant into SlotMachine");
1798
1799 const Type* VTy = V->getType();
1800
1801 // Just ignore void typed things
1802 if (VTy == Type::VoidTy) return 0; // FIXME: Wrong return value!
1803
1804 // Look up the type plane for the Value's type from the module map
1805 TypedPlanes::const_iterator MI = mMap.find(VTy);
1806
1807 if ( TheFunction ) {
1808 // Get the type plane for the Value's type from the function map
1809 TypedPlanes::const_iterator FI = fMap.find(VTy);
1810 // If there is a corresponding type plane in the function map
1811 if ( FI != fMap.end() ) {
1812 // Lookup the Value in the function map
1813 ValueMap::const_iterator FVI = FI->second.map.find(V);
1814 // If the value doesn't exist in the function map
1815 if ( FVI == FI->second.map.end() ) {
1816 // If there is no corresponding type plane in the module map
1817 if ( MI == mMap.end() )
1818 return insertValue(V);
1819 // Look up the value in the module map
1820 ValueMap::const_iterator MVI = MI->second.map.find(V);
1821 // If we didn't find it, it wasn't inserted
1822 if ( MVI == MI->second.map.end() )
1823 return insertValue(V);
1824 else
1825 // We found it only at the module level
1826 return MVI->second;
1827
1828 // else the value exists in the function map
1829 } else {
1830 if ( MI == mMap.end() )
1831 return FVI->second;
1832 else
1833 // Return the slot number as the module's contribution to
1834 // the type plane plus the index in the function's contribution
1835 // to the type plane.
1836 return MI->second.next_slot + FVI->second;
1837 }
1838
1839 // else there is not a corresponding type plane in the function map
1840 } else {
1841 // If the type plane doesn't exists at the module level
1842 if ( MI == mMap.end() ) {
1843 return insertValue(V);
1844 // else type plane exists at the module level, examine it
1845 } else {
1846 // Look up the value in the module's map
1847 ValueMap::const_iterator MVI = MI->second.map.find(V);
1848 // If we didn't find it there either
1849 if ( MVI == MI->second.map.end() )
1850 // Return the slot number as the module's contribution to
1851 // the type plane plus the index of the function map insertion.
1852 return MI->second.next_slot + insertValue(V);
1853 else
1854 return MVI->second;
1855 }
1856 }
1857 }
1858
1859 // N.B. Can only get here if !TheFunction
1860
1861 // If the module map's type plane is not for the Value's type
1862 if ( MI != mMap.end() ) {
1863 // Lookup the value in the module's map
1864 ValueMap::const_iterator MVI = MI->second.map.find(V);
1865 if ( MVI != MI->second.map.end() )
1866 return MVI->second;
1867 }
1868
1869 return insertValue(V);
1870}
1871
1872// Create a new slot, or return the existing slot if it is already
1873// inserted. Note that the logic here parallels getSlot but instead
1874// of asserting when the Value* isn't found, it inserts the value.
1875unsigned SlotMachine::createSlot(const Type *Ty) {
1876 assert( Ty && "Can't insert a null Type to SlotMachine");
1877
1878 if ( TheFunction ) {
1879 // Lookup the Type in the function map
1880 TypeMap::const_iterator FTI = fTypes.map.find(Ty);
1881 // If the type doesn't exist in the function map
1882 if ( FTI == fTypes.map.end() ) {
1883 // Look up the type in the module map
1884 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1885 // If we didn't find it, it wasn't inserted
1886 if ( MTI == mTypes.map.end() )
1887 return insertValue(Ty);
1888 else
1889 // We found it only at the module level
1890 return MTI->second;
1891
1892 // else the value exists in the function map
1893 } else {
1894 // Return the slot number as the module's contribution to
1895 // the type plane plus the index in the function's contribution
1896 // to the type plane.
1897 return mTypes.next_slot + FTI->second;
1898 }
1899 }
1900
1901 // N.B. Can only get here if !TheFunction
1902
1903 // Lookup the type in the module's map
1904 TypeMap::const_iterator MTI = mTypes.map.find(Ty);
1905 if ( MTI != mTypes.map.end() )
1906 return MTI->second;
1907
1908 return insertValue(Ty);
1909}
1910
1911// Low level insert function. Minimal checking is done. This
1912// function is just for the convenience of createSlot (above).
1913unsigned SlotMachine::insertValue(const Value *V ) {
1914 assert(V && "Can't insert a null Value into SlotMachine!");
1915 assert(!isa<Constant>(V) || isa<GlobalValue>(V) &&
1916 "Can't insert a non-GlobalValue Constant into SlotMachine");
1917
1918 // If this value does not contribute to a plane (is void)
1919 // or if the value already has a name then ignore it.
1920 if (V->getType() == Type::VoidTy || V->hasName() ) {
1921 SC_DEBUG("ignored value " << *V << "\n");
1922 return 0; // FIXME: Wrong return value
1923 }
1924
1925 const Type *VTy = V->getType();
1926 unsigned DestSlot = 0;
1927
1928 if ( TheFunction ) {
1929 TypedPlanes::iterator I = fMap.find( VTy );
1930 if ( I == fMap.end() )
1931 I = fMap.insert(std::make_pair(VTy,ValuePlane())).first;
1932 DestSlot = I->second.map[V] = I->second.next_slot++;
1933 } else {
1934 TypedPlanes::iterator I = mMap.find( VTy );
1935 if ( I == mMap.end() )
1936 I = mMap.insert(std::make_pair(VTy,ValuePlane())).first;
1937 DestSlot = I->second.map[V] = I->second.next_slot++;
1938 }
1939
1940 SC_DEBUG(" Inserting value [" << VTy << "] = " << V << " slot=" <<
1941 DestSlot << " [");
1942 // G = Global, C = Constant, T = Type, F = Function, o = other
1943 SC_DEBUG((isa<GlobalVariable>(V) ? 'G' : (isa<Function>(V) ? 'F' :
1944 (isa<Constant>(V) ? 'C' : 'o'))));
1945 SC_DEBUG("]\n");
1946 return DestSlot;
1947}
1948
1949// Low level insert function. Minimal checking is done. This
1950// function is just for the convenience of createSlot (above).
1951unsigned SlotMachine::insertValue(const Type *Ty ) {
1952 assert(Ty && "Can't insert a null Type into SlotMachine!");
1953
1954 unsigned DestSlot = fTypes.map[Ty] = fTypes.next_slot++;
1955 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n");
1956 return DestSlot;
1957}
1958
1959} // end anonymous llvm
1960
1961namespace llvm {
1962
1963void WriteModuleToCppFile(Module* mod, std::ostream& o) {
1964 o << "#include <llvm/Module.h>\n";
1965 o << "#include <llvm/DerivedTypes.h>\n";
1966 o << "#include <llvm/Constants.h>\n";
1967 o << "#include <llvm/GlobalVariable.h>\n";
1968 o << "#include <llvm/Function.h>\n";
1969 o << "#include <llvm/CallingConv.h>\n";
1970 o << "#include <llvm/BasicBlock.h>\n";
1971 o << "#include <llvm/Instructions.h>\n";
1972 o << "#include <llvm/Pass.h>\n";
1973 o << "#include <llvm/PassManager.h>\n";
1974 o << "#include <llvm/Analysis/Verifier.h>\n";
1975 o << "#include <llvm/Assembly/PrintModulePass.h>\n";
1976 o << "#include <algorithm>\n";
1977 o << "#include <iostream>\n\n";
1978 o << "using namespace llvm;\n\n";
1979 o << "Module* makeLLVMModule();\n\n";
1980 o << "int main(int argc, char**argv) {\n";
1981 o << " Module* Mod = makeLLVMModule();\n";
1982 o << " verifyModule(*Mod, PrintMessageAction);\n";
1983 o << " PassManager PM;\n";
1984 o << " PM.add(new PrintModulePass(&std::cout));\n";
1985 o << " PM.run(*Mod);\n";
1986 o << " return 0;\n";
1987 o << "}\n\n";
1988 o << "Module* makeLLVMModule() {\n";
1989 SlotMachine SlotTable(mod);
1990 CppWriter W(o, SlotTable, mod);
1991 W.write(mod);
1992 o << "}\n";
1993}
1994
1995}