1 //===- CleanupGCCOutput.cpp - Cleanup GCC Output ----------------------------=//
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:
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
10 // Note: This code produces dead declarations, it is a good idea to run DCE
13 //===----------------------------------------------------------------------===//
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"
33 static const Type *PtrSByte = 0; // 'sbyte*' type
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.
41 // Also, initialize instance variables.
43 bool doInitialization(Module *M);
45 // runOnFunction - This method simplifies the specified function hopefully.
47 bool runOnMethod(Function *F);
49 // doPassFinalization - Strip out type names that are unused by the program
50 bool doFinalization(Module *M);
52 // getAnalysisUsageInfo - This function needs FindUsedTypes to do its job...
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);
65 // ConvertCallTo - Convert a call to a varargs function with no arg types
66 // specified to a concrete nonvarargs function.
68 static void ConvertCallTo(CallInst *CI, Function *Dest) {
69 const FunctionType::ParamTypes &ParamTys =
70 Dest->getFunctionType()->getParamTypes();
71 BasicBlock *BB = CI->getParent();
73 // Get an iterator to where we want to insert cast instructions if the
74 // argument types don't agree.
76 BasicBlock::iterator BBI = find(BB->begin(), BB->end(), CI);
77 assert(BBI != BB->end() && "CallInst not in parent block?");
79 assert(CI->getNumOperands()-1 == ParamTys.size()&&
80 "Function calls resolved funny somehow, incompatible number of args");
82 vector<Value*> Params;
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);
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;
98 // Replace the old call instruction with a new call instruction that calls
101 ReplaceInstWithInst(BB->getInstList(), BBI, new CallInst(Dest, Params));
105 // PatchUpFunctionReferences - Go over the functions that are in the module and
106 // look for functions that have the same name. More often than not, there will
109 // void "foo"(int, int)
110 // because of the way things are declared in C. If this is the case, patch
113 static bool PatchUpFunctionReferences(Module *M) {
114 SymbolTable *ST = M->getSymbolTable();
115 if (!ST) return false;
117 std::map<string, vector<Function*> > Functions;
119 // Loop over the entries in the symbol table. If an entry is a func pointer,
120 // then add it to the Functions map. We do a two pass algorithm here to avoid
121 // problems with iterators getting invalidated if we did a one pass scheme.
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<FunctionType>(PT->getElementType())) {
126 SymbolTable::VarMap &Plane = I->second;
127 for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
129 const string &Name = PI->first;
130 Functions[Name].push_back(cast<Function>(PI->second));
134 bool Changed = false;
136 // Now we have a list of all functions with a particular name. If there is
137 // more than one entry in a list, merge the functions together.
139 for (std::map<string, vector<Function*> >::iterator I = Functions.begin(),
140 E = Functions.end(); I != E; ++I) {
141 vector<Function*> &Functions = I->second;
142 Function *Implementation = 0; // Find the implementation
143 Function *Concrete = 0;
144 for (unsigned i = 0; i < Functions.size(); ) {
145 if (!Functions[i]->isExternal()) { // Found an implementation
146 assert(Implementation == 0 && "Multiple definitions of the same"
147 " function. Case not handled yet!");
148 Implementation = Functions[i];
150 // Ignore functions that are never used so they don't cause spurious
151 // warnings... here we will actually DCE the function so that it isn't
154 if (Functions[i]->use_size() == 0) {
155 M->getFunctionList().remove(Functions[i]);
157 Functions.erase(Functions.begin()+i);
163 if (Functions[i] && (!Functions[i]->getFunctionType()->isVarArg())) {
164 if (Concrete) { // Found two different functions types. Can't choose
168 Concrete = Functions[i];
173 if (Functions.size() > 1) { // Found a multiply defined function...
174 // We should find exactly one non-vararg function definition, which is
175 // probably the implementation. Change all of the function definitions
176 // and uses to use it instead.
179 cerr << "Warning: Found functions types that are not compatible:\n";
180 for (unsigned i = 0; i < Functions.size(); ++i) {
181 cerr << "\t" << Functions[i]->getType()->getDescription() << " %"
182 << Functions[i]->getName() << "\n";
184 cerr << " No linkage of functions named '" << Functions[0]->getName()
187 for (unsigned i = 0; i < Functions.size(); ++i)
188 if (Functions[i] != Concrete) {
189 Function *Old = Functions[i];
190 const FunctionType *OldMT = Old->getFunctionType();
191 const FunctionType *ConcreteMT = Concrete->getFunctionType();
194 assert(Old->getReturnType() == Concrete->getReturnType() &&
195 "Differing return types not handled yet!");
196 assert(OldMT->getParamTypes().size() <=
197 ConcreteMT->getParamTypes().size() &&
198 "Concrete type must have more specified parameters!");
200 // Check to make sure that if there are specified types, that they
203 for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
204 if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
205 cerr << "Parameter types conflict for" << OldMT
206 << " and " << ConcreteMT;
209 if (Broken) break; // Can't process this one!
212 // Attempt to convert all of the uses of the old function to the
213 // concrete form of the function. If there is a use of the fn
214 // that we don't understand here we punt to avoid making a bad
217 // At this point, we know that the return values are the same for
218 // our two functions and that the Old function has no varargs fns
219 // specified. In otherwords it's just <retty> (...)
221 for (unsigned i = 0; i < Old->use_size(); ) {
222 User *U = *(Old->use_begin()+i);
223 if (CastInst *CI = dyn_cast<CastInst>(U)) {
224 // Convert casts directly
225 assert(CI->getOperand(0) == Old);
226 CI->setOperand(0, Concrete);
228 } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
229 // Can only fix up calls TO the argument, not args passed in.
230 if (CI->getCalledValue() == Old) {
231 ConvertCallTo(CI, Concrete);
234 cerr << "Couldn't cleanup this function call, must be an"
235 << " argument or something!" << CI;
239 cerr << "Cannot convert use of function: " << U << "\n";
252 // ShouldNukSymtabEntry - Return true if this module level symbol table entry
253 // should be eliminated.
255 static inline bool ShouldNukeSymtabEntry(const std::pair<string, Value*> &E) {
256 // Nuke all names for primitive types!
257 if (cast<Type>(E.second)->isPrimitiveType()) return true;
259 // Nuke all pointers to primitive types as well...
260 if (const PointerType *PT = dyn_cast<PointerType>(E.second))
261 if (PT->getElementType()->isPrimitiveType()) return true;
263 // The only types that could contain .'s in the program are things generated
264 // by GCC itself, including "complex.float" and friends. Nuke them too.
265 if (E.first.find('.') != string::npos) return true;
270 // doInitialization - For this pass, it removes global symbol table
271 // entries for primitive types. These are never used for linking in GCC and
272 // they make the output uglier to look at, so we nuke them.
274 bool CleanupGCCOutput::doInitialization(Module *M) {
275 bool Changed = false;
278 PtrSByte = PointerType::get(Type::SByteTy);
280 if (M->hasSymbolTable()) {
281 SymbolTable *ST = M->getSymbolTable();
283 // Go over the functions that are in the module and look for methods that
284 // have the same name. More often than not, there will be things like:
285 // void "foo"(...) and void "foo"(int, int) because of the way things are
286 // declared in C. If this is the case, patch things up.
288 Changed |= PatchUpFunctionReferences(M);
290 // Check the symbol table for superfluous type entries...
292 // Grab the 'type' plane of the module symbol...
293 SymbolTable::iterator STI = ST->find(Type::TypeTy);
294 if (STI != ST->end()) {
295 // Loop over all entries in the type plane...
296 SymbolTable::VarMap &Plane = STI->second;
297 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
298 if (ShouldNukeSymtabEntry(*PI)) { // Should we remove this entry?
299 #if MAP_IS_NOT_BRAINDEAD
300 PI = Plane.erase(PI); // STD C++ Map should support this!
302 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
316 // FixCastsAndPHIs - The LLVM GCC has a tendancy to intermix Cast instructions
317 // in with the PHI nodes. These cast instructions are potentially there for two
318 // different reasons:
320 // 1. The cast could be for an early PHI, and be accidentally inserted before
321 // another PHI node. In this case, the PHI node should be moved to the end
322 // of the PHI nodes in the basic block. We know that it is this case if
323 // the source for the cast is a PHI node in this basic block.
325 // 2. If not #1, the cast must be a source argument for one of the PHI nodes
326 // in the current basic block. If this is the case, the cast should be
327 // lifted into the basic block for the appropriate predecessor.
329 static inline bool FixCastsAndPHIs(BasicBlock *BB) {
330 bool Changed = false;
332 BasicBlock::iterator InsertPos = BB->begin();
334 // Find the end of the interesting instructions...
335 while (isa<PHINode>(*InsertPos) || isa<CastInst>(*InsertPos)) ++InsertPos;
337 // Back the InsertPos up to right after the last PHI node.
338 while (InsertPos != BB->begin() && isa<CastInst>(*(InsertPos-1))) --InsertPos;
340 // No PHI nodes, quick exit.
341 if (InsertPos == BB->begin()) return false;
343 // Loop over all casts trapped between the PHI's...
344 BasicBlock::iterator I = BB->begin();
345 while (I != InsertPos) {
346 if (CastInst *CI = dyn_cast<CastInst>(*I)) { // Fix all cast instructions
347 Value *Src = CI->getOperand(0);
349 // Move the cast instruction to the current insert position...
350 --InsertPos; // New position for cast to go...
351 std::swap(*InsertPos, *I); // Cast goes down, PHI goes up
353 if (isa<PHINode>(Src) && // Handle case #1
354 cast<PHINode>(Src)->getParent() == BB) {
355 // We're done for case #1
356 } else { // Handle case #2
357 // In case #2, we have to do a few things:
358 // 1. Remove the cast from the current basic block.
359 // 2. Identify the PHI node that the cast is for.
360 // 3. Find out which predecessor the value is for.
361 // 4. Move the cast to the end of the basic block that it SHOULD be
364 // Remove the cast instruction from the basic block. The remove only
365 // invalidates iterators in the basic block that are AFTER the removed
366 // element. Because we just moved the CastInst to the InsertPos, no
367 // iterators get invalidated.
369 BB->getInstList().remove(InsertPos);
371 // Find the PHI node. Since this cast was generated specifically for a
372 // PHI node, there can only be a single PHI node using it.
374 assert(CI->use_size() == 1 && "Exactly one PHI node should use cast!");
375 PHINode *PN = cast<PHINode>(*CI->use_begin());
377 // Find out which operand of the PHI it is...
379 for (i = 0; i < PN->getNumIncomingValues(); ++i)
380 if (PN->getIncomingValue(i) == CI)
382 assert(i != PN->getNumIncomingValues() && "PHI doesn't use cast!");
384 // Get the predecessor the value is for...
385 BasicBlock *Pred = PN->getIncomingBlock(i);
387 // Reinsert the cast right before the terminator in Pred.
388 Pred->getInstList().insert(Pred->end()-1, CI);
398 // RefactorPredecessor - When we find out that a basic block is a repeated
399 // predecessor in a PHI node, we have to refactor the function until there is at
400 // most a single instance of a basic block in any predecessor list.
402 static inline void RefactorPredecessor(BasicBlock *BB, BasicBlock *Pred) {
403 Function *M = BB->getParent();
404 assert(find(pred_begin(BB), pred_end(BB), Pred) != pred_end(BB) &&
405 "Pred is not a predecessor of BB!");
407 // Create a new basic block, adding it to the end of the function.
408 BasicBlock *NewBB = new BasicBlock("", M);
410 // Add an unconditional branch to BB to the new block.
411 NewBB->getInstList().push_back(new BranchInst(BB));
413 // Get the terminator that causes a branch to BB from Pred.
414 TerminatorInst *TI = Pred->getTerminator();
416 // Find the first use of BB in the terminator...
417 User::op_iterator OI = find(TI->op_begin(), TI->op_end(), BB);
418 assert(OI != TI->op_end() && "Pred does not branch to BB!!!");
420 // Change the use of BB to point to the new stub basic block
423 // Now we need to loop through all of the PHI nodes in BB and convert their
424 // first incoming value for Pred to reference the new basic block instead.
426 for (BasicBlock::iterator I = BB->begin();
427 PHINode *PN = dyn_cast<PHINode>(*I); ++I) {
428 int BBIdx = PN->getBasicBlockIndex(Pred);
429 assert(BBIdx != -1 && "PHI node doesn't have an entry for Pred!");
431 // The value that used to look like it came from Pred now comes from NewBB
432 PN->setIncomingBlock((unsigned)BBIdx, NewBB);
437 // fixLocalProblems - Loop through the function and fix problems with the PHI
438 // nodes in the current function. The problem is that PHI nodes might exist
439 // with multiple entries for the same predecessor. GCC sometimes generates code
440 // that looks like this:
442 // bb7: br bool %cond1004, label %bb8, label %bb8
443 // bb8: %reg119 = phi uint [ 0, %bb7 ], [ 1, %bb7 ]
445 // which is completely illegal LLVM code. To compensate for this, we insert
446 // an extra basic block, and convert the code to look like this:
448 // bb7: br bool %cond1004, label %bbX, label %bb8
450 // bb8: %reg119 = phi uint [ 0, %bbX ], [ 1, %bb7 ]
453 static bool fixLocalProblems(Function *M) {
454 bool Changed = false;
455 // Don't use iterators because invalidation gets messy...
456 for (unsigned MI = 0; MI < M->size(); ++MI) {
457 BasicBlock *BB = M->getBasicBlocks()[MI];
459 Changed |= FixCastsAndPHIs(BB);
461 if (isa<PHINode>(BB->front())) {
462 const vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
464 // Handle the problem. Sort the list of predecessors so that it is easy
465 // to decide whether or not duplicate predecessors exist.
466 vector<BasicBlock*> SortedPreds(Preds);
467 sort(SortedPreds.begin(), SortedPreds.end());
469 // Loop over the predecessors, looking for adjacent BB's that are equal.
470 BasicBlock *LastOne = 0;
471 for (unsigned i = 0; i < Preds.size(); ++i) {
472 if (SortedPreds[i] == LastOne) { // Found a duplicate.
473 RefactorPredecessor(BB, SortedPreds[i]);
476 LastOne = SortedPreds[i];
486 // runOnFunction - This method simplifies the specified function hopefully.
488 bool CleanupGCCOutput::runOnMethod(Function *F) {
489 return fixLocalProblems(F);
492 bool CleanupGCCOutput::doFinalization(Module *M) {
493 bool Changed = false;
496 if (M->hasSymbolTable()) {
497 SymbolTable *ST = M->getSymbolTable();
498 const std::set<const Type *> &UsedTypes =
499 getAnalysis<FindUsedTypes>().getTypes();
501 // Check the symbol table for superfluous type entries that aren't used in
504 // Grab the 'type' plane of the module symbol...
505 SymbolTable::iterator STI = ST->find(Type::TypeTy);
506 if (STI != ST->end()) {
507 // Loop over all entries in the type plane...
508 SymbolTable::VarMap &Plane = STI->second;
509 for (SymbolTable::VarMap::iterator PI = Plane.begin(); PI != Plane.end();)
510 if (!UsedTypes.count(cast<Type>(PI->second))) {
511 #if MAP_IS_NOT_BRAINDEAD
512 PI = Plane.erase(PI); // STD C++ Map should support this!
514 Plane.erase(PI); // Alas, GCC 2.95.3 doesn't *SIGH*
515 PI = Plane.begin(); // N^2 algorithms are fun. :(
526 Pass *createCleanupGCCOutputPass() {
527 return new CleanupGCCOutput();