13cc8d90af671490c86eafac7737a5b27cde072d
[oota-llvm.git] / lib / Transforms / IPO / DeadTypeElimination.cpp
1 //===- CleanupGCCOutput.cpp - Cleanup GCC Output ----------------------------=//
2 //
3 // This pass is used to cleanup the output of GCC.  GCC's output is
4 // unneccessarily gross for a couple of reasons. This pass does the following
5 // things to try to clean it up:
6 //
7 // * Eliminate names for GCC types that we know can't be needed by the user.
8 // - Eliminate names for types that are unused in the entire translation unit
9 //    but only if they do not name a structure type!
10 // - Replace calls to 'sbyte *%malloc(uint)' and 'void %free(sbyte *)' with
11 //   malloc and free instructions.
12 //
13 // Note:  This code produces dead declarations, it is a good idea to run DCE
14 //        after this pass.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/CleanupGCCOutput.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/iOther.h"
22 #include "llvm/iMemory.h"
23 #include <map>
24 #include <algorithm>
25
26 static const Type *PtrArrSByte = 0; // '[sbyte]*' type
27 static const Type *PtrSByte = 0;    // 'sbyte*' type
28
29
30 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
31 // with a value, then remove and delete the original instruction.
32 //
33 static void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
34                                  BasicBlock::iterator &BI, Value *V) {
35   Instruction *I = *BI;
36   // Replaces all of the uses of the instruction with uses of the value
37   I->replaceAllUsesWith(V);
38
39   // Remove the unneccesary instruction now...
40   BIL.remove(BI);
41
42   // Make sure to propogate a name if there is one already...
43   if (I->hasName() && !V->hasName())
44     V->setName(I->getName(), BIL.getParent()->getSymbolTable());
45
46   // Remove the dead instruction now...
47   delete I;
48 }
49
50
51 // ReplaceInstWithInst - Replace the instruction specified by BI with the
52 // instruction specified by I.  The original instruction is deleted and BI is
53 // updated to point to the new instruction.
54 //
55 static void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
56                                 BasicBlock::iterator &BI, Instruction *I) {
57   assert(I->getParent() == 0 &&
58          "ReplaceInstWithInst: Instruction already inserted into basic block!");
59
60   // Insert the new instruction into the basic block...
61   BI = BIL.insert(BI, I)+1;
62
63   // Replace all uses of the old instruction, and delete it.
64   ReplaceInstWithValue(BIL, BI, I);
65
66   // Reexamine the instruction just inserted next time around the cleanup pass
67   // loop.
68   --BI;
69 }
70
71
72
73 // ConvertCallTo - Convert a call to a varargs function with no arg types
74 // specified to a concrete nonvarargs method.
75 //
76 static void ConvertCallTo(CallInst *CI, Method *Dest) {
77   const MethodType::ParamTypes &ParamTys =
78     Dest->getMethodType()->getParamTypes();
79   BasicBlock *BB = CI->getParent();
80
81   // Get an iterator to where we want to insert cast instructions if the
82   // argument types don't agree.
83   //
84   BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
85   assert(BBI != BB->end() && "CallInst not in parent block?");
86
87   assert(CI->getNumOperands()-1 == ParamTys.size()&&
88          "Method calls resolved funny somehow, incompatible number of args");
89
90   vector<Value*> Params;
91
92   // Convert all of the call arguments over... inserting cast instructions if
93   // the types are not compatible.
94   for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
95     Value *V = CI->getOperand(i);
96
97     if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
98       Instruction *Cast = new CastInst(V, ParamTys[i-1]);
99       BBI = BB->getInstList().insert(BBI, Cast)+1;
100       V = Cast;
101     }
102
103     Params.push_back(V);
104   }
105
106   // Replace the old call instruction with a new call instruction that calls
107   // the real method.
108   //
109   ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
110 }
111
112
113 // PatchUpMethodReferences - Go over the methods that are in the module and
114 // look for methods that have the same name.  More often than not, there will
115 // be things like:
116 //    void "foo"(...)
117 //    void "foo"(int, int)
118 // because of the way things are declared in C.  If this is the case, patch
119 // things up.
120 //
121 static bool PatchUpMethodReferences(SymbolTable *ST) {
122   map<string, vector<Method*> > Methods;
123
124   // Loop over the entries in the symbol table. If an entry is a method pointer,
125   // then add it to the Methods map.  We do a two pass algorithm here to avoid
126   // problems with iterators getting invalidated if we did a one pass scheme.
127   //
128   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
129     if (const PointerType *PT = dyn_cast<PointerType>(I->first))
130       if (const MethodType *MT = dyn_cast<MethodType>(PT->getValueType())) {
131         SymbolTable::VarMap &Plane = I->second;
132         for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
133              PI != PE; ++PI) {
134           const string &Name = PI->first;
135           Method *M = cast<Method>(PI->second);
136           Methods[Name].push_back(M);          
137         }
138       }
139
140   bool Changed = false;
141
142   // Now we have a list of all methods with a particular name.  If there is more
143   // than one entry in a list, merge the methods together.
144   //
145   for (map<string, vector<Method*> >::iterator I = Methods.begin(), 
146          E = Methods.end(); I != E; ++I) {
147     vector<Method*> &Methods = I->second;
148     if (Methods.size() > 1) {         // Found a multiply defined method.
149       Method *Implementation = 0;     // Find the implementation
150       Method *Concrete = 0;
151       for (unsigned i = 0; i < Methods.size(); ++i) {
152         if (!Methods[i]->isExternal()) {  // Found an implementation
153           assert(Implementation == 0 && "Multiple definitions of the same"
154                  " method. Case not handled yet!");
155           Implementation = Methods[i];
156         }
157
158         if (!Methods[i]->getMethodType()->isVarArg() ||
159             Methods[i]->getMethodType()->getParamTypes().size()) {
160           if (Concrete) {  // Found two different methods types.  Can't choose
161             Concrete = 0;
162             break;
163           }
164           Concrete = Methods[i];
165         }
166       }
167
168       // We should find exactly one non-vararg method definition, which is
169       // probably the implementation.  Change all of the method definitions
170       // and uses to use it instead.
171       //
172       if (!Concrete) {
173         cerr << "Warning: Found methods types that are not compatible:\n";
174         for (unsigned i = 0; i < Methods.size(); ++i) {
175           cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
176                << Methods[i]->getName() << endl;
177         }
178         cerr << "  No linkage of methods named '" << Methods[0]->getName()
179              << "' performed!\n";
180       } else {
181         for (unsigned i = 0; i < Methods.size(); ++i)
182           if (Methods[i] != Concrete) {
183             Method *Old = Methods[i];
184             assert(Old->getReturnType() == Concrete->getReturnType() &&
185                    "Differing return types not handled yet!");
186             assert(Old->getMethodType()->getParamTypes().size() == 0 &&
187                    "Cannot handle varargs fn's with specified element types!");
188             
189             // Attempt to convert all of the uses of the old method to the
190             // concrete form of the method.  If there is a use of the method
191             // that we don't understand here we punt to avoid making a bad
192             // transformation.
193             //
194             // At this point, we know that the return values are the same for
195             // our two functions and that the Old method has no varargs methods
196             // specified.  In otherwords it's just <retty> (...)
197             //
198             for (unsigned i = 0; i < Old->use_size(); ) {
199               User *U = *(Old->use_begin()+i);
200               if (CastInst *CI = dyn_cast<CastInst>(U)) {
201                 // Convert casts directly
202                 assert(CI->getOperand(0) == Old);
203                 CI->setOperand(0, Concrete);
204                 Changed = true;
205               } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
206                 // Can only fix up calls TO the argument, not args passed in.
207                 if (CI->getCalledValue() == Old) {
208                   ConvertCallTo(CI, Concrete);
209                   Changed = true;
210                 } else {
211                   cerr << "Couldn't cleanup this function call, must be an"
212                        << " argument or something!" << CI;
213                   ++i;
214                 }
215               } else {
216                 cerr << "Cannot convert use of method: " << U << endl;
217                 ++i;
218               }
219             }
220           }
221         }
222     }
223   }
224
225   return Changed;
226 }
227
228
229 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
230 // should be eliminated.
231 //
232 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
233   // Nuke all names for primitive types!
234   if (cast<Type>(E.second)->isPrimitiveType()) return true;
235
236   // The only types that could contain .'s in the program are things generated
237   // by GCC itself, including "complex.float" and friends.  Nuke them too.
238   if (E.first.find('.') != string::npos) return true;
239
240   return false;
241 }
242
243 // doPassInitialization - For this pass, it removes global symbol table
244 // entries for primitive types.  These are never used for linking in GCC and
245 // they make the output uglier to look at, so we nuke them.
246 //
247 bool CleanupGCCOutput::doPassInitialization(Module *M) {
248   bool Changed = false;
249
250   if (PtrArrSByte == 0) {
251     PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
252     PtrSByte    = PointerType::get(Type::SByteTy);
253   }
254
255   if (M->hasSymbolTable()) {
256     SymbolTable *ST = M->getSymbolTable();
257
258     // Go over the methods that are in the module and look for methods that have
259     // the same name.  More often than not, there will be things like:
260     // void "foo"(...)  and void "foo"(int, int) because of the way things are
261     // declared in C.  If this is the case, patch things up.
262     //
263     Changed |= PatchUpMethodReferences(ST);
264
265
266     // If the module has a symbol table, they might be referring to the malloc
267     // and free functions.  If this is the case, grab the method pointers that 
268     // the module is using.
269     //
270     // Lookup %malloc and %free in the symbol table, for later use.  If they
271     // don't exist, or are not external, we do not worry about converting calls
272     // to that function into the appropriate instruction.
273     //
274     const PointerType *MallocType =   // Get the type for malloc
275       PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
276                                   vector<const Type*>(1, Type::UIntTy), false));
277     Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
278     if (Malloc && !Malloc->isExternal())
279       Malloc = 0;  // Don't mess with locally defined versions of the fn
280
281     const PointerType *FreeType =     // Get the type for free
282       PointerType::get(MethodType::get(Type::VoidTy,
283                vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
284     Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
285     if (Free && !Free->isExternal())
286       Free = 0;  // Don't mess with locally defined versions of the fn
287     
288
289     // Check the symbol table for superfluous type entries...
290     //
291     // Grab the 'type' plane of the module symbol...
292     SymbolTable::iterator STI = ST->find(Type::TypeTy);
293     if (STI != ST->end()) {
294       // Loop over all entries in the type plane...
295       SymbolTable::VarMap &Plane = STI->second;
296       for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
297         if (ShouldNukeSymtabEntry(*PI)) {    // Should we remove this entry?
298 #if MAP_IS_NOT_BRAINDEAD
299           PI = Plane.erase(PI);     // STD C++ Map should support this!
300 #else
301           Plane.erase(PI);          // Alas, GCC 2.95.3 doesn't  *SIGH*
302           PI = Plane.begin();
303 #endif
304           Changed = true;
305         } else {
306           ++PI;
307         }
308     }
309   }
310
311   return Changed;
312 }
313
314
315 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
316 //
317 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
318   bool Changed = false;
319   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
320     BasicBlock *BB = *MI;
321     BasicBlock::InstListType &BIL = BB->getInstList();
322
323     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
324       Instruction *I = *BI;
325
326       if (CallInst *CI = dyn_cast<CallInst>(I)) {
327         if (CI->getCalledValue() == Malloc) {      // Replace call to malloc?
328           MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
329                                                CI->getName());
330           CI->setName("");
331           BI = BIL.insert(BI, MallocI)+1;
332           ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
333           Changed = true;
334           continue;  // Skip the ++BI
335         } else if (CI->getCalledValue() == Free) { // Replace call to free?
336           ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
337           Changed = true;
338           continue;  // Skip the ++BI
339         }
340       }
341
342       ++BI;
343     }
344   }
345
346   return Changed;
347 }
348
349
350
351
352 // doPerMethodWork - This method simplifies the specified method hopefully.
353 //
354 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
355   bool Changed = false;
356   while (doOneCleanupPass(M)) Changed = true;
357   return Changed;
358 }