Add a getOffsetOf, for building a target-independent expression for
authorDan Gohman <gohman@apple.com>
Sun, 16 Aug 2009 21:26:11 +0000 (21:26 +0000)
committerDan Gohman <gohman@apple.com>
Sun, 16 Aug 2009 21:26:11 +0000 (21:26 +0000)
offsetof, similar to getSizeOf for sizeof.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@79208 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Constants.h
lib/VMCore/Constants.cpp

index e26bb62c357ba4d774b7c59a0b75c8a8a9ab71ce..a66773c0b5301d89fb64abf661ee75480e44f3d9 100644 (file)
@@ -602,6 +602,11 @@ public:
   /// independent way (Note: the return type is an i64).
   ///
   static Constant* getSizeOf(const Type* Ty);
+
+  /// getOffsetOf constant expr - computes the offset of a field in a target
+  /// independent way (Note: the return type is an i64).
+  ///
+  static Constant* getOffsetOf(const StructType* Ty, unsigned FieldNo);
   
   static Constant* getNeg(Constant* C);
   static Constant* getFNeg(Constant* C);
index 647bc1225a29016c067b1a5f24880ef552dadce5..f820033932d5fa396bed1c4bfb1be0343301c85b 100644 (file)
@@ -1391,6 +1391,18 @@ Constant* ConstantExpr::getAlignOf(const Type* Ty) {
                  Type::getInt32Ty(Ty->getContext()));
 }
 
+Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
+  // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
+  // Note that a non-inbounds gep is used, as null isn't within any object.
+  Constant *GEPIdx[] = {
+    ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
+    ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
+  };
+  Constant *GEP = getGetElementPtr(
+                Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
+  return getCast(Instruction::PtrToInt, GEP,
+                 Type::getInt64Ty(STy->getContext()));
+}
 
 Constant *ConstantExpr::getCompare(unsigned short pred, 
                             Constant *C1, Constant *C2) {