Add new cleanup pass:
[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 "llvm/iTerminators.h"
24 #include <map>
25 #include <algorithm>
26
27 static const Type *PtrArrSByte = 0; // '[sbyte]*' type
28 static const Type *PtrSByte = 0;    // 'sbyte*' type
29
30
31 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
32 // with a value, then remove and delete the original instruction.
33 //
34 static void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
35                                  BasicBlock::iterator &BI, Value *V) {
36   Instruction *I = *BI;
37   // Replaces all of the uses of the instruction with uses of the value
38   I->replaceAllUsesWith(V);
39
40   // Remove the unneccesary instruction now...
41   BIL.remove(BI);
42
43   // Make sure to propogate a name if there is one already...
44   if (I->hasName() && !V->hasName())
45     V->setName(I->getName(), BIL.getParent()->getSymbolTable());
46
47   // Remove the dead instruction now...
48   delete I;
49 }
50
51
52 // ReplaceInstWithInst - Replace the instruction specified by BI with the
53 // instruction specified by I.  The original instruction is deleted and BI is
54 // updated to point to the new instruction.
55 //
56 static void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
57                                 BasicBlock::iterator &BI, Instruction *I) {
58   assert(I->getParent() == 0 &&
59          "ReplaceInstWithInst: Instruction already inserted into basic block!");
60
61   // Insert the new instruction into the basic block...
62   BI = BIL.insert(BI, I)+1;
63
64   // Replace all uses of the old instruction, and delete it.
65   ReplaceInstWithValue(BIL, BI, I);
66
67   // Reexamine the instruction just inserted next time around the cleanup pass
68   // loop.
69   --BI;
70 }
71
72
73
74 // ConvertCallTo - Convert a call to a varargs function with no arg types
75 // specified to a concrete nonvarargs method.
76 //
77 static void ConvertCallTo(CallInst *CI, Method *Dest) {
78   const MethodType::ParamTypes &ParamTys =
79     Dest->getMethodType()->getParamTypes();
80   BasicBlock *BB = CI->getParent();
81
82   // Get an iterator to where we want to insert cast instructions if the
83   // argument types don't agree.
84   //
85   BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
86   assert(BBI != BB->end() && "CallInst not in parent block?");
87
88   assert(CI->getNumOperands()-1 == ParamTys.size()&&
89          "Method calls resolved funny somehow, incompatible number of args");
90
91   vector<Value*> Params;
92
93   // Convert all of the call arguments over... inserting cast instructions if
94   // the types are not compatible.
95   for (unsigned i = 1; i < CI->getNumOperands(); ++i) {
96     Value *V = CI->getOperand(i);
97
98     if (V->getType() != ParamTys[i-1]) { // Must insert a cast...
99       Instruction *Cast = new CastInst(V, ParamTys[i-1]);
100       BBI = BB->getInstList().insert(BBI, Cast)+1;
101       V = Cast;
102     }
103
104     Params.push_back(V);
105   }
106
107   // Replace the old call instruction with a new call instruction that calls
108   // the real method.
109   //
110   ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
111 }
112
113
114 // PatchUpMethodReferences - Go over the methods that are in the module and
115 // look for methods that have the same name.  More often than not, there will
116 // be things like:
117 //    void "foo"(...)
118 //    void "foo"(int, int)
119 // because of the way things are declared in C.  If this is the case, patch
120 // things up.
121 //
122 bool CleanupGCCOutput::PatchUpMethodReferences(Module *M) {
123   SymbolTable *ST = M->getSymbolTable();
124   if (!ST) return false;
125
126   map<string, vector<Method*> > Methods;
127
128   // Loop over the entries in the symbol table. If an entry is a method pointer,
129   // then add it to the Methods map.  We do a two pass algorithm here to avoid
130   // problems with iterators getting invalidated if we did a one pass scheme.
131   //
132   for (SymbolTable::iterator I = ST->begin(), E = ST->end(); I != E; ++I)
133     if (const PointerType *PT = dyn_cast<PointerType>(I->first))
134       if (const MethodType *MT = dyn_cast<MethodType>(PT->getValueType())) {
135         SymbolTable::VarMap &Plane = I->second;
136         for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
137              PI != PE; ++PI) {
138           const string &Name = PI->first;
139           Method *M = cast<Method>(PI->second);
140           Methods[Name].push_back(M);          
141         }
142       }
143
144   bool Changed = false;
145
146   // Now we have a list of all methods with a particular name.  If there is more
147   // than one entry in a list, merge the methods together.
148   //
149   for (map<string, vector<Method*> >::iterator I = Methods.begin(), 
150          E = Methods.end(); I != E; ++I) {
151     vector<Method*> &Methods = I->second;
152     if (Methods.size() > 1) {         // Found a multiply defined method.
153       Method *Implementation = 0;     // Find the implementation
154       Method *Concrete = 0;
155       for (unsigned i = 0; i < Methods.size(); ++i) {
156         // TODO: Ignore methods that are never USED!  DCE them.
157         // Remove their name. this should fix a majority of problems here.
158
159         if (!Methods[i]->isExternal()) {  // Found an implementation
160           assert(Implementation == 0 && "Multiple definitions of the same"
161                  " method. Case not handled yet!");
162           Implementation = Methods[i];
163         }
164
165         if (!Methods[i]->getMethodType()->isVarArg() ||
166             Methods[i]->getMethodType()->getParamTypes().size()) {
167           if (Concrete) {  // Found two different methods types.  Can't choose
168             Concrete = 0;
169             break;
170           }
171           Concrete = Methods[i];
172         }
173       }
174
175       // We should find exactly one non-vararg method definition, which is
176       // probably the implementation.  Change all of the method definitions
177       // and uses to use it instead.
178       //
179       if (!Concrete) {
180         cerr << "Warning: Found methods types that are not compatible:\n";
181         for (unsigned i = 0; i < Methods.size(); ++i) {
182           cerr << "\t" << Methods[i]->getType()->getDescription() << " %"
183                << Methods[i]->getName() << endl;
184         }
185         cerr << "  No linkage of methods named '" << Methods[0]->getName()
186              << "' performed!\n";
187       } else {
188         for (unsigned i = 0; i < Methods.size(); ++i)
189           if (Methods[i] != Concrete) {
190             Method *Old = Methods[i];
191             assert(Old->getReturnType() == Concrete->getReturnType() &&
192                    "Differing return types not handled yet!");
193             assert(Old->getMethodType()->getParamTypes().size() == 0 &&
194                    "Cannot handle varargs fn's with specified element types!");
195             
196             // Attempt to convert all of the uses of the old method to the
197             // concrete form of the method.  If there is a use of the method
198             // that we don't understand here we punt to avoid making a bad
199             // transformation.
200             //
201             // At this point, we know that the return values are the same for
202             // our two functions and that the Old method has no varargs methods
203             // specified.  In otherwords it's just <retty> (...)
204             //
205             for (unsigned i = 0; i < Old->use_size(); ) {
206               User *U = *(Old->use_begin()+i);
207               if (CastInst *CI = dyn_cast<CastInst>(U)) {
208                 // Convert casts directly
209                 assert(CI->getOperand(0) == Old);
210                 CI->setOperand(0, Concrete);
211                 Changed = true;
212               } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
213                 // Can only fix up calls TO the argument, not args passed in.
214                 if (CI->getCalledValue() == Old) {
215                   ConvertCallTo(CI, Concrete);
216                   Changed = true;
217                 } else {
218                   cerr << "Couldn't cleanup this function call, must be an"
219                        << " argument or something!" << CI;
220                   ++i;
221                 }
222               } else {
223                 cerr << "Cannot convert use of method: " << U << endl;
224                 ++i;
225               }
226             }
227           }
228         }
229     }
230   }
231
232   return Changed;
233 }
234
235
236 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
237 // should be eliminated.
238 //
239 static inline bool ShouldNukeSymtabEntry(const pair<string, Value*> &E) {
240   // Nuke all names for primitive types!
241   if (cast<Type>(E.second)->isPrimitiveType()) return true;
242
243   // The only types that could contain .'s in the program are things generated
244   // by GCC itself, including "complex.float" and friends.  Nuke them too.
245   if (E.first.find('.') != string::npos) return true;
246
247   return false;
248 }
249
250 // doPassInitialization - For this pass, it removes global symbol table
251 // entries for primitive types.  These are never used for linking in GCC and
252 // they make the output uglier to look at, so we nuke them.
253 //
254 bool CleanupGCCOutput::doPassInitialization(Module *M) {
255   bool Changed = false;
256
257   if (PtrArrSByte == 0) {
258     PtrArrSByte = PointerType::get(ArrayType::get(Type::SByteTy));
259     PtrSByte    = PointerType::get(Type::SByteTy);
260   }
261
262   if (M->hasSymbolTable()) {
263     SymbolTable *ST = M->getSymbolTable();
264
265     // Go over the methods that are in the module and look for methods that have
266     // the same name.  More often than not, there will be things like:
267     // void "foo"(...)  and void "foo"(int, int) because of the way things are
268     // declared in C.  If this is the case, patch things up.
269     //
270     Changed |= PatchUpMethodReferences(M);
271
272
273     // If the module has a symbol table, they might be referring to the malloc
274     // and free functions.  If this is the case, grab the method pointers that 
275     // the module is using.
276     //
277     // Lookup %malloc and %free in the symbol table, for later use.  If they
278     // don't exist, or are not external, we do not worry about converting calls
279     // to that function into the appropriate instruction.
280     //
281     const PointerType *MallocType =   // Get the type for malloc
282       PointerType::get(MethodType::get(PointerType::get(Type::SByteTy),
283                                   vector<const Type*>(1, Type::UIntTy), false));
284     Malloc = cast_or_null<Method>(ST->lookup(MallocType, "malloc"));
285     if (Malloc && !Malloc->isExternal())
286       Malloc = 0;  // Don't mess with locally defined versions of the fn
287
288     const PointerType *FreeType =     // Get the type for free
289       PointerType::get(MethodType::get(Type::VoidTy,
290                vector<const Type*>(1, PointerType::get(Type::SByteTy)), false));
291     Free = cast_or_null<Method>(ST->lookup(FreeType, "free"));
292     if (Free && !Free->isExternal())
293       Free = 0;  // Don't mess with locally defined versions of the fn
294     
295
296     // Check the symbol table for superfluous type entries...
297     //
298     // Grab the 'type' plane of the module symbol...
299     SymbolTable::iterator STI = ST->find(Type::TypeTy);
300     if (STI != ST->end()) {
301       // Loop over all entries in the type plane...
302       SymbolTable::VarMap &Plane = STI->second;
303       for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
304         if (ShouldNukeSymtabEntry(*PI)) {    // Should we remove this entry?
305 #if MAP_IS_NOT_BRAINDEAD
306           PI = Plane.erase(PI);     // STD C++ Map should support this!
307 #else
308           Plane.erase(PI);          // Alas, GCC 2.95.3 doesn't  *SIGH*
309           PI = Plane.begin();
310 #endif
311           Changed = true;
312         } else {
313           ++PI;
314         }
315     }
316   }
317
318   return Changed;
319 }
320
321
322 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
323 //
324 bool CleanupGCCOutput::doOneCleanupPass(Method *M) {
325   bool Changed = false;
326   for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
327     BasicBlock *BB = *MI;
328     BasicBlock::InstListType &BIL = BB->getInstList();
329
330     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
331       Instruction *I = *BI;
332
333       if (CallInst *CI = dyn_cast<CallInst>(I)) {
334         if (CI->getCalledValue() == Malloc) {      // Replace call to malloc?
335           MallocInst *MallocI = new MallocInst(PtrArrSByte, CI->getOperand(1),
336                                                CI->getName());
337           CI->setName("");
338           BI = BIL.insert(BI, MallocI)+1;
339           ReplaceInstWithInst(BIL, BI, new CastInst(MallocI, PtrSByte));
340           Changed = true;
341           continue;  // Skip the ++BI
342         } else if (CI->getCalledValue() == Free) { // Replace call to free?
343           ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
344           Changed = true;
345           continue;  // Skip the ++BI
346         }
347       }
348
349       ++BI;
350     }
351   }
352
353   return Changed;
354 }
355
356
357
358 // RefactorPredecessor - When we find out that a basic block is a repeated
359 // predecessor in a PHI node, we have to refactor the method until there is at
360 // most a single instance of a basic block in any predecessor list.
361 //
362 static inline void RefactorPredecessor(BasicBlock *BB, BasicBlock *Pred) {
363   Method *M = BB->getParent();
364   assert(find(BB->pred_begin(), BB->pred_end(), Pred) != BB->pred_end() &&
365          "Pred is not a predecessor of BB!");
366
367   // Create a new basic block, adding it to the end of the method.
368   BasicBlock *NewBB = new BasicBlock("", M);
369
370   // Add an unconditional branch to BB to the new block.
371   NewBB->getInstList().push_back(new BranchInst(BB));
372
373   // Get the terminator that causes a branch to BB from Pred.
374   TerminatorInst *TI = Pred->getTerminator();
375
376   // Find the first use of BB in the terminator...
377   User::op_iterator OI = find(TI->op_begin(), TI->op_end(), BB);
378   assert(OI != TI->op_end() && "Pred does not branch to BB!!!");
379
380   // Change the use of BB to point to the new stub basic block
381   *OI = NewBB;
382
383   // Now we need to loop through all of the PHI nodes in BB and convert their
384   // first incoming value for Pred to reference the new basic block instead.
385   //
386   for (BasicBlock::iterator I = BB->begin(); 
387        PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
388     int BBIdx = PN->getBasicBlockIndex(Pred);
389     assert(BBIdx != -1 && "PHI node doesn't have an entry for Pred!");
390
391     // The value that used to look like it came from Pred now comes from NewBB
392     PN->setIncomingBlock((unsigned)BBIdx, NewBB);
393   }
394 }
395
396
397 // CheckIncomingValueFor - Make sure that the specified PHI node has an entry
398 // for the provided basic block.  If it doesn't, add one and return true.
399 //
400 static inline void CheckIncomingValueFor(PHINode *PN, BasicBlock *BB) {
401   if (PN->getBasicBlockIndex(BB) != -1) return;  // Already has value
402
403   Value      *NewVal = 0;
404   const Type *Ty = PN->getType();
405
406   if (const PointerType *PT = dyn_cast<PointerType>(Ty))
407     NewVal = ConstPoolPointerNull::get(PT);
408   else if (Ty == Type::BoolTy)
409     NewVal = ConstPoolBool::True;
410   else if (Ty == Type::FloatTy || Ty == Type::DoubleTy)
411     NewVal = ConstPoolFP::get(Ty, 42);
412   else if (Ty->isIntegral())
413     NewVal = ConstPoolInt::get(Ty, 42);
414
415   assert(NewVal && "Unknown PHI node type!");
416   PN->addIncoming(NewVal, BB);
417
418
419 // fixLocalProblems - Loop through the method and fix problems with the PHI
420 // nodes in the current method.  The two problems that are handled are:
421 //
422 //  1. PHI nodes with multiple entries for the same predecessor.  GCC sometimes
423 //     generates code that looks like this:
424 //
425 //  bb7:  br bool %cond1004, label %bb8, label %bb8
426 //  bb8: %reg119 = phi uint [ 0, %bb7 ], [ 1, %bb7 ]
427 //     
428 //     which is completely illegal LLVM code.  To compensate for this, we insert
429 //     an extra basic block, and convert the code to look like this:
430 //
431 //  bb7: br bool %cond1004, label %bbX, label %bb8
432 //  bbX: br label bb8
433 //  bb8: %reg119 = phi uint [ 0, %bbX ], [ 1, %bb7 ]
434 //
435 //
436 //  2. PHI nodes with fewer arguments than predecessors.
437 //     These can be generated by GCC if a variable is uninitalized over a path
438 //     in the CFG.  We fix this by adding an entry for the missing predecessors
439 //     that is initialized to either 42 for a numeric/FP value, or null if it's
440 //     a pointer value. This problem can be generated by code that looks like
441 //     this:
442 //         int foo(int y) {
443 //           int X;
444 //           if (y) X = 1;
445 //           return X;
446 //         }
447 //
448 static bool fixLocalProblems(Method *M) {
449   bool Changed = false;
450   // Don't use iterators because invalidation gets messy...
451   for (unsigned MI = 0; MI < M->size(); ++MI) {
452     BasicBlock *BB = M->getBasicBlocks()[MI];
453
454     if (isa<PHINode>(BB->front())) {
455       const vector<BasicBlock*> Preds(BB->pred_begin(), BB->pred_end());
456
457       // Handle Problem #1.  Sort the list of predecessors so that it is easy to
458       // decide whether or not duplicate predecessors exist.
459       vector<BasicBlock*> SortedPreds(Preds);
460       sort(SortedPreds.begin(), SortedPreds.end());
461
462       // Loop over the predecessors, looking for adjacent BB's that are equal.
463       BasicBlock *LastOne = 0;
464       for (unsigned i = 0; i < Preds.size(); ++i) {
465         if (SortedPreds[i] == LastOne) {   // Found a duplicate.
466           RefactorPredecessor(BB, SortedPreds[i]);
467           Changed = true;
468         }
469         LastOne = SortedPreds[i];
470       }
471
472       // Loop over all of the PHI nodes in the current BB.  These PHI nodes are
473       // guaranteed to be at the beginning of the basic block.
474       //
475       for (BasicBlock::iterator I = BB->begin(); 
476            PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
477         
478         // Handle problem #2.
479         if (PN->getNumIncomingValues() != Preds.size()) {
480           assert(PN->getNumIncomingValues() <= Preds.size() &&
481                  "Can't handle extra arguments to PHI nodes!");
482           for (unsigned i = 0; i < Preds.size(); ++i)
483             CheckIncomingValueFor(PN, Preds[i]);
484           Changed = true;
485         }
486       }
487     }
488   }
489   return Changed;
490 }
491
492
493
494
495 // doPerMethodWork - This method simplifies the specified method hopefully.
496 //
497 bool CleanupGCCOutput::doPerMethodWork(Method *M) {
498   bool Changed = fixLocalProblems(M);
499   while (doOneCleanupPass(M)) Changed = true;
500   return Changed;
501 }