LLVM API Documentation

Local.h
Go to the documentation of this file.
00001 //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions perform various local transformations to the
00011 // program.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
00016 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
00017 
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/GetElementPtrTypeIterator.h"
00020 #include "llvm/IR/IRBuilder.h"
00021 #include "llvm/IR/Operator.h"
00022 
00023 namespace llvm {
00024 
00025 class User;
00026 class BasicBlock;
00027 class Function;
00028 class BranchInst;
00029 class Instruction;
00030 class DbgDeclareInst;
00031 class StoreInst;
00032 class LoadInst;
00033 class Value;
00034 class Pass;
00035 class PHINode;
00036 class AllocaInst;
00037 class AssumptionTracker;
00038 class ConstantExpr;
00039 class DataLayout;
00040 class TargetLibraryInfo;
00041 class TargetTransformInfo;
00042 class DIBuilder;
00043 class AliasAnalysis;
00044 class DominatorTree;
00045 
00046 template<typename T> class SmallVectorImpl;
00047 
00048 //===----------------------------------------------------------------------===//
00049 //  Local constant propagation.
00050 //
00051 
00052 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
00053 /// constant value, convert it into an unconditional branch to the constant
00054 /// destination.  This is a nontrivial operation because the successors of this
00055 /// basic block must have their PHI nodes updated.
00056 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
00057 /// conditions and indirectbr addresses this might make dead if
00058 /// DeleteDeadConditions is true.
00059 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
00060                             const TargetLibraryInfo *TLI = nullptr);
00061 
00062 //===----------------------------------------------------------------------===//
00063 //  Local dead code elimination.
00064 //
00065 
00066 /// isInstructionTriviallyDead - Return true if the result produced by the
00067 /// instruction is not used, and the instruction has no side effects.
00068 ///
00069 bool isInstructionTriviallyDead(Instruction *I,
00070                                 const TargetLibraryInfo *TLI = nullptr);
00071 
00072 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
00073 /// trivially dead instruction, delete it.  If that makes any of its operands
00074 /// trivially dead, delete them too, recursively.  Return true if any
00075 /// instructions were deleted.
00076 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
00077                                         const TargetLibraryInfo *TLI = nullptr);
00078 
00079 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
00080 /// dead PHI node, due to being a def-use chain of single-use nodes that
00081 /// either forms a cycle or is terminated by a trivially dead instruction,
00082 /// delete it.  If that makes any of its operands trivially dead, delete them
00083 /// too, recursively.  Return true if a change was made.
00084 bool RecursivelyDeleteDeadPHINode(PHINode *PN,
00085                                   const TargetLibraryInfo *TLI = nullptr);
00086 
00087 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
00088 /// simplify any instructions in it and recursively delete dead instructions.
00089 ///
00090 /// This returns true if it changed the code, note that it can delete
00091 /// instructions in other blocks as well in this block.
00092 bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD = nullptr,
00093                                  const TargetLibraryInfo *TLI = nullptr);
00094 
00095 //===----------------------------------------------------------------------===//
00096 //  Control Flow Graph Restructuring.
00097 //
00098 
00099 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
00100 /// method is called when we're about to delete Pred as a predecessor of BB.  If
00101 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
00102 ///
00103 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
00104 /// nodes that collapse into identity values.  For example, if we have:
00105 ///   x = phi(1, 0, 0, 0)
00106 ///   y = and x, z
00107 ///
00108 /// .. and delete the predecessor corresponding to the '1', this will attempt to
00109 /// recursively fold the 'and' to 0.
00110 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
00111                                   DataLayout *TD = nullptr);
00112 
00113 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
00114 /// predecessor is known to have one successor (BB!).  Eliminate the edge
00115 /// between them, moving the instructions in the predecessor into BB.  This
00116 /// deletes the predecessor block.
00117 ///
00118 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = nullptr);
00119 
00120 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
00121 /// unconditional branch, and contains no instructions other than PHI nodes,
00122 /// potential debug intrinsics and the branch.  If possible, eliminate BB by
00123 /// rewriting all the predecessors to branch to the successor block and return
00124 /// true.  If we can't transform, return false.
00125 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
00126 
00127 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
00128 /// nodes in this block. This doesn't try to be clever about PHI nodes
00129 /// which differ only in the order of the incoming values, but instcombine
00130 /// orders them so it usually won't matter.
00131 ///
00132 bool EliminateDuplicatePHINodes(BasicBlock *BB);
00133 
00134 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
00135 /// example, it adjusts branches to branches to eliminate the extra hop, it
00136 /// eliminates unreachable basic blocks, and does other "peephole" optimization
00137 /// of the CFG.  It returns true if a modification was made, possibly deleting
00138 /// the basic block that was pointed to.
00139 ///
00140 bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
00141                  unsigned BonusInstThreshold,
00142                  const DataLayout *TD = nullptr,
00143                  AssumptionTracker *AT = nullptr);
00144 
00145 /// FlatternCFG - This function is used to flatten a CFG.  For
00146 /// example, it uses parallel-and and parallel-or mode to collapse
00147 //  if-conditions and merge if-regions with identical statements.
00148 ///
00149 bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = nullptr);
00150 
00151 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
00152 /// and if a predecessor branches to us and one of our successors, fold the
00153 /// setcc into the predecessor and use logical operations to pick the right
00154 /// destination.
00155 bool FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL = nullptr,
00156                             unsigned BonusInstThreshold = 1);
00157 
00158 /// DemoteRegToStack - This function takes a virtual register computed by an
00159 /// Instruction and replaces it with a slot in the stack frame, allocated via
00160 /// alloca.  This allows the CFG to be changed around without fear of
00161 /// invalidating the SSA information for the value.  It returns the pointer to
00162 /// the alloca inserted to create a stack slot for X.
00163 ///
00164 AllocaInst *DemoteRegToStack(Instruction &X,
00165                              bool VolatileLoads = false,
00166                              Instruction *AllocaPoint = nullptr);
00167 
00168 /// DemotePHIToStack - This function takes a virtual register computed by a phi
00169 /// node and replaces it with a slot in the stack frame, allocated via alloca.
00170 /// The phi node is deleted and it returns the pointer to the alloca inserted.
00171 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = nullptr);
00172 
00173 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
00174 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
00175 /// and it is more than the alignment of the ultimate object, see if we can
00176 /// increase the alignment of the ultimate object, making this check succeed.
00177 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
00178                                     const DataLayout *TD = nullptr,
00179                                     AssumptionTracker *AT = nullptr,
00180                                     const Instruction *CxtI = nullptr,
00181                                     const DominatorTree *DT = nullptr);
00182 
00183 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
00184 static inline unsigned getKnownAlignment(Value *V,
00185                                          const DataLayout *TD = nullptr,
00186                                          AssumptionTracker *AT = nullptr,
00187                                          const Instruction *CxtI = nullptr,
00188                                          const DominatorTree *DT = nullptr) {
00189   return getOrEnforceKnownAlignment(V, 0, TD, AT, CxtI, DT);
00190 }
00191 
00192 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
00193 /// code necessary to compute the offset from the base pointer (without adding
00194 /// in the base pointer).  Return the result as a signed integer of intptr size.
00195 /// When NoAssumptions is true, no assumptions about index computation not
00196 /// overflowing is made.
00197 template<typename IRBuilderTy>
00198 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP,
00199                      bool NoAssumptions = false) {
00200   GEPOperator *GEPOp = cast<GEPOperator>(GEP);
00201   Type *IntPtrTy = TD.getIntPtrType(GEP->getType());
00202   Value *Result = Constant::getNullValue(IntPtrTy);
00203 
00204   // If the GEP is inbounds, we know that none of the addressing operations will
00205   // overflow in an unsigned sense.
00206   bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
00207 
00208   // Build a mask for high order bits.
00209   unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
00210   uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
00211 
00212   gep_type_iterator GTI = gep_type_begin(GEP);
00213   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
00214        ++i, ++GTI) {
00215     Value *Op = *i;
00216     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
00217     if (Constant *OpC = dyn_cast<Constant>(Op)) {
00218       if (OpC->isZeroValue())
00219         continue;
00220 
00221       // Handle a struct index, which adds its field offset to the pointer.
00222       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00223         if (OpC->getType()->isVectorTy())
00224           OpC = OpC->getSplatValue();
00225 
00226         uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
00227         Size = TD.getStructLayout(STy)->getElementOffset(OpValue);
00228 
00229         if (Size)
00230           Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
00231                                       GEP->getName()+".offs");
00232         continue;
00233       }
00234 
00235       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
00236       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
00237       Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
00238       // Emit an add instruction.
00239       Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
00240       continue;
00241     }
00242     // Convert to correct type.
00243     if (Op->getType() != IntPtrTy)
00244       Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
00245     if (Size != 1) {
00246       // We'll let instcombine(mul) convert this to a shl if possible.
00247       Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
00248                               GEP->getName()+".idx", isInBounds /*NUW*/);
00249     }
00250 
00251     // Emit an add instruction.
00252     Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
00253   }
00254   return Result;
00255 }
00256 
00257 ///===---------------------------------------------------------------------===//
00258 ///  Dbg Intrinsic utilities
00259 ///
00260 
00261 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
00262 /// that has an associated llvm.dbg.decl intrinsic.
00263 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00264                                      StoreInst *SI, DIBuilder &Builder);
00265 
00266 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
00267 /// that has an associated llvm.dbg.decl intrinsic.
00268 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
00269                                      LoadInst *LI, DIBuilder &Builder);
00270 
00271 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
00272 /// of llvm.dbg.value intrinsics.
00273 bool LowerDbgDeclare(Function &F);
00274 
00275 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
00276 /// an alloca, if any.
00277 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
00278 
00279 /// replaceDbgDeclareForAlloca - Replaces llvm.dbg.declare instruction when
00280 /// alloca is replaced with a new value.
00281 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
00282                                 DIBuilder &Builder);
00283 
00284 /// \brief Remove all blocks that can not be reached from the function's entry.
00285 ///
00286 /// Returns true if any basic block was removed.
00287 bool removeUnreachableBlocks(Function &F);
00288 
00289 /// \brief Combine the metadata of two instructions so that K can replace J
00290 ///
00291 /// Metadata not listed as known via KnownIDs is removed
00292 void combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs);
00293 
00294 } // End llvm namespace
00295 
00296 #endif