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