Analysis.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines several CodeGen-specific LLVM IR analysis utilties.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/Analysis.h"
  14. #include "llvm/Analysis/ValueTracking.h"
  15. #include "llvm/CodeGen/MachineFunction.h"
  16. #include "llvm/CodeGen/SelectionDAG.h"
  17. #include "llvm/DataLayout.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/Function.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/IntrinsicInst.h"
  22. #include "llvm/LLVMContext.h"
  23. #include "llvm/Module.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include "llvm/Support/MathExtras.h"
  26. #include "llvm/Target/TargetLowering.h"
  27. #include "llvm/Target/TargetOptions.h"
  28. using namespace llvm;
  29. /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
  30. /// of insertvalue or extractvalue indices that identify a member, return
  31. /// the linearized index of the start of the member.
  32. ///
  33. unsigned llvm::ComputeLinearIndex(Type *Ty,
  34. const unsigned *Indices,
  35. const unsigned *IndicesEnd,
  36. unsigned CurIndex) {
  37. // Base case: We're done.
  38. if (Indices && Indices == IndicesEnd)
  39. return CurIndex;
  40. // Given a struct type, recursively traverse the elements.
  41. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  42. for (StructType::element_iterator EB = STy->element_begin(),
  43. EI = EB,
  44. EE = STy->element_end();
  45. EI != EE; ++EI) {
  46. if (Indices && *Indices == unsigned(EI - EB))
  47. return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
  48. CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex);
  49. }
  50. return CurIndex;
  51. }
  52. // Given an array type, recursively traverse the elements.
  53. else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  54. Type *EltTy = ATy->getElementType();
  55. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
  56. if (Indices && *Indices == i)
  57. return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
  58. CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex);
  59. }
  60. return CurIndex;
  61. }
  62. // We haven't found the type we're looking for, so keep searching.
  63. return CurIndex + 1;
  64. }
  65. /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
  66. /// EVTs that represent all the individual underlying
  67. /// non-aggregate types that comprise it.
  68. ///
  69. /// If Offsets is non-null, it points to a vector to be filled in
  70. /// with the in-memory offsets of each of the individual values.
  71. ///
  72. void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
  73. SmallVectorImpl<EVT> &ValueVTs,
  74. SmallVectorImpl<uint64_t> *Offsets,
  75. uint64_t StartingOffset) {
  76. // Given a struct type, recursively traverse the elements.
  77. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  78. const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
  79. for (StructType::element_iterator EB = STy->element_begin(),
  80. EI = EB,
  81. EE = STy->element_end();
  82. EI != EE; ++EI)
  83. ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
  84. StartingOffset + SL->getElementOffset(EI - EB));
  85. return;
  86. }
  87. // Given an array type, recursively traverse the elements.
  88. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  89. Type *EltTy = ATy->getElementType();
  90. uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
  91. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  92. ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
  93. StartingOffset + i * EltSize);
  94. return;
  95. }
  96. // Interpret void as zero return values.
  97. if (Ty->isVoidTy())
  98. return;
  99. // Base case: we can get an EVT for this LLVM IR type.
  100. ValueVTs.push_back(TLI.getValueType(Ty));
  101. if (Offsets)
  102. Offsets->push_back(StartingOffset);
  103. }
  104. /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
  105. GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
  106. V = V->stripPointerCasts();
  107. GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
  108. if (GV && GV->getName() == "llvm.eh.catch.all.value") {
  109. assert(GV->hasInitializer() &&
  110. "The EH catch-all value must have an initializer");
  111. Value *Init = GV->getInitializer();
  112. GV = dyn_cast<GlobalVariable>(Init);
  113. if (!GV) V = cast<ConstantPointerNull>(Init);
  114. }
  115. assert((GV || isa<ConstantPointerNull>(V)) &&
  116. "TypeInfo must be a global variable or NULL");
  117. return GV;
  118. }
  119. /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
  120. /// processed uses a memory 'm' constraint.
  121. bool
  122. llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
  123. const TargetLowering &TLI) {
  124. for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
  125. InlineAsm::ConstraintInfo &CI = CInfos[i];
  126. for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
  127. TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
  128. if (CType == TargetLowering::C_Memory)
  129. return true;
  130. }
  131. // Indirect operand accesses access memory.
  132. if (CI.isIndirect)
  133. return true;
  134. }
  135. return false;
  136. }
  137. /// getFCmpCondCode - Return the ISD condition code corresponding to
  138. /// the given LLVM IR floating-point condition code. This includes
  139. /// consideration of global floating-point math flags.
  140. ///
  141. ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
  142. switch (Pred) {
  143. case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
  144. case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
  145. case FCmpInst::FCMP_OGT: return ISD::SETOGT;
  146. case FCmpInst::FCMP_OGE: return ISD::SETOGE;
  147. case FCmpInst::FCMP_OLT: return ISD::SETOLT;
  148. case FCmpInst::FCMP_OLE: return ISD::SETOLE;
  149. case FCmpInst::FCMP_ONE: return ISD::SETONE;
  150. case FCmpInst::FCMP_ORD: return ISD::SETO;
  151. case FCmpInst::FCMP_UNO: return ISD::SETUO;
  152. case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
  153. case FCmpInst::FCMP_UGT: return ISD::SETUGT;
  154. case FCmpInst::FCMP_UGE: return ISD::SETUGE;
  155. case FCmpInst::FCMP_ULT: return ISD::SETULT;
  156. case FCmpInst::FCMP_ULE: return ISD::SETULE;
  157. case FCmpInst::FCMP_UNE: return ISD::SETUNE;
  158. case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
  159. default: llvm_unreachable("Invalid FCmp predicate opcode!");
  160. }
  161. }
  162. ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
  163. switch (CC) {
  164. case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
  165. case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
  166. case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
  167. case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
  168. case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
  169. case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
  170. default: return CC;
  171. }
  172. }
  173. /// getICmpCondCode - Return the ISD condition code corresponding to
  174. /// the given LLVM IR integer condition code.
  175. ///
  176. ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
  177. switch (Pred) {
  178. case ICmpInst::ICMP_EQ: return ISD::SETEQ;
  179. case ICmpInst::ICMP_NE: return ISD::SETNE;
  180. case ICmpInst::ICMP_SLE: return ISD::SETLE;
  181. case ICmpInst::ICMP_ULE: return ISD::SETULE;
  182. case ICmpInst::ICMP_SGE: return ISD::SETGE;
  183. case ICmpInst::ICMP_UGE: return ISD::SETUGE;
  184. case ICmpInst::ICMP_SLT: return ISD::SETLT;
  185. case ICmpInst::ICMP_ULT: return ISD::SETULT;
  186. case ICmpInst::ICMP_SGT: return ISD::SETGT;
  187. case ICmpInst::ICMP_UGT: return ISD::SETUGT;
  188. default:
  189. llvm_unreachable("Invalid ICmp predicate opcode!");
  190. }
  191. }
  192. /// getNoopInput - If V is a noop (i.e., lowers to no machine code), look
  193. /// through it (and any transitive noop operands to it) and return its input
  194. /// value. This is used to determine if a tail call can be formed.
  195. ///
  196. static const Value *getNoopInput(const Value *V, const TargetLowering &TLI) {
  197. // If V is not an instruction, it can't be looked through.
  198. const Instruction *I = dyn_cast<Instruction>(V);
  199. if (I == 0 || !I->hasOneUse() || I->getNumOperands() == 0) return V;
  200. Value *Op = I->getOperand(0);
  201. // Look through truly no-op truncates.
  202. if (isa<TruncInst>(I) &&
  203. TLI.isTruncateFree(I->getOperand(0)->getType(), I->getType()))
  204. return getNoopInput(I->getOperand(0), TLI);
  205. // Look through truly no-op bitcasts.
  206. if (isa<BitCastInst>(I)) {
  207. // No type change at all.
  208. if (Op->getType() == I->getType())
  209. return getNoopInput(Op, TLI);
  210. // Pointer to pointer cast.
  211. if (Op->getType()->isPointerTy() && I->getType()->isPointerTy())
  212. return getNoopInput(Op, TLI);
  213. if (isa<VectorType>(Op->getType()) && isa<VectorType>(I->getType()) &&
  214. TLI.isTypeLegal(EVT::getEVT(Op->getType())) &&
  215. TLI.isTypeLegal(EVT::getEVT(I->getType())))
  216. return getNoopInput(Op, TLI);
  217. }
  218. // Look through inttoptr.
  219. if (isa<IntToPtrInst>(I) && !isa<VectorType>(I->getType())) {
  220. // Make sure this isn't a truncating or extending cast. We could support
  221. // this eventually, but don't bother for now.
  222. if (TLI.getPointerTy().getSizeInBits() ==
  223. cast<IntegerType>(Op->getType())->getBitWidth())
  224. return getNoopInput(Op, TLI);
  225. }
  226. // Look through ptrtoint.
  227. if (isa<PtrToIntInst>(I) && !isa<VectorType>(I->getType())) {
  228. // Make sure this isn't a truncating or extending cast. We could support
  229. // this eventually, but don't bother for now.
  230. if (TLI.getPointerTy().getSizeInBits() ==
  231. cast<IntegerType>(I->getType())->getBitWidth())
  232. return getNoopInput(Op, TLI);
  233. }
  234. // Otherwise it's not something we can look through.
  235. return V;
  236. }
  237. /// Test if the given instruction is in a position to be optimized
  238. /// with a tail-call. This roughly means that it's in a block with
  239. /// a return and there's nothing that needs to be scheduled
  240. /// between it and the return.
  241. ///
  242. /// This function only tests target-independent requirements.
  243. bool llvm::isInTailCallPosition(ImmutableCallSite CS, Attributes CalleeRetAttr,
  244. const TargetLowering &TLI) {
  245. const Instruction *I = CS.getInstruction();
  246. const BasicBlock *ExitBB = I->getParent();
  247. const TerminatorInst *Term = ExitBB->getTerminator();
  248. const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
  249. // The block must end in a return statement or unreachable.
  250. //
  251. // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
  252. // an unreachable, for now. The way tailcall optimization is currently
  253. // implemented means it will add an epilogue followed by a jump. That is
  254. // not profitable. Also, if the callee is a special function (e.g.
  255. // longjmp on x86), it can end up causing miscompilation that has not
  256. // been fully understood.
  257. if (!Ret &&
  258. (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
  259. !isa<UnreachableInst>(Term)))
  260. return false;
  261. // If I will have a chain, make sure no other instruction that will have a
  262. // chain interposes between I and the return.
  263. if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
  264. !isSafeToSpeculativelyExecute(I))
  265. for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
  266. --BBI) {
  267. if (&*BBI == I)
  268. break;
  269. // Debug info intrinsics do not get in the way of tail call optimization.
  270. if (isa<DbgInfoIntrinsic>(BBI))
  271. continue;
  272. if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
  273. !isSafeToSpeculativelyExecute(BBI))
  274. return false;
  275. }
  276. // If the block ends with a void return or unreachable, it doesn't matter
  277. // what the call's return type is.
  278. if (!Ret || Ret->getNumOperands() == 0) return true;
  279. // If the return value is undef, it doesn't matter what the call's
  280. // return type is.
  281. if (isa<UndefValue>(Ret->getOperand(0))) return true;
  282. // Conservatively require the attributes of the call to match those of
  283. // the return. Ignore noalias because it doesn't affect the call sequence.
  284. const Function *F = ExitBB->getParent();
  285. Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
  286. if (AttrBuilder(CalleeRetAttr).removeAttribute(Attributes::NoAlias) !=
  287. AttrBuilder(CallerRetAttr).removeAttribute(Attributes::NoAlias))
  288. return false;
  289. // It's not safe to eliminate the sign / zero extension of the return value.
  290. if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
  291. CallerRetAttr.hasAttribute(Attributes::SExt))
  292. return false;
  293. // Otherwise, make sure the unmodified return value of I is the return value.
  294. // We handle two cases: multiple return values + scalars.
  295. Value *RetVal = Ret->getOperand(0);
  296. if (!isa<InsertValueInst>(RetVal) || !isa<StructType>(RetVal->getType()))
  297. // Handle scalars first.
  298. return getNoopInput(Ret->getOperand(0), TLI) == I;
  299. // If this is an aggregate return, look through the insert/extract values and
  300. // see if each is transparent.
  301. for (unsigned i = 0, e =cast<StructType>(RetVal->getType())->getNumElements();
  302. i != e; ++i) {
  303. const Value *InScalar = FindInsertedValue(RetVal, i);
  304. if (InScalar == 0) return false;
  305. InScalar = getNoopInput(InScalar, TLI);
  306. // If the scalar value being inserted is an extractvalue of the right index
  307. // from the call, then everything is good.
  308. const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(InScalar);
  309. if (EVI == 0 || EVI->getOperand(0) != I || EVI->getNumIndices() != 1 ||
  310. EVI->getIndices()[0] != i)
  311. return false;
  312. }
  313. return true;
  314. }
  315. bool llvm::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
  316. SDValue &Chain, const TargetLowering &TLI) {
  317. const Function *F = DAG.getMachineFunction().getFunction();
  318. // Conservatively require the attributes of the call to match those of
  319. // the return. Ignore noalias because it doesn't affect the call sequence.
  320. Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
  321. if (AttrBuilder(CallerRetAttr)
  322. .removeAttribute(Attributes::NoAlias).hasAttributes())
  323. return false;
  324. // It's not safe to eliminate the sign / zero extension of the return value.
  325. if (CallerRetAttr.hasAttribute(Attributes::ZExt) ||
  326. CallerRetAttr.hasAttribute(Attributes::SExt))
  327. return false;
  328. // Check if the only use is a function return node.
  329. return TLI.isUsedByReturnOnly(Node, Chain);
  330. }