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