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