Local.cpp revision 3822ff5c71478c7c90a50ca57045fb676fcb5005
1//===-- Local.cpp - Functions to perform local transformations ------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This family of functions perform various local transformations to the 11// program. 12// 13//===----------------------------------------------------------------------===// 14 15#include "llvm/Transforms/Utils/Local.h" 16#include "llvm/Constants.h" 17#include "llvm/DerivedTypes.h" 18#include "llvm/Instructions.h" 19#include "llvm/Intrinsics.h" 20#include "llvm/Analysis/ConstantFolding.h" 21#include "llvm/Support/GetElementPtrTypeIterator.h" 22#include "llvm/Support/MathExtras.h" 23#include <cerrno> 24#include <cmath> 25using namespace llvm; 26 27//===----------------------------------------------------------------------===// 28// Local constant propagation... 29// 30 31/// doConstantPropagation - If an instruction references constants, try to fold 32/// them together... 33/// 34bool llvm::doConstantPropagation(BasicBlock::iterator &II) { 35 if (Constant *C = ConstantFoldInstruction(II)) { 36 // Replaces all of the uses of a variable with uses of the constant. 37 II->replaceAllUsesWith(C); 38 39 // Remove the instruction from the basic block... 40 II = II->getParent()->getInstList().erase(II); 41 return true; 42 } 43 44 return false; 45} 46 47/// ConstantFoldInstruction - Attempt to constant fold the specified 48/// instruction. If successful, the constant result is returned, if not, null 49/// is returned. Note that this function can only fail when attempting to fold 50/// instructions like loads and stores, which have no constant expression form. 51/// 52Constant *llvm::ConstantFoldInstruction(Instruction *I) { 53 if (PHINode *PN = dyn_cast<PHINode>(I)) { 54 if (PN->getNumIncomingValues() == 0) 55 return Constant::getNullValue(PN->getType()); 56 57 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); 58 if (Result == 0) return 0; 59 60 // Handle PHI nodes specially here... 61 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) 62 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) 63 return 0; // Not all the same incoming constants... 64 65 // If we reach here, all incoming values are the same constant. 66 return Result; 67 } 68 69 Constant *Op0 = 0, *Op1 = 0; 70 switch (I->getNumOperands()) { 71 default: 72 case 2: 73 Op1 = dyn_cast<Constant>(I->getOperand(1)); 74 if (Op1 == 0) return 0; // Not a constant?, can't fold 75 case 1: 76 Op0 = dyn_cast<Constant>(I->getOperand(0)); 77 if (Op0 == 0) return 0; // Not a constant?, can't fold 78 break; 79 case 0: return 0; 80 } 81 82 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) { 83 if (Constant *Op0 = dyn_cast<Constant>(I->getOperand(0))) 84 if (Constant *Op1 = dyn_cast<Constant>(I->getOperand(1))) 85 return ConstantExpr::get(I->getOpcode(), Op0, Op1); 86 return 0; // Operands not constants. 87 } 88 89 // Scan the operand list, checking to see if the are all constants, if so, 90 // hand off to ConstantFoldInstOperands. 91 std::vector<Constant*> Ops; 92 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 93 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i))) 94 Ops.push_back(Op); 95 else 96 return 0; // All operands not constant! 97 98 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops); 99} 100 101/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the 102/// specified opcode and operands. If successful, the constant result is 103/// returned, if not, null is returned. Note that this function can fail when 104/// attempting to fold instructions like loads and stores, which have no 105/// constant expression form. 106/// 107Constant *llvm::ConstantFoldInstOperands(unsigned Opc, const Type *DestTy, 108 const std::vector<Constant*> &Ops) { 109 if (Opc >= Instruction::BinaryOpsBegin && Opc < Instruction::BinaryOpsEnd) 110 return ConstantExpr::get(Opc, Ops[0], Ops[1]); 111 112 switch (Opc) { 113 default: return 0; 114 case Instruction::Call: 115 if (Function *F = dyn_cast<Function>(Ops[0])) { 116 if (canConstantFoldCallTo(F)) { 117 std::vector<Constant*> Args(Ops.begin()+1, Ops.end()); 118 return ConstantFoldCall(F, Args); 119 } 120 } 121 return 0; 122 case Instruction::Shl: 123 case Instruction::LShr: 124 case Instruction::AShr: 125 return ConstantExpr::get(Opc, Ops[0], Ops[1]); 126 case Instruction::Cast: 127 return ConstantExpr::getCast(Ops[0], DestTy); 128 case Instruction::Select: 129 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); 130 case Instruction::ExtractElement: 131 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 132 case Instruction::InsertElement: 133 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 134 case Instruction::ShuffleVector: 135 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]); 136 case Instruction::GetElementPtr: 137 return ConstantExpr::getGetElementPtr(Ops[0], 138 std::vector<Constant*>(Ops.begin()+1, 139 Ops.end())); 140 } 141} 142 143// ConstantFoldTerminator - If a terminator instruction is predicated on a 144// constant value, convert it into an unconditional branch to the constant 145// destination. 146// 147bool llvm::ConstantFoldTerminator(BasicBlock *BB) { 148 TerminatorInst *T = BB->getTerminator(); 149 150 // Branch - See if we are conditional jumping on constant 151 if (BranchInst *BI = dyn_cast<BranchInst>(T)) { 152 if (BI->isUnconditional()) return false; // Can't optimize uncond branch 153 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); 154 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); 155 156 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { 157 // Are we branching on constant? 158 // YES. Change to unconditional branch... 159 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; 160 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; 161 162 //cerr << "Function: " << T->getParent()->getParent() 163 // << "\nRemoving branch from " << T->getParent() 164 // << "\n\nTo: " << OldDest << endl; 165 166 // Let the basic block know that we are letting go of it. Based on this, 167 // it will adjust it's PHI nodes. 168 assert(BI->getParent() && "Terminator not inserted in block!"); 169 OldDest->removePredecessor(BI->getParent()); 170 171 // Set the unconditional destination, and change the insn to be an 172 // unconditional branch. 173 BI->setUnconditionalDest(Destination); 174 return true; 175 } else if (Dest2 == Dest1) { // Conditional branch to same location? 176 // This branch matches something like this: 177 // br bool %cond, label %Dest, label %Dest 178 // and changes it into: br label %Dest 179 180 // Let the basic block know that we are letting go of one copy of it. 181 assert(BI->getParent() && "Terminator not inserted in block!"); 182 Dest1->removePredecessor(BI->getParent()); 183 184 // Change a conditional branch to unconditional. 185 BI->setUnconditionalDest(Dest1); 186 return true; 187 } 188 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { 189 // If we are switching on a constant, we can convert the switch into a 190 // single branch instruction! 191 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); 192 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest 193 BasicBlock *DefaultDest = TheOnlyDest; 194 assert(TheOnlyDest == SI->getDefaultDest() && 195 "Default destination is not successor #0?"); 196 197 // Figure out which case it goes to... 198 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { 199 // Found case matching a constant operand? 200 if (SI->getSuccessorValue(i) == CI) { 201 TheOnlyDest = SI->getSuccessor(i); 202 break; 203 } 204 205 // Check to see if this branch is going to the same place as the default 206 // dest. If so, eliminate it as an explicit compare. 207 if (SI->getSuccessor(i) == DefaultDest) { 208 // Remove this entry... 209 DefaultDest->removePredecessor(SI->getParent()); 210 SI->removeCase(i); 211 --i; --e; // Don't skip an entry... 212 continue; 213 } 214 215 // Otherwise, check to see if the switch only branches to one destination. 216 // We do this by reseting "TheOnlyDest" to null when we find two non-equal 217 // destinations. 218 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; 219 } 220 221 if (CI && !TheOnlyDest) { 222 // Branching on a constant, but not any of the cases, go to the default 223 // successor. 224 TheOnlyDest = SI->getDefaultDest(); 225 } 226 227 // If we found a single destination that we can fold the switch into, do so 228 // now. 229 if (TheOnlyDest) { 230 // Insert the new branch.. 231 new BranchInst(TheOnlyDest, SI); 232 BasicBlock *BB = SI->getParent(); 233 234 // Remove entries from PHI nodes which we no longer branch to... 235 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { 236 // Found case matching a constant operand? 237 BasicBlock *Succ = SI->getSuccessor(i); 238 if (Succ == TheOnlyDest) 239 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest 240 else 241 Succ->removePredecessor(BB); 242 } 243 244 // Delete the old switch... 245 BB->getInstList().erase(SI); 246 return true; 247 } else if (SI->getNumSuccessors() == 2) { 248 // Otherwise, we can fold this switch into a conditional branch 249 // instruction if it has only one non-default destination. 250 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), 251 SI->getSuccessorValue(1), "cond", SI); 252 // Insert the new branch... 253 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); 254 255 // Delete the old switch... 256 SI->getParent()->getInstList().erase(SI); 257 return true; 258 } 259 } 260 return false; 261} 262 263/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a 264/// getelementptr constantexpr, return the constant value being addressed by the 265/// constant expression, or null if something is funny and we can't decide. 266Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 267 ConstantExpr *CE) { 268 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) 269 return 0; // Do not allow stepping over the value! 270 271 // Loop over all of the operands, tracking down which value we are 272 // addressing... 273 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 274 for (++I; I != E; ++I) 275 if (const StructType *STy = dyn_cast<StructType>(*I)) { 276 ConstantInt *CU = cast<ConstantInt>(I.getOperand()); 277 assert(CU->getZExtValue() < STy->getNumElements() && 278 "Struct index out of range!"); 279 unsigned El = (unsigned)CU->getZExtValue(); 280 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { 281 C = CS->getOperand(El); 282 } else if (isa<ConstantAggregateZero>(C)) { 283 C = Constant::getNullValue(STy->getElementType(El)); 284 } else if (isa<UndefValue>(C)) { 285 C = UndefValue::get(STy->getElementType(El)); 286 } else { 287 return 0; 288 } 289 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) { 290 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) { 291 if (CI->getZExtValue() >= ATy->getNumElements()) 292 return 0; 293 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) 294 C = CA->getOperand(CI->getZExtValue()); 295 else if (isa<ConstantAggregateZero>(C)) 296 C = Constant::getNullValue(ATy->getElementType()); 297 else if (isa<UndefValue>(C)) 298 C = UndefValue::get(ATy->getElementType()); 299 else 300 return 0; 301 } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) { 302 if (CI->getZExtValue() >= PTy->getNumElements()) 303 return 0; 304 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) 305 C = CP->getOperand(CI->getZExtValue()); 306 else if (isa<ConstantAggregateZero>(C)) 307 C = Constant::getNullValue(PTy->getElementType()); 308 else if (isa<UndefValue>(C)) 309 C = UndefValue::get(PTy->getElementType()); 310 else 311 return 0; 312 } else { 313 return 0; 314 } 315 } else { 316 return 0; 317 } 318 return C; 319} 320 321 322//===----------------------------------------------------------------------===// 323// Local dead code elimination... 324// 325 326bool llvm::isInstructionTriviallyDead(Instruction *I) { 327 if (!I->use_empty() || isa<TerminatorInst>(I)) return false; 328 329 if (!I->mayWriteToMemory()) return true; 330 331 if (CallInst *CI = dyn_cast<CallInst>(I)) 332 if (Function *F = CI->getCalledFunction()) { 333 unsigned IntrinsicID = F->getIntrinsicID(); 334#define GET_SIDE_EFFECT_INFO 335#include "llvm/Intrinsics.gen" 336#undef GET_SIDE_EFFECT_INFO 337 } 338 return false; 339} 340 341// dceInstruction - Inspect the instruction at *BBI and figure out if it's 342// [trivially] dead. If so, remove the instruction and update the iterator 343// to point to the instruction that immediately succeeded the original 344// instruction. 345// 346bool llvm::dceInstruction(BasicBlock::iterator &BBI) { 347 // Look for un"used" definitions... 348 if (isInstructionTriviallyDead(BBI)) { 349 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye 350 return true; 351 } 352 return false; 353} 354