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