1 //===- GEPSplitter.cpp - Split complex GEPs into simple ones --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This function breaks GEPs with more than 2 non-zero operands into smaller
11 // GEPs each with no more than 2 non-zero operands. This exposes redundancy
12 // between GEPs with common initial operand sequences.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "split-geps"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
25 class GEPSplitter
: public FunctionPass
{
26 virtual bool runOnFunction(Function
&F
);
27 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const;
29 static char ID
; // Pass identification, replacement for typeid
30 explicit GEPSplitter() : FunctionPass(ID
) {
31 initializeGEPSplitterPass(*PassRegistry::getPassRegistry());
36 char GEPSplitter::ID
= 0;
37 INITIALIZE_PASS(GEPSplitter
, "split-geps",
38 "split complex GEPs into simple GEPs", false, false)
40 FunctionPass
*llvm::createGEPSplitterPass() {
41 return new GEPSplitter();
44 bool GEPSplitter::runOnFunction(Function
&F
) {
47 // Visit each GEP instruction.
48 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
)
49 for (BasicBlock::iterator II
= I
->begin(), IE
= I
->end(); II
!= IE
; )
50 if (GetElementPtrInst
*GEP
= dyn_cast
<GetElementPtrInst
>(II
++)) {
51 unsigned NumOps
= GEP
->getNumOperands();
52 // Ignore GEPs which are already simple.
55 bool FirstIndexIsZero
= isa
<ConstantInt
>(GEP
->getOperand(1)) &&
56 cast
<ConstantInt
>(GEP
->getOperand(1))->isZero();
57 if (NumOps
== 3 && FirstIndexIsZero
)
59 // The first index is special and gets expanded with a 2-operand GEP
60 // (unless it's zero, in which case we can skip this).
61 Value
*NewGEP
= FirstIndexIsZero
?
63 GetElementPtrInst::Create(GEP
->getOperand(0), GEP
->getOperand(1),
65 // All remaining indices get expanded with a 3-operand GEP with zero
66 // as the second operand.
68 Idxs
[0] = ConstantInt::get(Type::getInt64Ty(F
.getContext()), 0);
69 for (unsigned i
= 2; i
!= NumOps
; ++i
) {
70 Idxs
[1] = GEP
->getOperand(i
);
71 NewGEP
= GetElementPtrInst::Create(NewGEP
, Idxs
, Idxs
+2, "tmp", GEP
);
73 GEP
->replaceAllUsesWith(NewGEP
);
74 GEP
->eraseFromParent();
81 void GEPSplitter::getAnalysisUsage(AnalysisUsage
&AU
) const {