c83eba36110a1dc87a529b1b6bf242a9f9523b16
[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 bool CleanupGCCOutput::PatchUpMethodReferences(Module *M) {
122   SymbolTable *ST = M->getSymbolTable();
123   if (!ST) return false;
124
125   map<string, vector<Method*> > Methods;
126
127   // Loop over the entries in the symbol table. If an entry is a method pointer,
128   // then add it to the Methods map.  We do a two pass algorithm here to avoid
129   // problems with iterators getting invalidated if we did a one pass scheme.
130   //
131   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
132     if (const PointerType *PT = dyn_cast<PointerType>(I->first))
133       if (const MethodType *MT = dyn_cast<MethodType>(PT->getValueType())) {
134         SymbolTable::VarMap &Plane = I->second;
135         for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
136              PI != PE; ++PI) {
137           const string &Name = PI->first;
138           Method *M = cast<Method>(PI->second);
139           Methods[Name].push_back(M);          
140         }
141       }
142
143   bool Changed = false;
144
145   // Now we have a list of all methods with a particular name.  If there is more
146   // than one entry in a list, merge the methods together.
147   //
148   for (map<string, vector<Method*> >::iterator I = Methods.begin(), 
149          E = Methods.end(); I != E; ++I) {
150     vector<Method*> &Methods = I->second;
151     if (Methods.size() > 1) {         // Found a multiply defined method.
152       Method *Implementation = 0;     // Find the implementation
153       Method *Concrete = 0;
154       for (unsigned i = 0; i < Methods.size(); ++i) {
155         // TODO: Ignore methods that are never USED!  DCE them.
156         // Remove their name. this should fix a majority of problems here.
157
158         if (!Methods[i]->isExternal()) {  // Found an implementation
159           assert(Implementation == 0 && "Multiple definitions of the same"
160                  " method. Case not handled yet!");
161           Implementation = Methods[i];
162         }
163
164         if (!Methods[i]->getMethodType()->isVarArg() ||
165             Methods[i]->getMethodType()->getParamTypes().size()) {
166           if (Concrete) {  // Found two different methods types.  Can't choose
167             Concrete = 0;
168             break;
169           }
170           Concrete = Methods[i];
171         }
172       }
173
174       // We should find exactly one non-vararg method definition, which is
175       // probably the implementation.  Change all of the method definitions
176       // and uses to use it instead.
177       //
178       if (!Concrete) {
179         cerr << "Warning: Found methods types that are not compatible:\n";
180         for (unsigned i = 0; i < Methods.size(); ++i) {
181           cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
182                << Methods[i]->getName() << endl;
183         }
184         cerr << "  No linkage of methods named '" << Methods[0]->getName()
185              << "' performed!\n";
186       } else {
187         for (unsigned i = 0; i < Methods.size(); ++i)
188           if (Methods[i] != Concrete) {
189             Method *Old = Methods[i];
190             assert(Old->getReturnType() == Concrete->getReturnType() &&
191                    "Differing return types not handled yet!");
192             assert(Old->getMethodType()->getParamTypes().size() == 0 &&
193                    "Cannot handle varargs fn's with specified element types!");
194             
195             // Attempt to convert all of the uses of the old method to the
196             // concrete form of the method.  If there is a use of the method
197             // that we don't understand here we punt to avoid making a bad
198             // transformation.
199             //
200             // At this point, we know that the return values are the same for
201             // our two functions and that the Old method has no varargs methods
202             // specified.  In otherwords it's just <retty> (...)
203             //
204             for (unsigned i = 0; i < Old->use_size(); ) {
205               User *U = *(Old->use_begin()+i);
206               if (CastInst *CI = dyn_cast<CastInst>(U)) {
207                 // Convert casts directly
208                 assert(CI->getOperand(0) == Old);
209                 CI->setOperand(0, Concrete);
210                 Changed = true;
211               } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
212                 // Can only fix up calls TO the argument, not args passed in.
213                 if (CI->getCalledValue() == Old) {
214                   ConvertCallTo(CI, Concrete);
215                   Changed = true;
216                 } else {
217                   cerr << "Couldn't cleanup this function call, must be an"
218                        << " argument or something!" << CI;
219                   ++i;
220                 }
221               } else {
222                 cerr << "Cannot convert use of method: " << U << endl;
223                 ++i;
224               }
225             }
226           }
227         }
228     }
229   }
230
231   return Changed;
232 }
233
234
235 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
236 // should be eliminated.
237 //
238 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
239   // Nuke all names for primitive types!
240   if (cast<Type>(E.second)->isPrimitiveType()) return true;
241
242   // The only types that could contain .'s in the program are things generated
243   // by GCC itself, including "complex.float" and friends.  Nuke them too.
244   if (E.first.find('.') != string::npos) return true;
245
246   return false;
247 }
248
249 // doPassInitialization - For this pass, it removes global symbol table
250 // entries for primitive types.  These are never used for linking in GCC and
251 // they make the output uglier to look at, so we nuke them.
252 //
253 bool CleanupGCCOutput::doPassInitialization(Module *M) {
254   bool Changed = false;
255
256   if (PtrArrSByte == 0) {
257     PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
258     PtrSByte    = PointerType::get(Type::SByteTy);
259   }
260
261   if (M->hasSymbolTable()) {
262     SymbolTable *ST = M->getSymbolTable();
263
264     // Go over the methods that are in the module and look for methods that have
265     // the same name.  More often than not, there will be things like:
266     // void "foo"(...)  and void "foo"(int, int) because of the way things are
267     // declared in C.  If this is the case, patch things up.
268     //
269     Changed |= PatchUpMethodReferences(M);
270
271
272     // If the module has a symbol table, they might be referring to the malloc
273     // and free functions.  If this is the case, grab the method pointers that 
274     // the module is using.
275     //
276     // Lookup %malloc and %free in the symbol table, for later use.  If they
277     // don't exist, or are not external, we do not worry about converting calls
278     // to that function into the appropriate instruction.
279     //
280     const PointerType *MallocType =   // Get the type for malloc
281       PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
282                                   vector<const Type*>(1, Type::UIntTy), false));
283     Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
284     if (Malloc && !Malloc->isExternal())
285       Malloc = 0;  // Don't mess with locally defined versions of the fn
286
287     const PointerType *FreeType =     // Get the type for free
288       PointerType::get(MethodType::get(Type::VoidTy,
289                vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
290     Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
291     if (Free && !Free->isExternal())
292       Free = 0;  // Don't mess with locally defined versions of the fn
293     
294
295     // Check the symbol table for superfluous type entries...
296     //
297     // Grab the 'type' plane of the module symbol...
298     SymbolTable::iterator STI = ST->find(Type::TypeTy);
299     if (STI != ST->end()) {
300       // Loop over all entries in the type plane...
301       SymbolTable::VarMap &Plane = STI->second;
302       for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
303         if (ShouldNukeSymtabEntry(*PI)) {    // Should we remove this entry?
304 #if MAP_IS_NOT_BRAINDEAD
305           PI = Plane.erase(PI);     // STD C++ Map should support this!
306 #else
307           Plane.erase(PI);          // Alas, GCC 2.95.3 doesn't  *SIGH*
308           PI = Plane.begin();
309 #endif
310           Changed = true;
311         } else {
312           ++PI;
313         }
314     }
315   }
316
317   return Changed;
318 }
319
320
321 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
322 //
323 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
324   bool Changed = false;
325   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
326     BasicBlock *BB = *MI;
327     BasicBlock::InstListType &BIL = BB->getInstList();
328
329     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
330       Instruction *I = *BI;
331
332       if (CallInst *CI = dyn_cast<CallInst>(I)) {
333         if (CI->getCalledValue() == Malloc) {      // Replace call to malloc?
334           MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
335                                                CI->getName());
336           CI->setName("");
337           BI = BIL.insert(BI, MallocI)+1;
338           ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
339           Changed = true;
340           continue;  // Skip the ++BI
341         } else if (CI->getCalledValue() == Free) { // Replace call to free?
342           ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
343           Changed = true;
344           continue;  // Skip the ++BI
345         }
346       }
347
348       ++BI;
349     }
350   }
351
352   return Changed;
353 }
354
355
356
357 // CheckIncomingValueFor - Make sure that the specified PHI node has an entry
358 // for the provided basic block.  If it doesn't, add one and return true.
359 //
360 static inline bool CheckIncomingValueFor(PHINode *PN, BasicBlock *BB) {
361   unsigned NumArgs = PN->getNumIncomingValues();
362   for (unsigned i = 0; i < NumArgs; ++i)
363     if (PN->getIncomingBlock(i) == BB) return false;  // Already has value
364
365   Value      *NewVal = 0;
366   const Type *Ty = PN->getType();
367   if (const PointerType *PT = dyn_cast<PointerType>(Ty))
368     NewVal = ConstPoolPointerNull::get(PT);
369   else if (Ty == Type::BoolTy)
370     NewVal = ConstPoolBool::True;
371   else if (Ty == Type::FloatTy || Ty == Type::DoubleTy)
372     NewVal = ConstPoolFP::get(Ty, 42);
373   else if (Ty->isIntegral())
374     NewVal = ConstPoolInt::get(Ty, 42);
375
376   assert(NewVal && "Unknown PHI node type!");
377   PN->addIncoming(NewVal, BB);
378   return true;
379
380
381 // fixLocalProblems - Loop through the method and fix problems with the PHI
382 // nodes in the current method.  The two problems that are handled are:
383 //
384 //  1. PHI nodes with multiple entries for the same predecessor.
385 //
386 //  2. PHI nodes with fewer arguments than predecessors.
387 //     These can be generated by GCC if a variable is uninitalized over a path
388 //     in the CFG.  We fix this by adding an entry for the missing predecessors
389 //     that is initialized to either 42 for a numeric/FP value, or null if it's
390 //     a pointer value. This problem can be generated by code that looks like
391 //     this:
392 //         int foo(int y) {
393 //           int X;
394 //           if (y) X = 1;
395 //           return X;
396 //         }
397 //
398 static bool fixLocalProblems(Method *M) {
399   bool Changed = false;
400   // Don't use iterators because invalidation gets messy...
401   for (unsigned MI = 0; MI < M->size(); ++MI) {
402     BasicBlock *BB = M->getBasicBlocks()[MI];
403
404     if (isa<PHINode>(BB->front())) {
405       const vector<BasicBlock*> Preds(BB->pred_begin(), BB->pred_end());
406
407       // Loop over all of the PHI nodes in the current BB.  These PHI nodes are
408       // guaranteed to be at the beginning of the basic block.
409       //
410       for (BasicBlock::iterator I = BB->begin(); 
411            PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
412         
413         // Handle problem #2.
414         if (PN->getNumIncomingValues() != Preds.size()) {
415           assert(PN->getNumIncomingValues() <= Preds.size() &&
416                  "Can't handle extra arguments to PHI nodes!");
417           for (unsigned i = 0; i < Preds.size(); ++i)
418             Changed |= CheckIncomingValueFor(PN, Preds[i]);
419         }
420       }
421     }
422   }
423   return Changed;
424 }
425
426
427
428
429 // doPerMethodWork - This method simplifies the specified method hopefully.
430 //
431 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
432   bool Changed = fixLocalProblems(M);
433   while (doOneCleanupPass(M)) Changed = true;
434   return Changed;
435 }