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