blob: 7a1cbdeb1eb4918c916b04632433a8f5794ed843 [file] [log] [blame]
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
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 contains code to emit Constant Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Daniel Dunbar2924ade2010-03-30 22:26:10 +000018#include "CGRecordLayout.h"
Chris Lattnerf6b24ea2008-10-06 05:59:01 +000019#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson4c98efd2009-07-24 15:20:52 +000021#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000024#include "llvm/Constants.h"
25#include "llvm/Function.h"
26#include "llvm/GlobalVariable.h"
Eli Friedmana8234002008-05-30 10:24:46 +000027#include "llvm/Target/TargetData.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000028using namespace clang;
29using namespace CodeGen;
30
Chris Lattnereba3e5a2010-04-13 17:45:57 +000031//===----------------------------------------------------------------------===//
32// ConstStructBuilder
33//===----------------------------------------------------------------------===//
34
35namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000036class ConstStructBuilder {
Anders Carlsson4c98efd2009-07-24 15:20:52 +000037 CodeGenModule &CGM;
38 CodeGenFunction *CGF;
39
Mike Stump1eb44332009-09-09 15:08:12 +000040 bool Packed;
Ken Dyckdc496392011-03-17 01:33:18 +000041 CharUnits NextFieldOffsetInChars;
Ken Dyck7d2f9d52011-03-18 01:26:17 +000042 CharUnits LLVMStructAlignment;
Anders Carlsson4c98efd2009-07-24 15:20:52 +000043 std::vector<llvm::Constant *> Elements;
Chris Lattnereba3e5a2010-04-13 17:45:57 +000044public:
45 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
46 InitListExpr *ILE);
47
48private:
Anders Carlsson4c98efd2009-07-24 15:20:52 +000049 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
Ken Dyckdc496392011-03-17 01:33:18 +000050 : CGM(CGM), CGF(CGF), Packed(false),
51 NextFieldOffsetInChars(CharUnits::Zero()),
Ken Dyck7d2f9d52011-03-18 01:26:17 +000052 LLVMStructAlignment(CharUnits::One()) { }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000053
Mike Stump1eb44332009-09-09 15:08:12 +000054 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
Chris Lattner8ce9e452010-04-13 18:16:19 +000055 llvm::Constant *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000056
Chris Lattner18806662010-07-05 17:04:23 +000057 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
58 llvm::ConstantInt *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000059
Ken Dyckc29ea8f2011-03-11 23:42:54 +000060 void AppendPadding(CharUnits PadSize);
Mike Stump1eb44332009-09-09 15:08:12 +000061
Ken Dyck106ca042011-03-11 02:17:05 +000062 void AppendTailPadding(CharUnits RecordSize);
Anders Carlssond24393b2009-07-27 01:23:51 +000063
Chris Lattnereba3e5a2010-04-13 17:45:57 +000064 void ConvertStructToPacked();
Anders Carlsson31f2f9c2009-10-02 02:15:20 +000065
Chris Lattnereba3e5a2010-04-13 17:45:57 +000066 bool Build(InitListExpr *ILE);
Mike Stump1eb44332009-09-09 15:08:12 +000067
Ken Dyck7d2f9d52011-03-18 01:26:17 +000068 CharUnits getAlignment(const llvm::Constant *C) const {
69 if (Packed) return CharUnits::One();
70 return CharUnits::fromQuantity(
71 CGM.getTargetData().getABITypeAlignment(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000072 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Ken Dyck15c152e2011-03-18 01:12:13 +000074 CharUnits getSizeInChars(const llvm::Constant *C) const {
75 return CharUnits::fromQuantity(
76 CGM.getTargetData().getTypeAllocSize(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000077 }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000078};
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattnereba3e5a2010-04-13 17:45:57 +000080bool ConstStructBuilder::
Chris Lattner8ce9e452010-04-13 18:16:19 +000081AppendField(const FieldDecl *Field, uint64_t FieldOffset,
82 llvm::Constant *InitCst) {
Ken Dyck6925cc42011-03-15 01:09:02 +000083
84 const ASTContext &Context = CGM.getContext();
85
86 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000087
Ken Dyckdc496392011-03-17 01:33:18 +000088 assert(NextFieldOffsetInChars <= FieldOffsetInChars
Chris Lattnereba3e5a2010-04-13 17:45:57 +000089 && "Field offset mismatch!");
90
Ken Dyck7d2f9d52011-03-18 01:26:17 +000091 CharUnits FieldAlignment = getAlignment(InitCst);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000092
93 // Round up the field offset to the alignment of the field type.
Ken Dyckdc496392011-03-17 01:33:18 +000094 CharUnits AlignedNextFieldOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +000095 NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000096
Ken Dyckdc496392011-03-17 01:33:18 +000097 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +000098 assert(!Packed && "Alignment is wrong even with a packed struct!");
99
100 // Convert the struct to a packed struct.
101 ConvertStructToPacked();
102
Ken Dyckdc496392011-03-17 01:33:18 +0000103 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000104 }
105
Ken Dyckdc496392011-03-17 01:33:18 +0000106 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000107 // We need to append padding.
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000108 AppendPadding(
Ken Dyckdc496392011-03-17 01:33:18 +0000109 FieldOffsetInChars - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000110
Ken Dyckdc496392011-03-17 01:33:18 +0000111 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000112 "Did not add enough padding!");
113
Ken Dyckdc496392011-03-17 01:33:18 +0000114 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000115 }
116
117 // Add the field.
Chris Lattner8ce9e452010-04-13 18:16:19 +0000118 Elements.push_back(InitCst);
Ken Dyckdc496392011-03-17 01:33:18 +0000119 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
Ken Dyck15c152e2011-03-18 01:12:13 +0000120 getSizeInChars(InitCst);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000121
122 if (Packed)
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000123 assert(LLVMStructAlignment == CharUnits::One() &&
124 "Packed struct not byte-aligned!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000125 else
126 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
127
128 return true;
129}
130
Chris Lattner18806662010-07-05 17:04:23 +0000131void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
132 uint64_t FieldOffset,
133 llvm::ConstantInt *CI) {
Ken Dyckf004da42011-03-12 12:03:11 +0000134 const ASTContext &Context = CGM.getContext();
Ken Dyck4f318c02011-03-19 00:57:28 +0000135 const uint64_t CharWidth = Context.getCharWidth();
Ken Dyckdc496392011-03-17 01:33:18 +0000136 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
137 if (FieldOffset > NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000138 // We need to add padding.
Ken Dyckf004da42011-03-12 12:03:11 +0000139 CharUnits PadSize = Context.toCharUnitsFromBits(
Ken Dyckdc496392011-03-17 01:33:18 +0000140 llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000141 Context.getTargetInfo().getCharAlign()));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000142
Ken Dyckf004da42011-03-12 12:03:11 +0000143 AppendPadding(PadSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000144 }
145
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000146 uint64_t FieldSize = Field->getBitWidthValue(Context);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000147
148 llvm::APInt FieldValue = CI->getValue();
149
150 // Promote the size of FieldValue if necessary
151 // FIXME: This should never occur, but currently it can because initializer
152 // constants are cast to bool, and because clang is not enforcing bitfield
153 // width limits.
154 if (FieldSize > FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000155 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000156
157 // Truncate the size of FieldValue to the bit field size.
158 if (FieldSize < FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000159 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000160
Ken Dyckdc496392011-03-17 01:33:18 +0000161 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
162 if (FieldOffset < NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000163 // Either part of the field or the entire field can go into the previous
164 // byte.
165 assert(!Elements.empty() && "Elements can't be empty!");
166
Ken Dyckdc496392011-03-17 01:33:18 +0000167 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000168
169 bool FitsCompletelyInPreviousByte =
170 BitsInPreviousByte >= FieldValue.getBitWidth();
171
172 llvm::APInt Tmp = FieldValue;
173
174 if (!FitsCompletelyInPreviousByte) {
175 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
176
177 if (CGM.getTargetData().isBigEndian()) {
178 Tmp = Tmp.lshr(NewFieldWidth);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000179 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000180
181 // We want the remaining high bits.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000182 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000183 } else {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000184 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000185
186 // We want the remaining low bits.
187 FieldValue = FieldValue.lshr(BitsInPreviousByte);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000188 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000189 }
190 }
191
Ken Dyck4f318c02011-03-19 00:57:28 +0000192 Tmp = Tmp.zext(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000193 if (CGM.getTargetData().isBigEndian()) {
194 if (FitsCompletelyInPreviousByte)
195 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
196 } else {
Ken Dyck4f318c02011-03-19 00:57:28 +0000197 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000198 }
199
Chris Lattner2bc00252010-07-05 18:03:30 +0000200 // 'or' in the bits that go into the previous byte.
201 llvm::Value *LastElt = Elements.back();
202 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000203 Tmp |= Val->getValue();
Chris Lattner2bc00252010-07-05 18:03:30 +0000204 else {
205 assert(isa<llvm::UndefValue>(LastElt));
206 // If there is an undef field that we're adding to, it can either be a
207 // scalar undef (in which case, we just replace it with our field) or it
208 // is an array. If it is an array, we have to pull one byte off the
209 // array so that the other undef bytes stay around.
210 if (!isa<llvm::IntegerType>(LastElt->getType())) {
211 // The undef padding will be a multibyte array, create a new smaller
212 // padding and then an hole for our i8 to get plopped into.
213 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
214 "Expected array padding of undefs");
Chris Lattner2acc6e32011-07-18 04:24:23 +0000215 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
Ken Dyck4f318c02011-03-19 00:57:28 +0000216 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000217 AT->getNumElements() != 0 &&
218 "Expected non-empty array padding of undefs");
219
220 // Remove the padding array.
Ken Dyckdc496392011-03-17 01:33:18 +0000221 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
Chris Lattner2bc00252010-07-05 18:03:30 +0000222 Elements.pop_back();
223
224 // Add the padding back in two chunks.
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000225 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
226 AppendPadding(CharUnits::One());
Chris Lattner2bc00252010-07-05 18:03:30 +0000227 assert(isa<llvm::UndefValue>(Elements.back()) &&
Ken Dyck4f318c02011-03-19 00:57:28 +0000228 Elements.back()->getType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000229 "Padding addition didn't work right");
230 }
231 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000232
233 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
234
235 if (FitsCompletelyInPreviousByte)
Chris Lattner18806662010-07-05 17:04:23 +0000236 return;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000237 }
238
Ken Dyck4f318c02011-03-19 00:57:28 +0000239 while (FieldValue.getBitWidth() > CharWidth) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000240 llvm::APInt Tmp;
241
242 if (CGM.getTargetData().isBigEndian()) {
243 // We want the high bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000244 Tmp =
245 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000246 } else {
247 // We want the low bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000248 Tmp = FieldValue.trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000249
Ken Dyck4f318c02011-03-19 00:57:28 +0000250 FieldValue = FieldValue.lshr(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000251 }
252
253 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
Ken Dyck199c1892011-03-19 01:28:06 +0000254 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000255
Ken Dyck4f318c02011-03-19 00:57:28 +0000256 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000257 }
258
259 assert(FieldValue.getBitWidth() > 0 &&
260 "Should have at least one bit left!");
Ken Dyck4f318c02011-03-19 00:57:28 +0000261 assert(FieldValue.getBitWidth() <= CharWidth &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000262 "Should not have more than a byte left!");
263
Ken Dyck4f318c02011-03-19 00:57:28 +0000264 if (FieldValue.getBitWidth() < CharWidth) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000265 if (CGM.getTargetData().isBigEndian()) {
266 unsigned BitWidth = FieldValue.getBitWidth();
267
Ken Dyck4f318c02011-03-19 00:57:28 +0000268 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000269 } else
Ken Dyck4f318c02011-03-19 00:57:28 +0000270 FieldValue = FieldValue.zext(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000271 }
272
273 // Append the last element.
274 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
275 FieldValue));
Ken Dyck199c1892011-03-19 01:28:06 +0000276 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000277}
278
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000279void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
280 if (PadSize.isZero())
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000281 return;
282
Chris Lattner2acc6e32011-07-18 04:24:23 +0000283 llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000284 if (PadSize > CharUnits::One())
285 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000286
Nuno Lopescdb30b42010-04-16 20:56:35 +0000287 llvm::Constant *C = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000288 Elements.push_back(C);
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000289 assert(getAlignment(C) == CharUnits::One() &&
290 "Padding must have 1 byte alignment!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000291
Ken Dyck15c152e2011-03-18 01:12:13 +0000292 NextFieldOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000293}
294
Ken Dyck106ca042011-03-11 02:17:05 +0000295void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
Ken Dyckdc496392011-03-17 01:33:18 +0000296 assert(NextFieldOffsetInChars <= RecordSize &&
Ken Dyck106ca042011-03-11 02:17:05 +0000297 "Size mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000298
Ken Dyckdc496392011-03-17 01:33:18 +0000299 AppendPadding(RecordSize - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000300}
301
302void ConstStructBuilder::ConvertStructToPacked() {
303 std::vector<llvm::Constant *> PackedElements;
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000304 CharUnits ElementOffsetInChars = CharUnits::Zero();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000305
306 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
307 llvm::Constant *C = Elements[i];
308
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000309 CharUnits ElementAlign = CharUnits::fromQuantity(
310 CGM.getTargetData().getABITypeAlignment(C->getType()));
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000311 CharUnits AlignedElementOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000312 ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000313
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000314 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000315 // We need some padding.
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000316 CharUnits NumChars =
317 AlignedElementOffsetInChars - ElementOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000318
Chris Lattner2acc6e32011-07-18 04:24:23 +0000319 llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000320 if (NumChars > CharUnits::One())
321 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000322
Nuno Lopescdb30b42010-04-16 20:56:35 +0000323 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000324 PackedElements.push_back(Padding);
Ken Dyck15c152e2011-03-18 01:12:13 +0000325 ElementOffsetInChars += getSizeInChars(Padding);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000326 }
327
328 PackedElements.push_back(C);
Ken Dyck15c152e2011-03-18 01:12:13 +0000329 ElementOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000330 }
331
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000332 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000333 "Packing the struct changed its size!");
334
335 Elements = PackedElements;
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000336 LLVMStructAlignment = CharUnits::One();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000337 Packed = true;
338}
339
340bool ConstStructBuilder::Build(InitListExpr *ILE) {
341 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
342 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
343
344 unsigned FieldNo = 0;
345 unsigned ElementNo = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000346 const FieldDecl *LastFD = 0;
347 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
348
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000349 for (RecordDecl::field_iterator Field = RD->field_begin(),
Chris Lattner8ce9e452010-04-13 18:16:19 +0000350 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000351 if (IsMsStruct) {
352 // Zero-length bitfields following non-bitfield members are
353 // ignored:
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000354 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((*Field), LastFD)) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000355 --FieldNo;
356 continue;
357 }
358 LastFD = (*Field);
359 }
Chris Lattner8ce9e452010-04-13 18:16:19 +0000360
361 // If this is a union, skip all the fields that aren't being initialized.
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000362 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
363 continue;
364
Chris Lattner8ce9e452010-04-13 18:16:19 +0000365 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedmandbff1a02011-08-23 20:22:34 +0000366 if (Field->isUnnamedBitfield()) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000367 LastFD = (*Field);
Chris Lattner8ce9e452010-04-13 18:16:19 +0000368 continue;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000369 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000370
Chris Lattner8ce9e452010-04-13 18:16:19 +0000371 // Get the initializer. A struct can include fields without initializers,
372 // we just use explicit null values for them.
373 llvm::Constant *EltInit;
374 if (ElementNo < ILE->getNumInits())
375 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
376 Field->getType(), CGF);
377 else
378 EltInit = CGM.EmitNullConstant(Field->getType());
Eli Friedmanf0ca0ee2010-07-17 23:55:01 +0000379
380 if (!EltInit)
381 return false;
Chris Lattner8ce9e452010-04-13 18:16:19 +0000382
383 if (!Field->isBitField()) {
384 // Handle non-bitfield members.
385 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit))
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000386 return false;
387 } else {
Chris Lattner8ce9e452010-04-13 18:16:19 +0000388 // Otherwise we have a bitfield.
Chris Lattner18806662010-07-05 17:04:23 +0000389 AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
390 cast<llvm::ConstantInt>(EltInit));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000391 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000392 }
393
Ken Dyckdc496392011-03-17 01:33:18 +0000394 CharUnits LayoutSizeInChars = Layout.getSize();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000395
Ken Dyckdc496392011-03-17 01:33:18 +0000396 if (NextFieldOffsetInChars > LayoutSizeInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000397 // If the struct is bigger than the size of the record type,
398 // we must have a flexible array member at the end.
399 assert(RD->hasFlexibleArrayMember() &&
400 "Must have flexible array member if struct is bigger than type!");
401
402 // No tail padding is necessary.
403 return true;
404 }
405
Ken Dyckdc496392011-03-17 01:33:18 +0000406 CharUnits LLVMSizeInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000407 NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000408
409 // Check if we need to convert the struct to a packed struct.
Ken Dyckdc496392011-03-17 01:33:18 +0000410 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
411 LLVMSizeInChars > LayoutSizeInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000412 assert(!Packed && "Size mismatch!");
413
414 ConvertStructToPacked();
Ken Dyckdc496392011-03-17 01:33:18 +0000415 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000416 "Converting to packed did not help!");
417 }
418
419 // Append tail padding if necessary.
Ken Dyckdc496392011-03-17 01:33:18 +0000420 AppendTailPadding(LayoutSizeInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000421
Ken Dyckdc496392011-03-17 01:33:18 +0000422 assert(LayoutSizeInChars == NextFieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000423 "Tail padding mismatch!");
424
425 return true;
426}
427
428llvm::Constant *ConstStructBuilder::
429 BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, InitListExpr *ILE) {
430 ConstStructBuilder Builder(CGM, CGF);
431
432 if (!Builder.Build(ILE))
433 return 0;
434
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000435 // Pick the type to use. If the type is layout identical to the ConvertType
436 // type then use it, otherwise use whatever the builder produced for us.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000437 llvm::StructType *STy =
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000438 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
439 Builder.Elements,Builder.Packed);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000440 llvm::Type *ILETy = CGM.getTypes().ConvertType(ILE->getType());
441 if (llvm::StructType *ILESTy = dyn_cast<llvm::StructType>(ILETy)) {
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000442 if (ILESTy->isLayoutIdentical(STy))
443 STy = ILESTy;
444 }
445
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000446 llvm::Constant *Result =
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000447 llvm::ConstantStruct::get(STy, Builder.Elements);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000448
Ken Dyck15c152e2011-03-18 01:12:13 +0000449 assert(Builder.NextFieldOffsetInChars.RoundUpToAlignment(
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000450 Builder.getAlignment(Result)) ==
Ken Dyck15c152e2011-03-18 01:12:13 +0000451 Builder.getSizeInChars(Result) && "Size mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000452
453 return Result;
454}
455
456
457//===----------------------------------------------------------------------===//
458// ConstExprEmitter
459//===----------------------------------------------------------------------===//
460
Benjamin Kramer85b45212009-11-28 19:45:26 +0000461class ConstExprEmitter :
Anders Carlsson84005b42008-01-26 04:30:23 +0000462 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000463 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000464 CodeGenFunction *CGF;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000465 llvm::LLVMContext &VMContext;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000466public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000467 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
Owen Andersona1cf15f2009-07-14 23:10:40 +0000468 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000471 //===--------------------------------------------------------------------===//
472 // Visitor Methods
473 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000475 llvm::Constant *VisitStmt(Stmt *S) {
Anders Carlsson069880e2009-03-03 16:43:34 +0000476 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
479 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
480 return Visit(PE->getSubExpr());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
John McCall91a57552011-07-15 05:09:51 +0000483 llvm::Constant *
484 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
485 return Visit(PE->getReplacement());
486 }
487
Peter Collingbournef111d932011-04-15 00:35:48 +0000488 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
489 return Visit(GE->getResultExpr());
490 }
491
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000492 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
493 return Visit(E->getInitializer());
494 }
John McCall5808ce42011-02-03 08:15:49 +0000495
Anders Carlssonf57b4e42009-10-03 15:02:02 +0000496 llvm::Constant *VisitUnaryAddrOf(UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000497 if (E->getType()->isMemberPointerType())
498 return CGM.getMemberPointerConstant(E);
Anders Carlsson45147d02010-02-02 03:37:46 +0000499
Anders Carlssonf57b4e42009-10-03 15:02:02 +0000500 return 0;
501 }
502
Chris Lattner3ae9f482009-10-13 07:14:16 +0000503 llvm::Constant *VisitBinSub(BinaryOperator *E) {
504 // This must be a pointer/pointer subtraction. This only happens for
505 // address of label.
506 if (!isa<AddrLabelExpr>(E->getLHS()->IgnoreParenNoopCasts(CGM.getContext())) ||
507 !isa<AddrLabelExpr>(E->getRHS()->IgnoreParenNoopCasts(CGM.getContext())))
508 return 0;
509
510 llvm::Constant *LHS = CGM.EmitConstantExpr(E->getLHS(),
511 E->getLHS()->getType(), CGF);
512 llvm::Constant *RHS = CGM.EmitConstantExpr(E->getRHS(),
513 E->getRHS()->getType(), CGF);
514
Chris Lattner2acc6e32011-07-18 04:24:23 +0000515 llvm::Type *ResultType = ConvertType(E->getType());
Chris Lattner3ae9f482009-10-13 07:14:16 +0000516 LHS = llvm::ConstantExpr::getPtrToInt(LHS, ResultType);
517 RHS = llvm::ConstantExpr::getPtrToInt(RHS, ResultType);
518
519 // No need to divide by element size, since addr of label is always void*,
520 // which has size 1 in GNUish.
521 return llvm::ConstantExpr::getSub(LHS, RHS);
522 }
523
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000524 llvm::Constant *VisitCastExpr(CastExpr* E) {
John McCall8bba1f42011-03-15 21:17:48 +0000525 Expr *subExpr = E->getSubExpr();
526 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
527 if (!C) return 0;
528
Chris Lattner2acc6e32011-07-18 04:24:23 +0000529 llvm::Type *destType = ConvertType(E->getType());
John McCall8bba1f42011-03-15 21:17:48 +0000530
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000531 switch (E->getCastKind()) {
John McCall2de56d12010-08-25 11:45:40 +0000532 case CK_ToUnion: {
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000533 // GCC cast to union extension
534 assert(E->getType()->isUnionType() &&
535 "Destination type is not union type!");
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000537 // Build a struct with the union sub-element as the first member,
538 // and padded to the appropriate size
539 std::vector<llvm::Constant*> Elts;
Jay Foadef6de3d2011-07-11 09:56:20 +0000540 std::vector<llvm::Type*> Types;
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000541 Elts.push_back(C);
542 Types.push_back(C->getType());
543 unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
John McCall8bba1f42011-03-15 21:17:48 +0000544 unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(destType);
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000546 assert(CurSize <= TotalSize && "Union size mismatch!");
547 if (unsigned NumPadBytes = TotalSize - CurSize) {
Jay Foadef6de3d2011-07-11 09:56:20 +0000548 llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000549 if (NumPadBytes > 1)
550 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000551
Nuno Lopescdb30b42010-04-16 20:56:35 +0000552 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000553 Types.push_back(Ty);
554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000556 llvm::StructType* STy =
557 llvm::StructType::get(C->getType()->getContext(), Types, false);
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000558 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes81e51e22009-01-17 00:48:48 +0000559 }
John McCall2de56d12010-08-25 11:45:40 +0000560 case CK_NullToMemberPointer: {
John McCalld608cdb2010-08-22 10:59:02 +0000561 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
John McCall0bab0cd2010-08-23 01:21:21 +0000562 return CGM.getCXXABI().EmitNullMemberPointer(MPT);
John McCalld608cdb2010-08-22 10:59:02 +0000563 }
Anders Carlsson2c51f092009-10-03 15:13:22 +0000564
John McCall8bba1f42011-03-15 21:17:48 +0000565 case CK_DerivedToBaseMemberPointer:
566 case CK_BaseToDerivedMemberPointer:
John McCall0bab0cd2010-08-23 01:21:21 +0000567 return CGM.getCXXABI().EmitMemberPointerConversion(C, E);
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000568
John McCall8bba1f42011-03-15 21:17:48 +0000569 case CK_LValueToRValue:
570 case CK_NoOp:
571 return C;
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000572
John McCall1d9b3b22011-09-09 05:25:32 +0000573 case CK_CPointerToObjCPointerCast:
574 case CK_BlockPointerToObjCPointerCast:
John McCall8bba1f42011-03-15 21:17:48 +0000575 case CK_AnyPointerToBlockPointerCast:
John McCall8bba1f42011-03-15 21:17:48 +0000576 case CK_BitCast:
577 if (C->getType() == destType) return C;
578 return llvm::ConstantExpr::getBitCast(C, destType);
Chris Lattner430656e2009-10-13 22:12:09 +0000579
John McCall8bba1f42011-03-15 21:17:48 +0000580 case CK_Dependent: llvm_unreachable("saw dependent cast!");
581
582 // These will never be supported.
583 case CK_ObjCObjectLValueCast:
John McCall8bba1f42011-03-15 21:17:48 +0000584 case CK_ToVoid:
585 case CK_Dynamic:
John McCall33e56f32011-09-10 06:18:15 +0000586 case CK_ARCProduceObject:
587 case CK_ARCConsumeObject:
588 case CK_ARCReclaimReturnedObject:
589 case CK_ARCExtendBlockObject:
Eli Friedmanb0004592011-10-24 22:25:55 +0000590 case CK_LValueBitCast:
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000591 return 0;
John McCall8bba1f42011-03-15 21:17:48 +0000592
593 // These might need to be supported for constexpr.
594 case CK_UserDefinedConversion:
595 case CK_ConstructorConversion:
596 return 0;
597
598 // These should eventually be supported.
599 case CK_ArrayToPointerDecay:
600 case CK_FunctionToPointerDecay:
601 case CK_BaseToDerived:
602 case CK_DerivedToBase:
603 case CK_UncheckedDerivedToBase:
604 case CK_MemberPointerToBoolean:
605 case CK_VectorSplat:
606 case CK_FloatingRealToComplex:
607 case CK_FloatingComplexToReal:
608 case CK_FloatingComplexToBoolean:
609 case CK_FloatingComplexCast:
610 case CK_FloatingComplexToIntegralComplex:
611 case CK_IntegralRealToComplex:
612 case CK_IntegralComplexToReal:
613 case CK_IntegralComplexToBoolean:
614 case CK_IntegralComplexCast:
615 case CK_IntegralComplexToFloatingComplex:
616 return 0;
617
618 case CK_PointerToIntegral:
619 if (!E->getType()->isBooleanType())
620 return llvm::ConstantExpr::getPtrToInt(C, destType);
621 // fallthrough
622
623 case CK_PointerToBoolean:
624 return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
625 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(C->getType())));
626
627 case CK_NullToPointer:
628 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destType));
629
630 case CK_IntegralCast: {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000631 bool isSigned = subExpr->getType()->isSignedIntegerOrEnumerationType();
John McCall8bba1f42011-03-15 21:17:48 +0000632 return llvm::ConstantExpr::getIntegerCast(C, destType, isSigned);
Eli Friedmanddd2b6e2009-02-22 07:29:04 +0000633 }
John McCall8bba1f42011-03-15 21:17:48 +0000634
635 case CK_IntegralToPointer: {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000636 bool isSigned = subExpr->getType()->isSignedIntegerOrEnumerationType();
John McCall8bba1f42011-03-15 21:17:48 +0000637 C = llvm::ConstantExpr::getIntegerCast(C, CGM.IntPtrTy, isSigned);
638 return llvm::ConstantExpr::getIntToPtr(C, destType);
639 }
640
641 case CK_IntegralToBoolean:
642 return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
643 llvm::Constant::getNullValue(C->getType()));
644
645 case CK_IntegralToFloating:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000646 if (subExpr->getType()->isSignedIntegerOrEnumerationType())
John McCall8bba1f42011-03-15 21:17:48 +0000647 return llvm::ConstantExpr::getSIToFP(C, destType);
648 else
649 return llvm::ConstantExpr::getUIToFP(C, destType);
650
651 case CK_FloatingToIntegral:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000652 if (E->getType()->isSignedIntegerOrEnumerationType())
John McCall8bba1f42011-03-15 21:17:48 +0000653 return llvm::ConstantExpr::getFPToSI(C, destType);
654 else
655 return llvm::ConstantExpr::getFPToUI(C, destType);
656
657 case CK_FloatingToBoolean:
658 return llvm::ConstantExpr::getFCmp(llvm::CmpInst::FCMP_UNE, C,
659 llvm::Constant::getNullValue(C->getType()));
660
661 case CK_FloatingCast:
662 return llvm::ConstantExpr::getFPCast(C, destType);
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000663 }
Matt Beaumont-Gay17d12fe2011-03-17 00:46:34 +0000664 llvm_unreachable("Invalid CastKind");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000665 }
Devang Pateleae15602008-02-05 02:39:50 +0000666
Chris Lattner04421082008-04-08 04:40:51 +0000667 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
668 return Visit(DAE->getExpr());
669 }
670
Douglas Gregor03e80032011-06-21 17:03:29 +0000671 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
672 return Visit(E->GetTemporaryExpr());
673 }
674
Eli Friedmana8234002008-05-30 10:24:46 +0000675 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Nuno Lopesa75b71f2010-04-18 19:06:43 +0000676 unsigned NumInitElements = ILE->getNumInits();
Benjamin Kramer0483a6f2011-03-02 21:27:44 +0000677 if (NumInitElements == 1 && ILE->getType() == ILE->getInit(0)->getType() &&
Nuno Lopesa75b71f2010-04-18 19:06:43 +0000678 (isa<StringLiteral>(ILE->getInit(0)) ||
679 isa<ObjCEncodeExpr>(ILE->getInit(0))))
680 return Visit(ILE->getInit(0));
681
Nuno Lopes67847042010-04-16 23:19:41 +0000682 std::vector<llvm::Constant*> Elts;
Chris Lattner2acc6e32011-07-18 04:24:23 +0000683 llvm::ArrayType *AType =
Nuno Lopes67847042010-04-16 23:19:41 +0000684 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000685 llvm::Type *ElemTy = AType->getElementType();
Devang Pateleae15602008-02-05 02:39:50 +0000686 unsigned NumElements = AType->getNumElements();
687
Mike Stump1eb44332009-09-09 15:08:12 +0000688 // Initialising an array requires us to automatically
Devang Pateleae15602008-02-05 02:39:50 +0000689 // initialise any elements that have not been initialised explicitly
690 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
691
692 // Copy initializer elements.
693 unsigned i = 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000694 bool RewriteType = false;
Devang Pateleae15602008-02-05 02:39:50 +0000695 for (; i < NumInitableElts; ++i) {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000696 Expr *Init = ILE->getInit(i);
697 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000698 if (!C)
699 return 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000700 RewriteType |= (C->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +0000701 Elts.push_back(C);
702 }
Eli Friedmana04a1532008-05-30 19:58:50 +0000703
Devang Pateleae15602008-02-05 02:39:50 +0000704 // Initialize remaining array elements.
Eli Friedman0f593122009-04-13 21:47:26 +0000705 // FIXME: This doesn't handle member pointers correctly!
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000706 llvm::Constant *fillC;
707 if (Expr *filler = ILE->getArrayFiller())
708 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
709 else
710 fillC = llvm::Constant::getNullValue(ElemTy);
711 if (!fillC)
712 return 0;
713 RewriteType |= (fillC->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +0000714 for (; i < NumElements; ++i)
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000715 Elts.push_back(fillC);
Devang Pateleae15602008-02-05 02:39:50 +0000716
Eli Friedmana04a1532008-05-30 19:58:50 +0000717 if (RewriteType) {
718 // FIXME: Try to avoid packing the array
Jay Foadef6de3d2011-07-11 09:56:20 +0000719 std::vector<llvm::Type*> Types;
Eli Friedmana04a1532008-05-30 19:58:50 +0000720 for (unsigned i = 0; i < Elts.size(); ++i)
721 Types.push_back(Elts[i]->getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000722 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000723 Types, true);
Owen Anderson08e25242009-07-27 22:29:56 +0000724 return llvm::ConstantStruct::get(SType, Elts);
Eli Friedmana04a1532008-05-30 19:58:50 +0000725 }
726
Mike Stump1eb44332009-09-09 15:08:12 +0000727 return llvm::ConstantArray::get(AType, Elts);
Devang Pateleae15602008-02-05 02:39:50 +0000728 }
729
Eli Friedmana8234002008-05-30 10:24:46 +0000730 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
Anders Carlsson8dca3b32009-07-27 05:54:15 +0000731 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
Devang Pateleae15602008-02-05 02:39:50 +0000732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Eli Friedmana8234002008-05-30 10:24:46 +0000734 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
Anders Carlssonf6c43962009-07-31 21:34:04 +0000735 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
Eli Friedmana8234002008-05-30 10:24:46 +0000736 }
737
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000738 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
Eli Friedman0f593122009-04-13 21:47:26 +0000739 return CGM.EmitNullConstant(E->getType());
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000742 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000743 if (ILE->getType()->isAnyComplexType() && ILE->getNumInits() == 2) {
744 // Complex type with element initializers
745 Expr *Real = ILE->getInit(0);
746 Expr *Imag = ILE->getInit(1);
747 llvm::Constant *Complex[2];
748 Complex[0] = CGM.EmitConstantExpr(Real, Real->getType(), CGF);
749 if (!Complex[0])
750 return 0;
751 Complex[1] = CGM.EmitConstantExpr(Imag, Imag->getType(), CGF);
752 if (!Complex[1])
753 return 0;
754 llvm::StructType *STy =
755 cast<llvm::StructType>(ConvertType(ILE->getType()));
756 return llvm::ConstantStruct::get(STy, Complex);
757 }
758
Eli Friedmana8234002008-05-30 10:24:46 +0000759 if (ILE->getType()->isScalarType()) {
760 // We have a scalar in braces. Just use the first element.
Anders Carlssone9352cc2009-04-08 04:48:15 +0000761 if (ILE->getNumInits() > 0) {
762 Expr *Init = ILE->getInit(0);
763 return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
764 }
Eli Friedman0f593122009-04-13 21:47:26 +0000765 return CGM.EmitNullConstant(ILE->getType());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Eli Friedmana8234002008-05-30 10:24:46 +0000768 if (ILE->getType()->isArrayType())
769 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000770
Anders Carlsson01a79ac2009-11-21 23:56:04 +0000771 if (ILE->getType()->isRecordType())
Eli Friedmana8234002008-05-30 10:24:46 +0000772 return EmitStructInitialization(ILE);
773
774 if (ILE->getType()->isUnionType())
775 return EmitUnionInitialization(ILE);
776
Eli Friedman8ac55492010-01-02 23:43:59 +0000777 // If ILE was a constant vector, we would have handled it already.
Eli Friedmana8234002008-05-30 10:24:46 +0000778 if (ILE->getType()->isVectorType())
Eli Friedman8ac55492010-01-02 23:43:59 +0000779 return 0;
Eli Friedmana8234002008-05-30 10:24:46 +0000780
David Blaikieb219cfc2011-09-23 05:06:16 +0000781 llvm_unreachable("Unable to handle InitListExpr");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000782 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000783
John McCallfb8b69a2010-02-02 08:02:49 +0000784 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
785 if (!E->getConstructor()->isTrivial())
786 return 0;
787
Anders Carlsson2ca4f632010-02-05 18:38:45 +0000788 QualType Ty = E->getType();
789
790 // FIXME: We should not have to call getBaseElementType here.
791 const RecordType *RT =
792 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
793 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
794
795 // If the class doesn't have a trivial destructor, we can't emit it as a
796 // constant expr.
797 if (!RD->hasTrivialDestructor())
798 return 0;
799
John McCallfb8b69a2010-02-02 08:02:49 +0000800 // Only copy and default constructors can be trivial.
801
John McCallfb8b69a2010-02-02 08:02:49 +0000802
803 if (E->getNumArgs()) {
804 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000805 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
806 "trivial ctor has argument but isn't a copy/move ctor");
John McCallfb8b69a2010-02-02 08:02:49 +0000807
808 Expr *Arg = E->getArg(0);
809 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
810 "argument to copy ctor is of wrong type");
811
Chandler Carruth878b55c2010-02-02 12:15:55 +0000812 return Visit(Arg);
John McCallfb8b69a2010-02-02 08:02:49 +0000813 }
814
815 return CGM.EmitNullConstant(Ty);
816 }
817
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000818 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
Eli Friedman64f45a22011-11-01 02:23:42 +0000819 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000820 }
821
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000822 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
823 // This must be an @encode initializing an array in a static initializer.
824 // Don't emit it as the address of the string, emit the string data itself
825 // as an inline array.
826 std::string Str;
827 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
828 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000830 // Resize the string to the right size, adding zeros at the end, or
831 // truncating as needed.
832 Str.resize(CAT->getSize().getZExtValue(), '\0');
Owen Anderson0032b272009-08-13 21:57:51 +0000833 return llvm::ConstantArray::get(VMContext, Str, false);
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000836 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
837 return Visit(E->getSubExpr());
838 }
Mike Stumpb83d2872009-02-19 22:01:56 +0000839
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000840 // Utility methods
Chris Lattner2acc6e32011-07-18 04:24:23 +0000841 llvm::Type *ConvertType(QualType T) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000842 return CGM.getTypes().ConvertType(T);
843 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000844
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000845public:
Anders Carlsson84005b42008-01-26 04:30:23 +0000846 llvm::Constant *EmitLValue(Expr *E) {
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000847 switch (E->getStmtClass()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000848 default: break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000849 case Expr::CompoundLiteralExprClass: {
850 // Note that due to the nature of compound literals, this is guaranteed
851 // to be the only use of the variable, so we just generate it here.
Anders Carlsson84005b42008-01-26 04:30:23 +0000852 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
853 llvm::Constant* C = Visit(CLE->getInitializer());
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000854 // FIXME: "Leaked" on failure.
855 if (C)
Owen Anderson1c431b32009-07-08 19:05:04 +0000856 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
Eli Friedmand15d8c62009-08-26 20:01:39 +0000857 E->getType().isConstant(CGM.getContext()),
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000858 llvm::GlobalValue::InternalLinkage,
Eli Friedmand15d8c62009-08-26 20:01:39 +0000859 C, ".compoundliteral", 0, false,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000860 CGM.getContext().getTargetAddressSpace(E->getType()));
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000861 return C;
Anders Carlsson84005b42008-01-26 04:30:23 +0000862 }
Douglas Gregora2813ce2009-10-23 18:54:35 +0000863 case Expr::DeclRefExprClass: {
Rafael Espindolada182612010-03-04 21:26:03 +0000864 ValueDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
865 if (Decl->hasAttr<WeakRefAttr>())
Eli Friedmana7e68452010-08-22 01:00:03 +0000866 return CGM.GetWeakRefReference(Decl);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000867 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000868 return CGM.GetAddrOfFunction(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000869 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000870 // We can never refer to a variable with local storage.
Mike Stump1eb44332009-09-09 15:08:12 +0000871 if (!VD->hasLocalStorage()) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000872 if (VD->isFileVarDecl() || VD->hasExternalStorage())
873 return CGM.GetAddrOfGlobalVar(VD);
John McCallb6bbcc92010-10-15 04:57:14 +0000874 else if (VD->isLocalVarDecl()) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000875 assert(CGF && "Can't access static local vars without CGF");
876 return CGF->GetAddrOfStaticLocalVar(VD);
877 }
Steve Naroff248a7532008-04-15 22:42:06 +0000878 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000879 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000880 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000881 }
Daniel Dunbar61432932008-08-13 23:20:05 +0000882 case Expr::StringLiteralClass:
883 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000884 case Expr::ObjCEncodeExprClass:
885 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000886 case Expr::ObjCStringLiteralClass: {
887 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000888 llvm::Constant *C =
889 CGM.getObjCRuntime().GenerateConstantString(SL->getString());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000890 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000891 }
Chris Lattner35345642008-12-12 05:18:02 +0000892 case Expr::PredefinedExprClass: {
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000893 unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
894 if (CGF) {
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +0000895 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000896 return cast<llvm::Constant>(Res.getAddress());
897 } else if (Type == PredefinedExpr::PrettyFunction) {
898 return CGM.GetAddrOfConstantCString("top level", ".tmp");
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000901 return CGM.GetAddrOfConstantCString("", ".tmp");
Chris Lattner35345642008-12-12 05:18:02 +0000902 }
Eli Friedmanf0115892009-01-25 01:21:06 +0000903 case Expr::AddrLabelExprClass: {
904 assert(CGF && "Invalid address of label expression outside function.");
Chris Lattnerd9becd12009-10-28 23:59:40 +0000905 llvm::Constant *Ptr =
906 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
907 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
Eli Friedmanf0115892009-01-25 01:21:06 +0000908 }
Eli Friedman3941b182009-01-25 01:54:01 +0000909 case Expr::CallExprClass: {
910 CallExpr* CE = cast<CallExpr>(E);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000911 unsigned builtin = CE->isBuiltinCall(CGM.getContext());
912 if (builtin !=
913 Builtin::BI__builtin___CFStringMakeConstantString &&
914 builtin !=
915 Builtin::BI__builtin___NSStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000916 break;
917 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
918 const StringLiteral *Literal = cast<StringLiteral>(Arg);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000919 if (builtin ==
920 Builtin::BI__builtin___NSStringMakeConstantString) {
921 return CGM.getObjCRuntime().GenerateConstantString(Literal);
922 }
Steve Naroff33fdb732009-03-31 16:53:37 +0000923 // FIXME: need to deal with UCN conversion issues.
Steve Naroff8d4141f2009-04-01 13:55:36 +0000924 return CGM.GetAddrOfConstantCFString(Literal);
Eli Friedman3941b182009-01-25 01:54:01 +0000925 }
Mike Stumpbd65cac2009-02-19 01:01:04 +0000926 case Expr::BlockExprClass: {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000927 std::string FunctionName;
928 if (CGF)
929 FunctionName = CGF->CurFn->getName();
930 else
931 FunctionName = "global";
932
933 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
Mike Stumpbd65cac2009-02-19 01:01:04 +0000934 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000935 }
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000936
937 return 0;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000938 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000939};
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000941} // end anonymous namespace.
942
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000943llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
Anders Carlssone9352cc2009-04-08 04:48:15 +0000944 QualType DestType,
Chris Lattner96196622008-07-26 22:37:01 +0000945 CodeGenFunction *CGF) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000946 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlsson1e5dc6e2009-04-11 01:08:03 +0000948 bool Success = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Eli Friedman50c39ea2009-05-27 06:04:58 +0000950 if (DestType->isReferenceType())
951 Success = E->EvaluateAsLValue(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000952 else
Richard Smith51f47082011-10-29 00:50:52 +0000953 Success = E->EvaluateAsRValue(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Eli Friedman55f9bdd2009-11-14 08:51:33 +0000955 if (Success && !Result.HasSideEffects) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000956 switch (Result.Val.getKind()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +0000957 case APValue::Uninitialized:
David Blaikieb219cfc2011-09-23 05:06:16 +0000958 llvm_unreachable("Constant expressions should be initialized.");
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000959 case APValue::LValue: {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000960 llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
Mike Stump1eb44332009-09-09 15:08:12 +0000961 llvm::Constant *Offset =
962 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Ken Dycka7305832010-01-15 12:37:54 +0000963 Result.Val.getLValueOffset().getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Daniel Dunbare20de512009-02-19 21:44:24 +0000965 llvm::Constant *C;
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000966 if (const Expr *LVBase = Result.Val.getLValueBase()) {
Daniel Dunbare20de512009-02-19 21:44:24 +0000967 C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000968
Daniel Dunbare20de512009-02-19 21:44:24 +0000969 // Apply offset if necessary.
970 if (!Offset->isNullValue()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000971 llvm::Type *Type = llvm::Type::getInt8PtrTy(VMContext);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000972 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
Jay Foada5c04342011-07-21 14:31:17 +0000973 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000974 C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
Daniel Dunbare20de512009-02-19 21:44:24 +0000975 }
976
977 // Convert to the appropriate type; this could be an lvalue for
978 // an integer.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000979 if (isa<llvm::PointerType>(DestTy))
Owen Anderson3c4972d2009-07-29 18:54:39 +0000980 return llvm::ConstantExpr::getBitCast(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000981
Owen Anderson3c4972d2009-07-29 18:54:39 +0000982 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000983 } else {
984 C = Offset;
985
986 // Convert to the appropriate type; this could be an lvalue for
987 // an integer.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000988 if (isa<llvm::PointerType>(DestTy))
Owen Anderson3c4972d2009-07-29 18:54:39 +0000989 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000990
991 // If the types don't match this should only be a truncate.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000992 if (C->getType() != DestTy)
Owen Anderson3c4972d2009-07-29 18:54:39 +0000993 return llvm::ConstantExpr::getTrunc(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000994
995 return C;
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000996 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000997 }
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000998 case APValue::Int: {
Mike Stump1eb44332009-09-09 15:08:12 +0000999 llvm::Constant *C = llvm::ConstantInt::get(VMContext,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001000 Result.Val.getInt());
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner7f215c12010-06-26 21:52:32 +00001002 if (C->getType()->isIntegerTy(1)) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001003 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
Owen Anderson3c4972d2009-07-29 18:54:39 +00001004 C = llvm::ConstantExpr::getZExt(C, BoolTy);
Anders Carlsson5a9a4572008-11-15 20:45:50 +00001005 }
1006 return C;
Eli Friedman7b30b1c2008-11-17 03:57:28 +00001007 }
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001008 case APValue::ComplexInt: {
1009 llvm::Constant *Complex[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001011 Complex[0] = llvm::ConstantInt::get(VMContext,
1012 Result.Val.getComplexIntReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001013 Complex[1] = llvm::ConstantInt::get(VMContext,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001014 Result.Val.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001016 // FIXME: the target may want to specify that this is packed.
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001017 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1018 Complex[1]->getType(),
1019 NULL);
1020 return llvm::ConstantStruct::get(STy, Complex);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001021 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001022 case APValue::Float: {
1023 const llvm::APFloat &Init = Result.Val.getFloat();
1024 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf)
1025 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1026 else
1027 return llvm::ConstantFP::get(VMContext, Init);
1028 }
Anders Carlssonaa432562008-11-17 01:58:55 +00001029 case APValue::ComplexFloat: {
1030 llvm::Constant *Complex[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001031
1032 Complex[0] = llvm::ConstantFP::get(VMContext,
Owen Andersonbc0a2222009-07-27 21:00:51 +00001033 Result.Val.getComplexFloatReal());
1034 Complex[1] = llvm::ConstantFP::get(VMContext,
1035 Result.Val.getComplexFloatImag());
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001037 // FIXME: the target may want to specify that this is packed.
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001038 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1039 Complex[1]->getType(),
1040 NULL);
1041 return llvm::ConstantStruct::get(STy, Complex);
Anders Carlssonaa432562008-11-17 01:58:55 +00001042 }
Nate Begeman3d309f92009-01-18 01:01:34 +00001043 case APValue::Vector: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001044 SmallVector<llvm::Constant *, 4> Inits;
Nate Begeman3d309f92009-01-18 01:01:34 +00001045 unsigned NumElts = Result.Val.getVectorLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Anton Yartsevd06fea82011-03-27 09:32:40 +00001047 if (Context.getLangOptions().AltiVec &&
1048 isa<CastExpr>(E) &&
1049 cast<CastExpr>(E)->getCastKind() == CK_VectorSplat) {
1050 // AltiVec vector initialization with a single literal
1051 APValue &Elt = Result.Val.getVectorElt(0);
1052
1053 llvm::Constant* InitValue = Elt.isInt()
1054 ? cast<llvm::Constant>
1055 (llvm::ConstantInt::get(VMContext, Elt.getInt()))
1056 : cast<llvm::Constant>
1057 (llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1058
1059 for (unsigned i = 0; i != NumElts; ++i)
1060 Inits.push_back(InitValue);
1061
1062 } else {
1063 for (unsigned i = 0; i != NumElts; ++i) {
1064 APValue &Elt = Result.Val.getVectorElt(i);
1065 if (Elt.isInt())
1066 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
1067 else
1068 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1069 }
Nate Begeman3d309f92009-01-18 01:01:34 +00001070 }
Chris Lattnerfb018d12011-02-15 00:14:06 +00001071 return llvm::ConstantVector::get(Inits);
Nate Begeman3d309f92009-01-18 01:01:34 +00001072 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +00001073 }
1074 }
Eli Friedman7dfa6392008-06-01 15:31:44 +00001075
1076 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
Chris Lattner7f215c12010-06-26 21:52:32 +00001077 if (C && C->getType()->isIntegerTy(1)) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001078 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
Owen Anderson3c4972d2009-07-29 18:54:39 +00001079 C = llvm::ConstantExpr::getZExt(C, BoolTy);
Eli Friedman7dfa6392008-06-01 15:31:44 +00001080 }
1081 return C;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001082}
Eli Friedman0f593122009-04-13 21:47:26 +00001083
John McCall5808ce42011-02-03 08:15:49 +00001084static uint64_t getFieldOffset(ASTContext &C, const FieldDecl *field) {
1085 const ASTRecordLayout &layout = C.getASTRecordLayout(field->getParent());
1086 return layout.getFieldOffset(field->getFieldIndex());
1087}
1088
1089llvm::Constant *
1090CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1091 // Member pointer constants always have a very particular form.
1092 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1093 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1094
1095 // A member function pointer.
1096 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1097 return getCXXABI().EmitMemberPointer(method);
1098
1099 // Otherwise, a member data pointer.
1100 uint64_t fieldOffset;
1101 if (const FieldDecl *field = dyn_cast<FieldDecl>(decl))
1102 fieldOffset = getFieldOffset(getContext(), field);
1103 else {
1104 const IndirectFieldDecl *ifield = cast<IndirectFieldDecl>(decl);
1105
1106 fieldOffset = 0;
1107 for (IndirectFieldDecl::chain_iterator ci = ifield->chain_begin(),
1108 ce = ifield->chain_end(); ci != ce; ++ci)
1109 fieldOffset += getFieldOffset(getContext(), cast<FieldDecl>(*ci));
1110 }
1111
1112 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1113 return getCXXABI().EmitMemberDataPointer(type, chars);
1114}
1115
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001116static void
1117FillInNullDataMemberPointers(CodeGenModule &CGM, QualType T,
1118 std::vector<llvm::Constant *> &Elements,
1119 uint64_t StartOffset) {
Ken Dyckc4d68db2011-03-22 00:24:31 +00001120 assert(StartOffset % CGM.getContext().getCharWidth() == 0 &&
1121 "StartOffset not byte aligned!");
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001122
John McCallf16aa102010-08-22 21:01:12 +00001123 if (CGM.getTypes().isZeroInitializable(T))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001124 return;
1125
1126 if (const ConstantArrayType *CAT =
1127 CGM.getContext().getAsConstantArrayType(T)) {
1128 QualType ElementTy = CAT->getElementType();
1129 uint64_t ElementSize = CGM.getContext().getTypeSize(ElementTy);
1130
1131 for (uint64_t I = 0, E = CAT->getSize().getZExtValue(); I != E; ++I) {
1132 FillInNullDataMemberPointers(CGM, ElementTy, Elements,
1133 StartOffset + I * ElementSize);
1134 }
1135 } else if (const RecordType *RT = T->getAs<RecordType>()) {
1136 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1137 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1138
1139 // Go through all bases and fill in any null pointer to data members.
1140 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1141 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson0a87b372010-05-27 18:51:01 +00001142 if (I->isVirtual()) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001143 // Ignore virtual bases.
Anders Carlsson0a87b372010-05-27 18:51:01 +00001144 continue;
1145 }
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001146
1147 const CXXRecordDecl *BaseDecl =
1148 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1149
1150 // Ignore empty bases.
1151 if (BaseDecl->isEmpty())
1152 continue;
1153
1154 // Ignore bases that don't have any pointer to data members.
John McCallf16aa102010-08-22 21:01:12 +00001155 if (CGM.getTypes().isZeroInitializable(BaseDecl))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001156 continue;
1157
Anders Carlssona14f5972010-10-31 23:22:37 +00001158 uint64_t BaseOffset = Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001159 FillInNullDataMemberPointers(CGM, I->getType(),
1160 Elements, StartOffset + BaseOffset);
1161 }
1162
1163 // Visit all fields.
1164 unsigned FieldNo = 0;
1165 for (RecordDecl::field_iterator I = RD->field_begin(),
1166 E = RD->field_end(); I != E; ++I, ++FieldNo) {
1167 QualType FieldType = I->getType();
1168
John McCallf16aa102010-08-22 21:01:12 +00001169 if (CGM.getTypes().isZeroInitializable(FieldType))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001170 continue;
1171
1172 uint64_t FieldOffset = StartOffset + Layout.getFieldOffset(FieldNo);
1173 FillInNullDataMemberPointers(CGM, FieldType, Elements, FieldOffset);
1174 }
1175 } else {
1176 assert(T->isMemberPointerType() && "Should only see member pointers here!");
1177 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1178 "Should only see pointers to data members here!");
1179
Ken Dyckc4d68db2011-03-22 00:24:31 +00001180 CharUnits StartIndex = CGM.getContext().toCharUnitsFromBits(StartOffset);
1181 CharUnits EndIndex = StartIndex + CGM.getContext().getTypeSizeInChars(T);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001182
John McCall5808ce42011-02-03 08:15:49 +00001183 // FIXME: hardcodes Itanium member pointer representation!
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001184 llvm::Constant *NegativeOne =
1185 llvm::ConstantInt::get(llvm::Type::getInt8Ty(CGM.getLLVMContext()),
John McCall5808ce42011-02-03 08:15:49 +00001186 -1ULL, /*isSigned*/true);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001187
1188 // Fill in the null data member pointer.
Ken Dyckc4d68db2011-03-22 00:24:31 +00001189 for (CharUnits I = StartIndex; I != EndIndex; ++I)
1190 Elements[I.getQuantity()] = NegativeOne;
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001191 }
1192}
1193
John McCall9b7da1c2011-02-15 06:40:56 +00001194static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001195 llvm::Type *baseType,
John McCall9b7da1c2011-02-15 06:40:56 +00001196 const CXXRecordDecl *base);
1197
Anders Carlssonada4b322010-11-22 18:42:14 +00001198static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
John McCall9b7da1c2011-02-15 06:40:56 +00001199 const CXXRecordDecl *record,
1200 bool asCompleteObject) {
1201 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001202 llvm::StructType *structure =
John McCall9b7da1c2011-02-15 06:40:56 +00001203 (asCompleteObject ? layout.getLLVMType()
1204 : layout.getBaseSubobjectLLVMType());
Anders Carlssonada4b322010-11-22 18:42:14 +00001205
John McCall9b7da1c2011-02-15 06:40:56 +00001206 unsigned numElements = structure->getNumElements();
1207 std::vector<llvm::Constant *> elements(numElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001208
John McCall9b7da1c2011-02-15 06:40:56 +00001209 // Fill in all the bases.
1210 for (CXXRecordDecl::base_class_const_iterator
1211 I = record->bases_begin(), E = record->bases_end(); I != E; ++I) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001212 if (I->isVirtual()) {
John McCall9b7da1c2011-02-15 06:40:56 +00001213 // Ignore virtual bases; if we're laying out for a complete
1214 // object, we'll lay these out later.
Anders Carlssonada4b322010-11-22 18:42:14 +00001215 continue;
1216 }
1217
John McCall9b7da1c2011-02-15 06:40:56 +00001218 const CXXRecordDecl *base =
1219 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonada4b322010-11-22 18:42:14 +00001220
1221 // Ignore empty bases.
John McCall9b7da1c2011-02-15 06:40:56 +00001222 if (base->isEmpty())
Anders Carlssonada4b322010-11-22 18:42:14 +00001223 continue;
1224
John McCall9b7da1c2011-02-15 06:40:56 +00001225 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001226 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall9b7da1c2011-02-15 06:40:56 +00001227 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlssonada4b322010-11-22 18:42:14 +00001228 }
1229
John McCall9b7da1c2011-02-15 06:40:56 +00001230 // Fill in all the fields.
1231 for (RecordDecl::field_iterator I = record->field_begin(),
1232 E = record->field_end(); I != E; ++I) {
1233 const FieldDecl *field = *I;
Anders Carlssonada4b322010-11-22 18:42:14 +00001234
1235 // Ignore bit fields.
John McCall9b7da1c2011-02-15 06:40:56 +00001236 if (field->isBitField())
Anders Carlssonada4b322010-11-22 18:42:14 +00001237 continue;
1238
John McCall9b7da1c2011-02-15 06:40:56 +00001239 unsigned fieldIndex = layout.getLLVMFieldNo(field);
1240 elements[fieldIndex] = CGM.EmitNullConstant(field->getType());
1241 }
1242
1243 // Fill in the virtual bases, if we're working with the complete object.
1244 if (asCompleteObject) {
1245 for (CXXRecordDecl::base_class_const_iterator
1246 I = record->vbases_begin(), E = record->vbases_end(); I != E; ++I) {
1247 const CXXRecordDecl *base =
1248 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1249
1250 // Ignore empty bases.
1251 if (base->isEmpty())
1252 continue;
1253
1254 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1255
1256 // We might have already laid this field out.
1257 if (elements[fieldIndex]) continue;
1258
Chris Lattner2acc6e32011-07-18 04:24:23 +00001259 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall9b7da1c2011-02-15 06:40:56 +00001260 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1261 }
Anders Carlssonada4b322010-11-22 18:42:14 +00001262 }
1263
1264 // Now go through all other fields and zero them out.
John McCall9b7da1c2011-02-15 06:40:56 +00001265 for (unsigned i = 0; i != numElements; ++i) {
1266 if (!elements[i])
1267 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlssonada4b322010-11-22 18:42:14 +00001268 }
1269
John McCall9b7da1c2011-02-15 06:40:56 +00001270 return llvm::ConstantStruct::get(structure, elements);
1271}
1272
1273/// Emit the null constant for a base subobject.
1274static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001275 llvm::Type *baseType,
John McCall9b7da1c2011-02-15 06:40:56 +00001276 const CXXRecordDecl *base) {
1277 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1278
1279 // Just zero out bases that don't have any pointer to data members.
1280 if (baseLayout.isZeroInitializableAsBase())
1281 return llvm::Constant::getNullValue(baseType);
1282
1283 // If the base type is a struct, we can just use its null constant.
1284 if (isa<llvm::StructType>(baseType)) {
1285 return EmitNullConstant(CGM, base, /*complete*/ false);
1286 }
1287
1288 // Otherwise, some bases are represented as arrays of i8 if the size
1289 // of the base is smaller than its corresponding LLVM type. Figure
1290 // out how many elements this base array has.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001291 llvm::ArrayType *baseArrayType = cast<llvm::ArrayType>(baseType);
John McCall9b7da1c2011-02-15 06:40:56 +00001292 unsigned numBaseElements = baseArrayType->getNumElements();
1293
1294 // Fill in null data member pointers.
1295 std::vector<llvm::Constant *> baseElements(numBaseElements);
1296 FillInNullDataMemberPointers(CGM, CGM.getContext().getTypeDeclType(base),
1297 baseElements, 0);
1298
1299 // Now go through all other elements and zero them out.
1300 if (numBaseElements) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001301 llvm::Type *i8 = llvm::Type::getInt8Ty(CGM.getLLVMContext());
John McCall9b7da1c2011-02-15 06:40:56 +00001302 llvm::Constant *i8_zero = llvm::Constant::getNullValue(i8);
1303 for (unsigned i = 0; i != numBaseElements; ++i) {
1304 if (!baseElements[i])
1305 baseElements[i] = i8_zero;
1306 }
1307 }
1308
1309 return llvm::ConstantArray::get(baseArrayType, baseElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001310}
1311
Eli Friedman0f593122009-04-13 21:47:26 +00001312llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
John McCallf16aa102010-08-22 21:01:12 +00001313 if (getTypes().isZeroInitializable(T))
Anders Carlssonad3e7112009-08-24 17:16:23 +00001314 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Anders Carlsson2c12d032010-02-02 05:17:25 +00001315
Anders Carlsson237957c2009-08-09 18:26:27 +00001316 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Anders Carlsson237957c2009-08-09 18:26:27 +00001318 QualType ElementTy = CAT->getElementType();
1319
Anders Carlsson2c12d032010-02-02 05:17:25 +00001320 llvm::Constant *Element = EmitNullConstant(ElementTy);
1321 unsigned NumElements = CAT->getSize().getZExtValue();
1322 std::vector<llvm::Constant *> Array(NumElements);
1323 for (unsigned i = 0; i != NumElements; ++i)
1324 Array[i] = Element;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Chris Lattner2acc6e32011-07-18 04:24:23 +00001326 llvm::ArrayType *ATy =
Anders Carlsson2c12d032010-02-02 05:17:25 +00001327 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1328 return llvm::ConstantArray::get(ATy, Array);
Anders Carlsson237957c2009-08-09 18:26:27 +00001329 }
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001330
1331 if (const RecordType *RT = T->getAs<RecordType>()) {
Anders Carlsson2c12d032010-02-02 05:17:25 +00001332 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall9b7da1c2011-02-15 06:40:56 +00001333 return ::EmitNullConstant(*this, RD, /*complete object*/ true);
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001334 }
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001336 assert(T->isMemberPointerType() && "Should only see member pointers here!");
Anders Carlsson2c12d032010-02-02 05:17:25 +00001337 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1338 "Should only see pointers to data members here!");
1339
1340 // Itanium C++ ABI 2.3:
1341 // A NULL pointer is represented as -1.
John McCall5808ce42011-02-03 08:15:49 +00001342 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman0f593122009-04-13 21:47:26 +00001343}
Eli Friedman2ed7cb62011-10-14 02:27:24 +00001344
1345llvm::Constant *
1346CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
1347 return ::EmitNullConstant(*this, Record, false);
1348}