Bug Summary

File:tools/clang/lib/CodeGen/CGExprConstant.cpp
Warning:line 1664, column 21
Value stored to 'C' during its initialization is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGExprConstant.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp
1//===--- 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 "CGCXXABI.h"
16#include "CGObjCRuntime.h"
17#include "CGRecordLayout.h"
18#include "CodeGenModule.h"
19#include "ConstantEmitter.h"
20#include "TargetInfo.h"
21#include "clang/AST/APValue.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Basic/Builtins.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalVariable.h"
30using namespace clang;
31using namespace CodeGen;
32
33//===----------------------------------------------------------------------===//
34// ConstStructBuilder
35//===----------------------------------------------------------------------===//
36
37namespace {
38class ConstExprEmitter;
39class ConstStructBuilder {
40 CodeGenModule &CGM;
41 ConstantEmitter &Emitter;
42
43 bool Packed;
44 CharUnits NextFieldOffsetInChars;
45 CharUnits LLVMStructAlignment;
46 SmallVector<llvm::Constant *, 32> Elements;
47public:
48 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
49 ConstExprEmitter *ExprEmitter,
50 llvm::ConstantStruct *Base,
51 InitListExpr *Updater,
52 QualType ValTy);
53 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
54 InitListExpr *ILE, QualType StructTy);
55 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
56 const APValue &Value, QualType ValTy);
57
58private:
59 ConstStructBuilder(ConstantEmitter &emitter)
60 : CGM(emitter.CGM), Emitter(emitter), Packed(false),
61 NextFieldOffsetInChars(CharUnits::Zero()),
62 LLVMStructAlignment(CharUnits::One()) { }
63
64 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
65 llvm::Constant *InitExpr);
66
67 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
68
69 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
70 llvm::ConstantInt *InitExpr);
71
72 void AppendPadding(CharUnits PadSize);
73
74 void AppendTailPadding(CharUnits RecordSize);
75
76 void ConvertStructToPacked();
77
78 bool Build(InitListExpr *ILE);
79 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base,
80 InitListExpr *Updater);
81 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
82 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
83 llvm::Constant *Finalize(QualType Ty);
84
85 CharUnits getAlignment(const llvm::Constant *C) const {
86 if (Packed) return CharUnits::One();
87 return CharUnits::fromQuantity(
88 CGM.getDataLayout().getABITypeAlignment(C->getType()));
89 }
90
91 CharUnits getSizeInChars(const llvm::Constant *C) const {
92 return CharUnits::fromQuantity(
93 CGM.getDataLayout().getTypeAllocSize(C->getType()));
94 }
95};
96
97void ConstStructBuilder::
98AppendField(const FieldDecl *Field, uint64_t FieldOffset,
99 llvm::Constant *InitCst) {
100 const ASTContext &Context = CGM.getContext();
101
102 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
103
104 AppendBytes(FieldOffsetInChars, InitCst);
105}
106
107void ConstStructBuilder::
108AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
109
110 assert(NextFieldOffsetInChars <= FieldOffsetInChars(static_cast <bool> (NextFieldOffsetInChars <= FieldOffsetInChars
&& "Field offset mismatch!") ? void (0) : __assert_fail
("NextFieldOffsetInChars <= FieldOffsetInChars && \"Field offset mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 111, __extension__ __PRETTY_FUNCTION__))
111 && "Field offset mismatch!")(static_cast <bool> (NextFieldOffsetInChars <= FieldOffsetInChars
&& "Field offset mismatch!") ? void (0) : __assert_fail
("NextFieldOffsetInChars <= FieldOffsetInChars && \"Field offset mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 111, __extension__ __PRETTY_FUNCTION__))
;
112
113 CharUnits FieldAlignment = getAlignment(InitCst);
114
115 // Round up the field offset to the alignment of the field type.
116 CharUnits AlignedNextFieldOffsetInChars =
117 NextFieldOffsetInChars.alignTo(FieldAlignment);
118
119 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
120 // We need to append padding.
121 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
122
123 assert(NextFieldOffsetInChars == FieldOffsetInChars &&(static_cast <bool> (NextFieldOffsetInChars == FieldOffsetInChars
&& "Did not add enough padding!") ? void (0) : __assert_fail
("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 124, __extension__ __PRETTY_FUNCTION__))
124 "Did not add enough padding!")(static_cast <bool> (NextFieldOffsetInChars == FieldOffsetInChars
&& "Did not add enough padding!") ? void (0) : __assert_fail
("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 124, __extension__ __PRETTY_FUNCTION__))
;
125
126 AlignedNextFieldOffsetInChars =
127 NextFieldOffsetInChars.alignTo(FieldAlignment);
128 }
129
130 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
131 assert(!Packed && "Alignment is wrong even with a packed struct!")(static_cast <bool> (!Packed && "Alignment is wrong even with a packed struct!"
) ? void (0) : __assert_fail ("!Packed && \"Alignment is wrong even with a packed struct!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 131, __extension__ __PRETTY_FUNCTION__))
;
132
133 // Convert the struct to a packed struct.
134 ConvertStructToPacked();
135
136 // After we pack the struct, we may need to insert padding.
137 if (NextFieldOffsetInChars < FieldOffsetInChars) {
138 // We need to append padding.
139 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
140
141 assert(NextFieldOffsetInChars == FieldOffsetInChars &&(static_cast <bool> (NextFieldOffsetInChars == FieldOffsetInChars
&& "Did not add enough padding!") ? void (0) : __assert_fail
("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 142, __extension__ __PRETTY_FUNCTION__))
142 "Did not add enough padding!")(static_cast <bool> (NextFieldOffsetInChars == FieldOffsetInChars
&& "Did not add enough padding!") ? void (0) : __assert_fail
("NextFieldOffsetInChars == FieldOffsetInChars && \"Did not add enough padding!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 142, __extension__ __PRETTY_FUNCTION__))
;
143 }
144 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
145 }
146
147 // Add the field.
148 Elements.push_back(InitCst);
149 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
150 getSizeInChars(InitCst);
151
152 if (Packed)
153 assert(LLVMStructAlignment == CharUnits::One() &&(static_cast <bool> (LLVMStructAlignment == CharUnits::
One() && "Packed struct not byte-aligned!") ? void (0
) : __assert_fail ("LLVMStructAlignment == CharUnits::One() && \"Packed struct not byte-aligned!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 154, __extension__ __PRETTY_FUNCTION__))
154 "Packed struct not byte-aligned!")(static_cast <bool> (LLVMStructAlignment == CharUnits::
One() && "Packed struct not byte-aligned!") ? void (0
) : __assert_fail ("LLVMStructAlignment == CharUnits::One() && \"Packed struct not byte-aligned!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 154, __extension__ __PRETTY_FUNCTION__))
;
155 else
156 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
157}
158
159void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
160 uint64_t FieldOffset,
161 llvm::ConstantInt *CI) {
162 const ASTContext &Context = CGM.getContext();
163 const uint64_t CharWidth = Context.getCharWidth();
164 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
165 if (FieldOffset > NextFieldOffsetInBits) {
166 // We need to add padding.
167 CharUnits PadSize = Context.toCharUnitsFromBits(
168 llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
169 Context.getTargetInfo().getCharAlign()));
170
171 AppendPadding(PadSize);
172 }
173
174 uint64_t FieldSize = Field->getBitWidthValue(Context);
175
176 llvm::APInt FieldValue = CI->getValue();
177
178 // Promote the size of FieldValue if necessary
179 // FIXME: This should never occur, but currently it can because initializer
180 // constants are cast to bool, and because clang is not enforcing bitfield
181 // width limits.
182 if (FieldSize > FieldValue.getBitWidth())
183 FieldValue = FieldValue.zext(FieldSize);
184
185 // Truncate the size of FieldValue to the bit field size.
186 if (FieldSize < FieldValue.getBitWidth())
187 FieldValue = FieldValue.trunc(FieldSize);
188
189 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
190 if (FieldOffset < NextFieldOffsetInBits) {
191 // Either part of the field or the entire field can go into the previous
192 // byte.
193 assert(!Elements.empty() && "Elements can't be empty!")(static_cast <bool> (!Elements.empty() && "Elements can't be empty!"
) ? void (0) : __assert_fail ("!Elements.empty() && \"Elements can't be empty!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 193, __extension__ __PRETTY_FUNCTION__))
;
194
195 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
196
197 bool FitsCompletelyInPreviousByte =
198 BitsInPreviousByte >= FieldValue.getBitWidth();
199
200 llvm::APInt Tmp = FieldValue;
201
202 if (!FitsCompletelyInPreviousByte) {
203 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
204
205 if (CGM.getDataLayout().isBigEndian()) {
206 Tmp.lshrInPlace(NewFieldWidth);
207 Tmp = Tmp.trunc(BitsInPreviousByte);
208
209 // We want the remaining high bits.
210 FieldValue = FieldValue.trunc(NewFieldWidth);
211 } else {
212 Tmp = Tmp.trunc(BitsInPreviousByte);
213
214 // We want the remaining low bits.
215 FieldValue.lshrInPlace(BitsInPreviousByte);
216 FieldValue = FieldValue.trunc(NewFieldWidth);
217 }
218 }
219
220 Tmp = Tmp.zext(CharWidth);
221 if (CGM.getDataLayout().isBigEndian()) {
222 if (FitsCompletelyInPreviousByte)
223 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
224 } else {
225 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
226 }
227
228 // 'or' in the bits that go into the previous byte.
229 llvm::Value *LastElt = Elements.back();
230 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
231 Tmp |= Val->getValue();
232 else {
233 assert(isa<llvm::UndefValue>(LastElt))(static_cast <bool> (isa<llvm::UndefValue>(LastElt
)) ? void (0) : __assert_fail ("isa<llvm::UndefValue>(LastElt)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 233, __extension__ __PRETTY_FUNCTION__))
;
234 // If there is an undef field that we're adding to, it can either be a
235 // scalar undef (in which case, we just replace it with our field) or it
236 // is an array. If it is an array, we have to pull one byte off the
237 // array so that the other undef bytes stay around.
238 if (!isa<llvm::IntegerType>(LastElt->getType())) {
239 // The undef padding will be a multibyte array, create a new smaller
240 // padding and then an hole for our i8 to get plopped into.
241 assert(isa<llvm::ArrayType>(LastElt->getType()) &&(static_cast <bool> (isa<llvm::ArrayType>(LastElt
->getType()) && "Expected array padding of undefs"
) ? void (0) : __assert_fail ("isa<llvm::ArrayType>(LastElt->getType()) && \"Expected array padding of undefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 242, __extension__ __PRETTY_FUNCTION__))
242 "Expected array padding of undefs")(static_cast <bool> (isa<llvm::ArrayType>(LastElt
->getType()) && "Expected array padding of undefs"
) ? void (0) : __assert_fail ("isa<llvm::ArrayType>(LastElt->getType()) && \"Expected array padding of undefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 242, __extension__ __PRETTY_FUNCTION__))
;
243 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
244 assert(AT->getElementType()->isIntegerTy(CharWidth) &&(static_cast <bool> (AT->getElementType()->isIntegerTy
(CharWidth) && AT->getNumElements() != 0 &&
"Expected non-empty array padding of undefs") ? void (0) : __assert_fail
("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 246, __extension__ __PRETTY_FUNCTION__))
245 AT->getNumElements() != 0 &&(static_cast <bool> (AT->getElementType()->isIntegerTy
(CharWidth) && AT->getNumElements() != 0 &&
"Expected non-empty array padding of undefs") ? void (0) : __assert_fail
("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 246, __extension__ __PRETTY_FUNCTION__))
246 "Expected non-empty array padding of undefs")(static_cast <bool> (AT->getElementType()->isIntegerTy
(CharWidth) && AT->getNumElements() != 0 &&
"Expected non-empty array padding of undefs") ? void (0) : __assert_fail
("AT->getElementType()->isIntegerTy(CharWidth) && AT->getNumElements() != 0 && \"Expected non-empty array padding of undefs\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 246, __extension__ __PRETTY_FUNCTION__))
;
247
248 // Remove the padding array.
249 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
250 Elements.pop_back();
251
252 // Add the padding back in two chunks.
253 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
254 AppendPadding(CharUnits::One());
255 assert(isa<llvm::UndefValue>(Elements.back()) &&(static_cast <bool> (isa<llvm::UndefValue>(Elements
.back()) && Elements.back()->getType()->isIntegerTy
(CharWidth) && "Padding addition didn't work right") ?
void (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 257, __extension__ __PRETTY_FUNCTION__))
256 Elements.back()->getType()->isIntegerTy(CharWidth) &&(static_cast <bool> (isa<llvm::UndefValue>(Elements
.back()) && Elements.back()->getType()->isIntegerTy
(CharWidth) && "Padding addition didn't work right") ?
void (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 257, __extension__ __PRETTY_FUNCTION__))
257 "Padding addition didn't work right")(static_cast <bool> (isa<llvm::UndefValue>(Elements
.back()) && Elements.back()->getType()->isIntegerTy
(CharWidth) && "Padding addition didn't work right") ?
void (0) : __assert_fail ("isa<llvm::UndefValue>(Elements.back()) && Elements.back()->getType()->isIntegerTy(CharWidth) && \"Padding addition didn't work right\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 257, __extension__ __PRETTY_FUNCTION__))
;
258 }
259 }
260
261 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
262
263 if (FitsCompletelyInPreviousByte)
264 return;
265 }
266
267 while (FieldValue.getBitWidth() > CharWidth) {
268 llvm::APInt Tmp;
269
270 if (CGM.getDataLayout().isBigEndian()) {
271 // We want the high bits.
272 Tmp =
273 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
274 } else {
275 // We want the low bits.
276 Tmp = FieldValue.trunc(CharWidth);
277
278 FieldValue.lshrInPlace(CharWidth);
279 }
280
281 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
282 ++NextFieldOffsetInChars;
283
284 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
285 }
286
287 assert(FieldValue.getBitWidth() > 0 &&(static_cast <bool> (FieldValue.getBitWidth() > 0 &&
"Should have at least one bit left!") ? void (0) : __assert_fail
("FieldValue.getBitWidth() > 0 && \"Should have at least one bit left!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 288, __extension__ __PRETTY_FUNCTION__))
288 "Should have at least one bit left!")(static_cast <bool> (FieldValue.getBitWidth() > 0 &&
"Should have at least one bit left!") ? void (0) : __assert_fail
("FieldValue.getBitWidth() > 0 && \"Should have at least one bit left!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 288, __extension__ __PRETTY_FUNCTION__))
;
289 assert(FieldValue.getBitWidth() <= CharWidth &&(static_cast <bool> (FieldValue.getBitWidth() <= CharWidth
&& "Should not have more than a byte left!") ? void (
0) : __assert_fail ("FieldValue.getBitWidth() <= CharWidth && \"Should not have more than a byte left!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 290, __extension__ __PRETTY_FUNCTION__))
290 "Should not have more than a byte left!")(static_cast <bool> (FieldValue.getBitWidth() <= CharWidth
&& "Should not have more than a byte left!") ? void (
0) : __assert_fail ("FieldValue.getBitWidth() <= CharWidth && \"Should not have more than a byte left!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 290, __extension__ __PRETTY_FUNCTION__))
;
291
292 if (FieldValue.getBitWidth() < CharWidth) {
293 if (CGM.getDataLayout().isBigEndian()) {
294 unsigned BitWidth = FieldValue.getBitWidth();
295
296 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
297 } else
298 FieldValue = FieldValue.zext(CharWidth);
299 }
300
301 // Append the last element.
302 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
303 FieldValue));
304 ++NextFieldOffsetInChars;
305}
306
307void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
308 if (PadSize.isZero())
309 return;
310
311 llvm::Type *Ty = CGM.Int8Ty;
312 if (PadSize > CharUnits::One())
313 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
314
315 llvm::Constant *C = llvm::UndefValue::get(Ty);
316 Elements.push_back(C);
317 assert(getAlignment(C) == CharUnits::One() &&(static_cast <bool> (getAlignment(C) == CharUnits::One(
) && "Padding must have 1 byte alignment!") ? void (0
) : __assert_fail ("getAlignment(C) == CharUnits::One() && \"Padding must have 1 byte alignment!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
318 "Padding must have 1 byte alignment!")(static_cast <bool> (getAlignment(C) == CharUnits::One(
) && "Padding must have 1 byte alignment!") ? void (0
) : __assert_fail ("getAlignment(C) == CharUnits::One() && \"Padding must have 1 byte alignment!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 318, __extension__ __PRETTY_FUNCTION__))
;
319
320 NextFieldOffsetInChars += getSizeInChars(C);
321}
322
323void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
324 assert(NextFieldOffsetInChars <= RecordSize &&(static_cast <bool> (NextFieldOffsetInChars <= RecordSize
&& "Size mismatch!") ? void (0) : __assert_fail ("NextFieldOffsetInChars <= RecordSize && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 325, __extension__ __PRETTY_FUNCTION__))
325 "Size mismatch!")(static_cast <bool> (NextFieldOffsetInChars <= RecordSize
&& "Size mismatch!") ? void (0) : __assert_fail ("NextFieldOffsetInChars <= RecordSize && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 325, __extension__ __PRETTY_FUNCTION__))
;
326
327 AppendPadding(RecordSize - NextFieldOffsetInChars);
328}
329
330void ConstStructBuilder::ConvertStructToPacked() {
331 SmallVector<llvm::Constant *, 16> PackedElements;
332 CharUnits ElementOffsetInChars = CharUnits::Zero();
333
334 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
335 llvm::Constant *C = Elements[i];
336
337 CharUnits ElementAlign = CharUnits::fromQuantity(
338 CGM.getDataLayout().getABITypeAlignment(C->getType()));
339 CharUnits AlignedElementOffsetInChars =
340 ElementOffsetInChars.alignTo(ElementAlign);
341
342 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
343 // We need some padding.
344 CharUnits NumChars =
345 AlignedElementOffsetInChars - ElementOffsetInChars;
346
347 llvm::Type *Ty = CGM.Int8Ty;
348 if (NumChars > CharUnits::One())
349 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
350
351 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
352 PackedElements.push_back(Padding);
353 ElementOffsetInChars += getSizeInChars(Padding);
354 }
355
356 PackedElements.push_back(C);
357 ElementOffsetInChars += getSizeInChars(C);
358 }
359
360 assert(ElementOffsetInChars == NextFieldOffsetInChars &&(static_cast <bool> (ElementOffsetInChars == NextFieldOffsetInChars
&& "Packing the struct changed its size!") ? void (0
) : __assert_fail ("ElementOffsetInChars == NextFieldOffsetInChars && \"Packing the struct changed its size!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 361, __extension__ __PRETTY_FUNCTION__))
361 "Packing the struct changed its size!")(static_cast <bool> (ElementOffsetInChars == NextFieldOffsetInChars
&& "Packing the struct changed its size!") ? void (0
) : __assert_fail ("ElementOffsetInChars == NextFieldOffsetInChars && \"Packing the struct changed its size!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 361, __extension__ __PRETTY_FUNCTION__))
;
362
363 Elements.swap(PackedElements);
364 LLVMStructAlignment = CharUnits::One();
365 Packed = true;
366}
367
368bool ConstStructBuilder::Build(InitListExpr *ILE) {
369 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
370 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
371
372 unsigned FieldNo = 0;
373 unsigned ElementNo = 0;
374
375 // Bail out if we have base classes. We could support these, but they only
376 // arise in C++1z where we will have already constant folded most interesting
377 // cases. FIXME: There are still a few more cases we can handle this way.
378 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
379 if (CXXRD->getNumBases())
380 return false;
381
382 for (RecordDecl::field_iterator Field = RD->field_begin(),
383 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
384 // If this is a union, skip all the fields that aren't being initialized.
385 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
386 continue;
387
388 // Don't emit anonymous bitfields, they just affect layout.
389 if (Field->isUnnamedBitfield())
390 continue;
391
392 // Get the initializer. A struct can include fields without initializers,
393 // we just use explicit null values for them.
394 llvm::Constant *EltInit;
395 if (ElementNo < ILE->getNumInits())
396 EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
397 Field->getType());
398 else
399 EltInit = Emitter.emitNullForMemory(Field->getType());
400
401 if (!EltInit)
402 return false;
403
404 if (!Field->isBitField()) {
405 // Handle non-bitfield members.
406 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
407 } else {
408 // Otherwise we have a bitfield.
409 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
410 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
411 } else {
412 // We are trying to initialize a bitfield with a non-trivial constant,
413 // this must require run-time code.
414 return false;
415 }
416 }
417 }
418
419 return true;
420}
421
422namespace {
423struct BaseInfo {
424 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
425 : Decl(Decl), Offset(Offset), Index(Index) {
426 }
427
428 const CXXRecordDecl *Decl;
429 CharUnits Offset;
430 unsigned Index;
431
432 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
433};
434}
435
436bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
437 bool IsPrimaryBase,
438 const CXXRecordDecl *VTableClass,
439 CharUnits Offset) {
440 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
441
442 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
443 // Add a vtable pointer, if we need one and it hasn't already been added.
444 if (CD->isDynamicClass() && !IsPrimaryBase) {
445 llvm::Constant *VTableAddressPoint =
446 CGM.getCXXABI().getVTableAddressPointForConstExpr(
447 BaseSubobject(CD, Offset), VTableClass);
448 AppendBytes(Offset, VTableAddressPoint);
449 }
450
451 // Accumulate and sort bases, in order to visit them in address order, which
452 // may not be the same as declaration order.
453 SmallVector<BaseInfo, 8> Bases;
454 Bases.reserve(CD->getNumBases());
455 unsigned BaseNo = 0;
456 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
457 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
458 assert(!Base->isVirtual() && "should not have virtual bases here")(static_cast <bool> (!Base->isVirtual() && "should not have virtual bases here"
) ? void (0) : __assert_fail ("!Base->isVirtual() && \"should not have virtual bases here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 458, __extension__ __PRETTY_FUNCTION__))
;
459 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
460 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
461 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
462 }
463 std::stable_sort(Bases.begin(), Bases.end());
464
465 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
466 BaseInfo &Base = Bases[I];
467
468 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
469 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
470 VTableClass, Offset + Base.Offset);
471 }
472 }
473
474 unsigned FieldNo = 0;
475 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
476
477 for (RecordDecl::field_iterator Field = RD->field_begin(),
478 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
479 // If this is a union, skip all the fields that aren't being initialized.
480 if (RD->isUnion() && Val.getUnionField() != *Field)
481 continue;
482
483 // Don't emit anonymous bitfields, they just affect layout.
484 if (Field->isUnnamedBitfield())
485 continue;
486
487 // Emit the value of the initializer.
488 const APValue &FieldValue =
489 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
490 llvm::Constant *EltInit =
491 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
492 if (!EltInit)
493 return false;
494
495 if (!Field->isBitField()) {
496 // Handle non-bitfield members.
497 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
498 } else {
499 // Otherwise we have a bitfield.
500 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
501 cast<llvm::ConstantInt>(EltInit));
502 }
503 }
504
505 return true;
506}
507
508llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
509 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
510 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
511
512 CharUnits LayoutSizeInChars = Layout.getSize();
513
514 if (NextFieldOffsetInChars > LayoutSizeInChars) {
515 // If the struct is bigger than the size of the record type,
516 // we must have a flexible array member at the end.
517 assert(RD->hasFlexibleArrayMember() &&(static_cast <bool> (RD->hasFlexibleArrayMember() &&
"Must have flexible array member if struct is bigger than type!"
) ? void (0) : __assert_fail ("RD->hasFlexibleArrayMember() && \"Must have flexible array member if struct is bigger than type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 518, __extension__ __PRETTY_FUNCTION__))
518 "Must have flexible array member if struct is bigger than type!")(static_cast <bool> (RD->hasFlexibleArrayMember() &&
"Must have flexible array member if struct is bigger than type!"
) ? void (0) : __assert_fail ("RD->hasFlexibleArrayMember() && \"Must have flexible array member if struct is bigger than type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 518, __extension__ __PRETTY_FUNCTION__))
;
519
520 // No tail padding is necessary.
521 } else {
522 // Append tail padding if necessary.
523 CharUnits LLVMSizeInChars =
524 NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
525
526 if (LLVMSizeInChars != LayoutSizeInChars)
527 AppendTailPadding(LayoutSizeInChars);
528
529 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
530
531 // Check if we need to convert the struct to a packed struct.
532 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
533 LLVMSizeInChars > LayoutSizeInChars) {
534 assert(!Packed && "Size mismatch!")(static_cast <bool> (!Packed && "Size mismatch!"
) ? void (0) : __assert_fail ("!Packed && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 534, __extension__ __PRETTY_FUNCTION__))
;
535
536 ConvertStructToPacked();
537 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&(static_cast <bool> (NextFieldOffsetInChars <= LayoutSizeInChars
&& "Converting to packed did not help!") ? void (0) :
__assert_fail ("NextFieldOffsetInChars <= LayoutSizeInChars && \"Converting to packed did not help!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 538, __extension__ __PRETTY_FUNCTION__))
538 "Converting to packed did not help!")(static_cast <bool> (NextFieldOffsetInChars <= LayoutSizeInChars
&& "Converting to packed did not help!") ? void (0) :
__assert_fail ("NextFieldOffsetInChars <= LayoutSizeInChars && \"Converting to packed did not help!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 538, __extension__ __PRETTY_FUNCTION__))
;
539 }
540
541 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
542
543 assert(LayoutSizeInChars == LLVMSizeInChars &&(static_cast <bool> (LayoutSizeInChars == LLVMSizeInChars
&& "Tail padding mismatch!") ? void (0) : __assert_fail
("LayoutSizeInChars == LLVMSizeInChars && \"Tail padding mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 544, __extension__ __PRETTY_FUNCTION__))
544 "Tail padding mismatch!")(static_cast <bool> (LayoutSizeInChars == LLVMSizeInChars
&& "Tail padding mismatch!") ? void (0) : __assert_fail
("LayoutSizeInChars == LLVMSizeInChars && \"Tail padding mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 544, __extension__ __PRETTY_FUNCTION__))
;
545 }
546
547 // Pick the type to use. If the type is layout identical to the ConvertType
548 // type then use it, otherwise use whatever the builder produced for us.
549 llvm::StructType *STy =
550 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
551 Elements, Packed);
552 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
553 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
554 if (ValSTy->isLayoutIdentical(STy))
555 STy = ValSTy;
556 }
557
558 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
559
560 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==(static_cast <bool> (NextFieldOffsetInChars.alignTo(getAlignment
(Result)) == getSizeInChars(Result) && "Size mismatch!"
) ? void (0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 562, __extension__ __PRETTY_FUNCTION__))
561 getSizeInChars(Result) &&(static_cast <bool> (NextFieldOffsetInChars.alignTo(getAlignment
(Result)) == getSizeInChars(Result) && "Size mismatch!"
) ? void (0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 562, __extension__ __PRETTY_FUNCTION__))
562 "Size mismatch!")(static_cast <bool> (NextFieldOffsetInChars.alignTo(getAlignment
(Result)) == getSizeInChars(Result) && "Size mismatch!"
) ? void (0) : __assert_fail ("NextFieldOffsetInChars.alignTo(getAlignment(Result)) == getSizeInChars(Result) && \"Size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 562, __extension__ __PRETTY_FUNCTION__))
;
563
564 return Result;
565}
566
567llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
568 ConstExprEmitter *ExprEmitter,
569 llvm::ConstantStruct *Base,
570 InitListExpr *Updater,
571 QualType ValTy) {
572 ConstStructBuilder Builder(Emitter);
573 if (!Builder.Build(ExprEmitter, Base, Updater))
574 return nullptr;
575 return Builder.Finalize(ValTy);
576}
577
578llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
579 InitListExpr *ILE,
580 QualType ValTy) {
581 ConstStructBuilder Builder(Emitter);
582
583 if (!Builder.Build(ILE))
584 return nullptr;
585
586 return Builder.Finalize(ValTy);
587}
588
589llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
590 const APValue &Val,
591 QualType ValTy) {
592 ConstStructBuilder Builder(Emitter);
593
594 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
595 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
596 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
597 return nullptr;
598
599 return Builder.Finalize(ValTy);
600}
601
602
603//===----------------------------------------------------------------------===//
604// ConstExprEmitter
605//===----------------------------------------------------------------------===//
606
607static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
608 CodeGenFunction *CGF,
609 const CompoundLiteralExpr *E) {
610 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
611 if (llvm::GlobalVariable *Addr =
612 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
613 return ConstantAddress(Addr, Align);
614
615 LangAS addressSpace = E->getType().getAddressSpace();
616
617 ConstantEmitter emitter(CGM, CGF);
618 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
619 addressSpace, E->getType());
620 if (!C) {
621 assert(!E->isFileScope() &&(static_cast <bool> (!E->isFileScope() && "file-scope compound literal did not have constant initializer!"
) ? void (0) : __assert_fail ("!E->isFileScope() && \"file-scope compound literal did not have constant initializer!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 622, __extension__ __PRETTY_FUNCTION__))
622 "file-scope compound literal did not have constant initializer!")(static_cast <bool> (!E->isFileScope() && "file-scope compound literal did not have constant initializer!"
) ? void (0) : __assert_fail ("!E->isFileScope() && \"file-scope compound literal did not have constant initializer!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 622, __extension__ __PRETTY_FUNCTION__))
;
623 return ConstantAddress::invalid();
624 }
625
626 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
627 CGM.isTypeConstant(E->getType(), true),
628 llvm::GlobalValue::InternalLinkage,
629 C, ".compoundliteral", nullptr,
630 llvm::GlobalVariable::NotThreadLocal,
631 CGM.getContext().getTargetAddressSpace(addressSpace));
632 emitter.finalize(GV);
633 GV->setAlignment(Align.getQuantity());
634 CGM.setAddrOfConstantCompoundLiteral(E, GV);
635 return ConstantAddress(GV, Align);
636}
637
638/// This class only needs to handle two cases:
639/// 1) Literals (this is used by APValue emission to emit literals).
640/// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
641/// constant fold these types).
642class ConstExprEmitter :
643 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
644 CodeGenModule &CGM;
645 ConstantEmitter &Emitter;
646 llvm::LLVMContext &VMContext;
647public:
648 ConstExprEmitter(ConstantEmitter &emitter)
649 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
650 }
651
652 //===--------------------------------------------------------------------===//
653 // Visitor Methods
654 //===--------------------------------------------------------------------===//
655
656 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
657 return nullptr;
658 }
659
660 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
661 return Visit(PE->getSubExpr(), T);
662 }
663
664 llvm::Constant *
665 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
666 QualType T) {
667 return Visit(PE->getReplacement(), T);
668 }
669
670 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
671 QualType T) {
672 return Visit(GE->getResultExpr(), T);
673 }
674
675 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
676 return Visit(CE->getChosenSubExpr(), T);
677 }
678
679 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
680 return Visit(E->getInitializer(), T);
681 }
682
683 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
684 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
685 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
686 Expr *subExpr = E->getSubExpr();
687
688 switch (E->getCastKind()) {
689 case CK_ToUnion: {
690 // GCC cast to union extension
691 assert(E->getType()->isUnionType() &&(static_cast <bool> (E->getType()->isUnionType() &&
"Destination type is not union type!") ? void (0) : __assert_fail
("E->getType()->isUnionType() && \"Destination type is not union type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 692, __extension__ __PRETTY_FUNCTION__))
692 "Destination type is not union type!")(static_cast <bool> (E->getType()->isUnionType() &&
"Destination type is not union type!") ? void (0) : __assert_fail
("E->getType()->isUnionType() && \"Destination type is not union type!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 692, __extension__ __PRETTY_FUNCTION__))
;
693
694 auto field = E->getTargetUnionField();
695
696 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
697 if (!C) return nullptr;
698
699 auto destTy = ConvertType(destType);
700 if (C->getType() == destTy) return C;
701
702 // Build a struct with the union sub-element as the first member,
703 // and padded to the appropriate size.
704 SmallVector<llvm::Constant*, 2> Elts;
705 SmallVector<llvm::Type*, 2> Types;
706 Elts.push_back(C);
707 Types.push_back(C->getType());
708 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
709 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
710
711 assert(CurSize <= TotalSize && "Union size mismatch!")(static_cast <bool> (CurSize <= TotalSize &&
"Union size mismatch!") ? void (0) : __assert_fail ("CurSize <= TotalSize && \"Union size mismatch!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 711, __extension__ __PRETTY_FUNCTION__))
;
712 if (unsigned NumPadBytes = TotalSize - CurSize) {
713 llvm::Type *Ty = CGM.Int8Ty;
714 if (NumPadBytes > 1)
715 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
716
717 Elts.push_back(llvm::UndefValue::get(Ty));
718 Types.push_back(Ty);
719 }
720
721 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
722 return llvm::ConstantStruct::get(STy, Elts);
723 }
724
725 case CK_AddressSpaceConversion: {
726 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
727 if (!C) return nullptr;
728 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
729 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
730 llvm::Type *destTy = ConvertType(E->getType());
731 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
732 destAS, destTy);
733 }
734
735 case CK_LValueToRValue:
736 case CK_AtomicToNonAtomic:
737 case CK_NonAtomicToAtomic:
738 case CK_NoOp:
739 case CK_ConstructorConversion:
740 return Visit(subExpr, destType);
741
742 case CK_IntToOCLSampler:
743 llvm_unreachable("global sampler variables are not generated")::llvm::llvm_unreachable_internal("global sampler variables are not generated"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 743)
;
744
745 case CK_Dependent: llvm_unreachable("saw dependent cast!")::llvm::llvm_unreachable_internal("saw dependent cast!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 745)
;
746
747 case CK_BuiltinFnToFnPtr:
748 llvm_unreachable("builtin functions are handled elsewhere")::llvm::llvm_unreachable_internal("builtin functions are handled elsewhere"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 748)
;
749
750 case CK_ReinterpretMemberPointer:
751 case CK_DerivedToBaseMemberPointer:
752 case CK_BaseToDerivedMemberPointer: {
753 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
754 if (!C) return nullptr;
755 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
756 }
757
758 // These will never be supported.
759 case CK_ObjCObjectLValueCast:
760 case CK_ARCProduceObject:
761 case CK_ARCConsumeObject:
762 case CK_ARCReclaimReturnedObject:
763 case CK_ARCExtendBlockObject:
764 case CK_CopyAndAutoreleaseBlockObject:
765 return nullptr;
766
767 // These don't need to be handled here because Evaluate knows how to
768 // evaluate them in the cases where they can be folded.
769 case CK_BitCast:
770 case CK_ToVoid:
771 case CK_Dynamic:
772 case CK_LValueBitCast:
773 case CK_NullToMemberPointer:
774 case CK_UserDefinedConversion:
775 case CK_CPointerToObjCPointerCast:
776 case CK_BlockPointerToObjCPointerCast:
777 case CK_AnyPointerToBlockPointerCast:
778 case CK_ArrayToPointerDecay:
779 case CK_FunctionToPointerDecay:
780 case CK_BaseToDerived:
781 case CK_DerivedToBase:
782 case CK_UncheckedDerivedToBase:
783 case CK_MemberPointerToBoolean:
784 case CK_VectorSplat:
785 case CK_FloatingRealToComplex:
786 case CK_FloatingComplexToReal:
787 case CK_FloatingComplexToBoolean:
788 case CK_FloatingComplexCast:
789 case CK_FloatingComplexToIntegralComplex:
790 case CK_IntegralRealToComplex:
791 case CK_IntegralComplexToReal:
792 case CK_IntegralComplexToBoolean:
793 case CK_IntegralComplexCast:
794 case CK_IntegralComplexToFloatingComplex:
795 case CK_PointerToIntegral:
796 case CK_PointerToBoolean:
797 case CK_NullToPointer:
798 case CK_IntegralCast:
799 case CK_BooleanToSignedIntegral:
800 case CK_IntegralToPointer:
801 case CK_IntegralToBoolean:
802 case CK_IntegralToFloating:
803 case CK_FloatingToIntegral:
804 case CK_FloatingToBoolean:
805 case CK_FloatingCast:
806 case CK_ZeroToOCLEvent:
807 case CK_ZeroToOCLQueue:
808 return nullptr;
809 }
810 llvm_unreachable("Invalid CastKind")::llvm::llvm_unreachable_internal("Invalid CastKind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 810)
;
811 }
812
813 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
814 return Visit(DAE->getExpr(), T);
815 }
816
817 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
818 // No need for a DefaultInitExprScope: we don't handle 'this' in a
819 // constant expression.
820 return Visit(DIE->getExpr(), T);
821 }
822
823 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
824 if (!E->cleanupsHaveSideEffects())
825 return Visit(E->getSubExpr(), T);
826 return nullptr;
827 }
828
829 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
830 QualType T) {
831 return Visit(E->GetTemporaryExpr(), T);
832 }
833
834 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
835 llvm::ArrayType *AType =
836 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
837 llvm::Type *ElemTy = AType->getElementType();
838 unsigned NumInitElements = ILE->getNumInits();
839 unsigned NumElements = AType->getNumElements();
840
841 // Initialising an array requires us to automatically
842 // initialise any elements that have not been initialised explicitly
843 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
844
845 QualType EltType = CGM.getContext().getAsArrayType(T)->getElementType();
846
847 // Initialize remaining array elements.
848 llvm::Constant *fillC;
849 if (Expr *filler = ILE->getArrayFiller())
850 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
851 else
852 fillC = Emitter.emitNullForMemory(EltType);
853 if (!fillC)
854 return nullptr;
855
856 // Try to use a ConstantAggregateZero if we can.
857 if (fillC->isNullValue() && !NumInitableElts)
858 return llvm::ConstantAggregateZero::get(AType);
859
860 // Copy initializer elements.
861 SmallVector<llvm::Constant*, 16> Elts;
862 Elts.reserve(std::max(NumInitableElts, NumElements));
863
864 bool RewriteType = false;
865 bool AllNullValues = true;
866 for (unsigned i = 0; i < NumInitableElts; ++i) {
867 Expr *Init = ILE->getInit(i);
868 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
869 if (!C)
870 return nullptr;
871 RewriteType |= (C->getType() != ElemTy);
872 Elts.push_back(C);
873 if (AllNullValues && !C->isNullValue())
874 AllNullValues = false;
875 }
876
877 // If all initializer elements are "zero," then avoid storing NumElements
878 // instances of the zero representation.
879 if (AllNullValues)
880 return llvm::ConstantAggregateZero::get(AType);
881
882 RewriteType |= (fillC->getType() != ElemTy);
883 Elts.resize(NumElements, fillC);
884
885 if (RewriteType) {
886 // FIXME: Try to avoid packing the array
887 std::vector<llvm::Type*> Types;
888 Types.reserve(Elts.size());
889 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
890 Types.push_back(Elts[i]->getType());
891 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
892 Types, true);
893 return llvm::ConstantStruct::get(SType, Elts);
894 }
895
896 return llvm::ConstantArray::get(AType, Elts);
897 }
898
899 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
900 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
901 }
902
903 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
904 QualType T) {
905 return CGM.EmitNullConstant(T);
906 }
907
908 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
909 if (ILE->isTransparent())
910 return Visit(ILE->getInit(0), T);
911
912 if (ILE->getType()->isArrayType())
913 return EmitArrayInitialization(ILE, T);
914
915 if (ILE->getType()->isRecordType())
916 return EmitRecordInitialization(ILE, T);
917
918 return nullptr;
919 }
920
921 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
922 InitListExpr *Updater,
923 QualType destType) {
924 if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
925 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
926 llvm::Type *ElemType = AType->getElementType();
927
928 unsigned NumInitElements = Updater->getNumInits();
929 unsigned NumElements = AType->getNumElements();
930
931 std::vector<llvm::Constant *> Elts;
932 Elts.reserve(NumElements);
933
934 QualType destElemType = destAT->getElementType();
935
936 if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
937 for (unsigned i = 0; i != NumElements; ++i)
938 Elts.push_back(DataArray->getElementAsConstant(i));
939 else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
940 for (unsigned i = 0; i != NumElements; ++i)
941 Elts.push_back(Array->getOperand(i));
942 else
943 return nullptr; // FIXME: other array types not implemented
944
945 llvm::Constant *fillC = nullptr;
946 if (Expr *filler = Updater->getArrayFiller())
947 if (!isa<NoInitExpr>(filler))
948 fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
949 bool RewriteType = (fillC && fillC->getType() != ElemType);
950
951 for (unsigned i = 0; i != NumElements; ++i) {
952 Expr *Init = nullptr;
953 if (i < NumInitElements)
954 Init = Updater->getInit(i);
955
956 if (!Init && fillC)
957 Elts[i] = fillC;
958 else if (!Init || isa<NoInitExpr>(Init))
959 ; // Do nothing.
960 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
961 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
962 else
963 Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
964
965 if (!Elts[i])
966 return nullptr;
967 RewriteType |= (Elts[i]->getType() != ElemType);
968 }
969
970 if (RewriteType) {
971 std::vector<llvm::Type *> Types;
972 Types.reserve(NumElements);
973 for (unsigned i = 0; i != NumElements; ++i)
974 Types.push_back(Elts[i]->getType());
975 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
976 Types, true);
977 return llvm::ConstantStruct::get(SType, Elts);
978 }
979
980 return llvm::ConstantArray::get(AType, Elts);
981 }
982
983 if (destType->isRecordType())
984 return ConstStructBuilder::BuildStruct(Emitter, this,
985 dyn_cast<llvm::ConstantStruct>(Base), Updater, destType);
986
987 return nullptr;
988 }
989
990 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
991 QualType destType) {
992 auto C = Visit(E->getBase(), destType);
993 if (!C) return nullptr;
994 return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
995 }
996
997 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
998 if (!E->getConstructor()->isTrivial())
999 return nullptr;
1000
1001 // FIXME: We should not have to call getBaseElementType here.
1002 const RecordType *RT =
1003 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1004 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1005
1006 // If the class doesn't have a trivial destructor, we can't emit it as a
1007 // constant expr.
1008 if (!RD->hasTrivialDestructor())
1009 return nullptr;
1010
1011 // Only copy and default constructors can be trivial.
1012
1013
1014 if (E->getNumArgs()) {
1015 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument")(static_cast <bool> (E->getNumArgs() == 1 &&
"trivial ctor with > 1 argument") ? void (0) : __assert_fail
("E->getNumArgs() == 1 && \"trivial ctor with > 1 argument\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1015, __extension__ __PRETTY_FUNCTION__))
;
1016 assert(E->getConstructor()->isCopyOrMoveConstructor() &&(static_cast <bool> (E->getConstructor()->isCopyOrMoveConstructor
() && "trivial ctor has argument but isn't a copy/move ctor"
) ? void (0) : __assert_fail ("E->getConstructor()->isCopyOrMoveConstructor() && \"trivial ctor has argument but isn't a copy/move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1017, __extension__ __PRETTY_FUNCTION__))
1017 "trivial ctor has argument but isn't a copy/move ctor")(static_cast <bool> (E->getConstructor()->isCopyOrMoveConstructor
() && "trivial ctor has argument but isn't a copy/move ctor"
) ? void (0) : __assert_fail ("E->getConstructor()->isCopyOrMoveConstructor() && \"trivial ctor has argument but isn't a copy/move ctor\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018
1019 Expr *Arg = E->getArg(0);
1020 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&(static_cast <bool> (CGM.getContext().hasSameUnqualifiedType
(Ty, Arg->getType()) && "argument to copy ctor is of wrong type"
) ? void (0) : __assert_fail ("CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && \"argument to copy ctor is of wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1021, __extension__ __PRETTY_FUNCTION__))
1021 "argument to copy ctor is of wrong type")(static_cast <bool> (CGM.getContext().hasSameUnqualifiedType
(Ty, Arg->getType()) && "argument to copy ctor is of wrong type"
) ? void (0) : __assert_fail ("CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && \"argument to copy ctor is of wrong type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022
1023 return Visit(Arg, Ty);
1024 }
1025
1026 return CGM.EmitNullConstant(Ty);
1027 }
1028
1029 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1030 return CGM.GetConstantArrayFromStringLiteral(E);
1031 }
1032
1033 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1034 // This must be an @encode initializing an array in a static initializer.
1035 // Don't emit it as the address of the string, emit the string data itself
1036 // as an inline array.
1037 std::string Str;
1038 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1039 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1040
1041 // Resize the string to the right size, adding zeros at the end, or
1042 // truncating as needed.
1043 Str.resize(CAT->getSize().getZExtValue(), '\0');
1044 return llvm::ConstantDataArray::getString(VMContext, Str, false);
1045 }
1046
1047 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1048 return Visit(E->getSubExpr(), T);
1049 }
1050
1051 // Utility methods
1052 llvm::Type *ConvertType(QualType T) {
1053 return CGM.getTypes().ConvertType(T);
1054 }
1055};
1056
1057} // end anonymous namespace.
1058
1059bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1060 llvm::ConstantStruct *Base,
1061 InitListExpr *Updater) {
1062 assert(Base && "base expression should not be empty")(static_cast <bool> (Base && "base expression should not be empty"
) ? void (0) : __assert_fail ("Base && \"base expression should not be empty\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1062, __extension__ __PRETTY_FUNCTION__))
;
1063
1064 QualType ExprType = Updater->getType();
1065 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1066 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1067 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1068 Base->getType());
1069 unsigned FieldNo = -1;
1070 unsigned ElementNo = 0;
1071
1072 // Bail out if we have base classes. We could support these, but they only
1073 // arise in C++1z where we will have already constant folded most interesting
1074 // cases. FIXME: There are still a few more cases we can handle this way.
1075 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1076 if (CXXRD->getNumBases())
1077 return false;
1078
1079 for (FieldDecl *Field : RD->fields()) {
1080 ++FieldNo;
1081
1082 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1083 continue;
1084
1085 // Skip anonymous bitfields.
1086 if (Field->isUnnamedBitfield())
1087 continue;
1088
1089 llvm::Constant *EltInit = Base->getOperand(ElementNo);
1090
1091 // Bail out if the type of the ConstantStruct does not have the same layout
1092 // as the type of the InitListExpr.
1093 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1094 Layout.getFieldOffset(ElementNo) !=
1095 BaseLayout->getElementOffsetInBits(ElementNo))
1096 return false;
1097
1098 // Get the initializer. If we encounter an empty field or a NoInitExpr,
1099 // we use values from the base expression.
1100 Expr *Init = nullptr;
1101 if (ElementNo < Updater->getNumInits())
1102 Init = Updater->getInit(ElementNo);
1103
1104 if (!Init || isa<NoInitExpr>(Init))
1105 ; // Do nothing.
1106 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1107 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1108 Field->getType());
1109 else
1110 EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
1111
1112 ++ElementNo;
1113
1114 if (!EltInit)
1115 return false;
1116
1117 if (!Field->isBitField())
1118 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1119 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1120 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1121 else
1122 // Initializing a bitfield with a non-trivial constant?
1123 return false;
1124 }
1125
1126 return true;
1127}
1128
1129llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1130 AbstractState saved) {
1131 Abstract = saved.OldValue;
1132
1133 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&(static_cast <bool> (saved.OldPlaceholdersSize == PlaceholderAddresses
.size() && "created a placeholder while doing an abstract emission?"
) ? void (0) : __assert_fail ("saved.OldPlaceholdersSize == PlaceholderAddresses.size() && \"created a placeholder while doing an abstract emission?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1134, __extension__ __PRETTY_FUNCTION__))
1134 "created a placeholder while doing an abstract emission?")(static_cast <bool> (saved.OldPlaceholdersSize == PlaceholderAddresses
.size() && "created a placeholder while doing an abstract emission?"
) ? void (0) : __assert_fail ("saved.OldPlaceholdersSize == PlaceholderAddresses.size() && \"created a placeholder while doing an abstract emission?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1134, __extension__ __PRETTY_FUNCTION__))
;
1135
1136 // No validation necessary for now.
1137 // No cleanup to do for now.
1138 return C;
1139}
1140
1141llvm::Constant *
1142ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1143 auto state = pushAbstract();
1144 auto C = tryEmitPrivateForVarInit(D);
1145 return validateAndPopAbstract(C, state);
1146}
1147
1148llvm::Constant *
1149ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1150 auto state = pushAbstract();
1151 auto C = tryEmitPrivate(E, destType);
1152 return validateAndPopAbstract(C, state);
1153}
1154
1155llvm::Constant *
1156ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1157 auto state = pushAbstract();
1158 auto C = tryEmitPrivate(value, destType);
1159 return validateAndPopAbstract(C, state);
1160}
1161
1162llvm::Constant *
1163ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1164 auto state = pushAbstract();
1165 auto C = tryEmitPrivate(E, destType);
1166 C = validateAndPopAbstract(C, state);
1167 if (!C) {
1168 CGM.Error(E->getExprLoc(),
1169 "internal error: could not emit constant value \"abstractly\"");
1170 C = CGM.EmitNullConstant(destType);
1171 }
1172 return C;
1173}
1174
1175llvm::Constant *
1176ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1177 QualType destType) {
1178 auto state = pushAbstract();
1179 auto C = tryEmitPrivate(value, destType);
1180 C = validateAndPopAbstract(C, state);
1181 if (!C) {
1182 CGM.Error(loc,
1183 "internal error: could not emit constant value \"abstractly\"");
1184 C = CGM.EmitNullConstant(destType);
1185 }
1186 return C;
1187}
1188
1189llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1190 initializeNonAbstract(D.getType().getAddressSpace());
1191 return markIfFailed(tryEmitPrivateForVarInit(D));
1192}
1193
1194llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1195 LangAS destAddrSpace,
1196 QualType destType) {
1197 initializeNonAbstract(destAddrSpace);
1198 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1199}
1200
1201llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1202 LangAS destAddrSpace,
1203 QualType destType) {
1204 initializeNonAbstract(destAddrSpace);
1205 auto C = tryEmitPrivateForMemory(value, destType);
1206 assert(C && "couldn't emit constant value non-abstractly?")(static_cast <bool> (C && "couldn't emit constant value non-abstractly?"
) ? void (0) : __assert_fail ("C && \"couldn't emit constant value non-abstractly?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1206, __extension__ __PRETTY_FUNCTION__))
;
1207 return C;
1208}
1209
1210llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1211 assert(!Abstract && "cannot get current address for abstract constant")(static_cast <bool> (!Abstract && "cannot get current address for abstract constant"
) ? void (0) : __assert_fail ("!Abstract && \"cannot get current address for abstract constant\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1211, __extension__ __PRETTY_FUNCTION__))
;
1212
1213
1214
1215 // Make an obviously ill-formed global that should blow up compilation
1216 // if it survives.
1217 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1218 llvm::GlobalValue::PrivateLinkage,
1219 /*init*/ nullptr,
1220 /*name*/ "",
1221 /*before*/ nullptr,
1222 llvm::GlobalVariable::NotThreadLocal,
1223 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1224
1225 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1226
1227 return global;
1228}
1229
1230void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1231 llvm::GlobalValue *placeholder) {
1232 assert(!PlaceholderAddresses.empty())(static_cast <bool> (!PlaceholderAddresses.empty()) ? void
(0) : __assert_fail ("!PlaceholderAddresses.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1232, __extension__ __PRETTY_FUNCTION__))
;
1233 assert(PlaceholderAddresses.back().first == nullptr)(static_cast <bool> (PlaceholderAddresses.back().first ==
nullptr) ? void (0) : __assert_fail ("PlaceholderAddresses.back().first == nullptr"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1233, __extension__ __PRETTY_FUNCTION__))
;
1234 assert(PlaceholderAddresses.back().second == placeholder)(static_cast <bool> (PlaceholderAddresses.back().second
== placeholder) ? void (0) : __assert_fail ("PlaceholderAddresses.back().second == placeholder"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1234, __extension__ __PRETTY_FUNCTION__))
;
1235 PlaceholderAddresses.back().first = signal;
1236}
1237
1238namespace {
1239 struct ReplacePlaceholders {
1240 CodeGenModule &CGM;
1241
1242 /// The base address of the global.
1243 llvm::Constant *Base;
1244 llvm::Type *BaseValueTy = nullptr;
1245
1246 /// The placeholder addresses that were registered during emission.
1247 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1248
1249 /// The locations of the placeholder signals.
1250 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1251
1252 /// The current index stack. We use a simple unsigned stack because
1253 /// we assume that placeholders will be relatively sparse in the
1254 /// initializer, but we cache the index values we find just in case.
1255 llvm::SmallVector<unsigned, 8> Indices;
1256 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1257
1258 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1259 ArrayRef<std::pair<llvm::Constant*,
1260 llvm::GlobalVariable*>> addresses)
1261 : CGM(CGM), Base(base),
1262 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1263 }
1264
1265 void replaceInInitializer(llvm::Constant *init) {
1266 // Remember the type of the top-most initializer.
1267 BaseValueTy = init->getType();
1268
1269 // Initialize the stack.
1270 Indices.push_back(0);
1271 IndexValues.push_back(nullptr);
1272
1273 // Recurse into the initializer.
1274 findLocations(init);
1275
1276 // Check invariants.
1277 assert(IndexValues.size() == Indices.size() && "mismatch")(static_cast <bool> (IndexValues.size() == Indices.size
() && "mismatch") ? void (0) : __assert_fail ("IndexValues.size() == Indices.size() && \"mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1277, __extension__ __PRETTY_FUNCTION__))
;
1278 assert(Indices.size() == 1 && "didn't pop all indices")(static_cast <bool> (Indices.size() == 1 && "didn't pop all indices"
) ? void (0) : __assert_fail ("Indices.size() == 1 && \"didn't pop all indices\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1278, __extension__ __PRETTY_FUNCTION__))
;
1279
1280 // Do the replacement; this basically invalidates 'init'.
1281 assert(Locations.size() == PlaceholderAddresses.size() &&(static_cast <bool> (Locations.size() == PlaceholderAddresses
.size() && "missed a placeholder?") ? void (0) : __assert_fail
("Locations.size() == PlaceholderAddresses.size() && \"missed a placeholder?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1282, __extension__ __PRETTY_FUNCTION__))
1282 "missed a placeholder?")(static_cast <bool> (Locations.size() == PlaceholderAddresses
.size() && "missed a placeholder?") ? void (0) : __assert_fail
("Locations.size() == PlaceholderAddresses.size() && \"missed a placeholder?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1282, __extension__ __PRETTY_FUNCTION__))
;
1283
1284 // We're iterating over a hashtable, so this would be a source of
1285 // non-determinism in compiler output *except* that we're just
1286 // messing around with llvm::Constant structures, which never itself
1287 // does anything that should be visible in compiler output.
1288 for (auto &entry : Locations) {
1289 assert(entry.first->getParent() == nullptr && "not a placeholder!")(static_cast <bool> (entry.first->getParent() == nullptr
&& "not a placeholder!") ? void (0) : __assert_fail (
"entry.first->getParent() == nullptr && \"not a placeholder!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1289, __extension__ __PRETTY_FUNCTION__))
;
1290 entry.first->replaceAllUsesWith(entry.second);
1291 entry.first->eraseFromParent();
1292 }
1293 }
1294
1295 private:
1296 void findLocations(llvm::Constant *init) {
1297 // Recurse into aggregates.
1298 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1299 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1300 Indices.push_back(i);
1301 IndexValues.push_back(nullptr);
1302
1303 findLocations(agg->getOperand(i));
1304
1305 IndexValues.pop_back();
1306 Indices.pop_back();
1307 }
1308 return;
1309 }
1310
1311 // Otherwise, check for registered constants.
1312 while (true) {
1313 auto it = PlaceholderAddresses.find(init);
1314 if (it != PlaceholderAddresses.end()) {
1315 setLocation(it->second);
1316 break;
1317 }
1318
1319 // Look through bitcasts or other expressions.
1320 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1321 init = expr->getOperand(0);
1322 } else {
1323 break;
1324 }
1325 }
1326 }
1327
1328 void setLocation(llvm::GlobalVariable *placeholder) {
1329 assert(Locations.find(placeholder) == Locations.end() &&(static_cast <bool> (Locations.find(placeholder) == Locations
.end() && "already found location for placeholder!") ?
void (0) : __assert_fail ("Locations.find(placeholder) == Locations.end() && \"already found location for placeholder!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1330, __extension__ __PRETTY_FUNCTION__))
1330 "already found location for placeholder!")(static_cast <bool> (Locations.find(placeholder) == Locations
.end() && "already found location for placeholder!") ?
void (0) : __assert_fail ("Locations.find(placeholder) == Locations.end() && \"already found location for placeholder!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1330, __extension__ __PRETTY_FUNCTION__))
;
1331
1332 // Lazily fill in IndexValues with the values from Indices.
1333 // We do this in reverse because we should always have a strict
1334 // prefix of indices from the start.
1335 assert(Indices.size() == IndexValues.size())(static_cast <bool> (Indices.size() == IndexValues.size
()) ? void (0) : __assert_fail ("Indices.size() == IndexValues.size()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1335, __extension__ __PRETTY_FUNCTION__))
;
1336 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1337 if (IndexValues[i]) {
1338#ifndef NDEBUG
1339 for (size_t j = 0; j != i + 1; ++j) {
1340 assert(IndexValues[j] &&(static_cast <bool> (IndexValues[j] && isa<llvm
::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt
>(IndexValues[j])->getZExtValue() == Indices[j]) ? void
(0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
1341 isa<llvm::ConstantInt>(IndexValues[j]) &&(static_cast <bool> (IndexValues[j] && isa<llvm
::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt
>(IndexValues[j])->getZExtValue() == Indices[j]) ? void
(0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
1342 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()(static_cast <bool> (IndexValues[j] && isa<llvm
::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt
>(IndexValues[j])->getZExtValue() == Indices[j]) ? void
(0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
1343 == Indices[j])(static_cast <bool> (IndexValues[j] && isa<llvm
::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt
>(IndexValues[j])->getZExtValue() == Indices[j]) ? void
(0) : __assert_fail ("IndexValues[j] && isa<llvm::ConstantInt>(IndexValues[j]) && cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() == Indices[j]"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
;
1344 }
1345#endif
1346 break;
1347 }
1348
1349 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1350 }
1351
1352 // Form a GEP and then bitcast to the placeholder type so that the
1353 // replacement will succeed.
1354 llvm::Constant *location =
1355 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1356 Base, IndexValues);
1357 location = llvm::ConstantExpr::getBitCast(location,
1358 placeholder->getType());
1359
1360 Locations.insert({placeholder, location});
1361 }
1362 };
1363}
1364
1365void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1366 assert(InitializedNonAbstract &&(static_cast <bool> (InitializedNonAbstract && "finalizing emitter that was used for abstract emission?"
) ? void (0) : __assert_fail ("InitializedNonAbstract && \"finalizing emitter that was used for abstract emission?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1367, __extension__ __PRETTY_FUNCTION__))
1367 "finalizing emitter that was used for abstract emission?")(static_cast <bool> (InitializedNonAbstract && "finalizing emitter that was used for abstract emission?"
) ? void (0) : __assert_fail ("InitializedNonAbstract && \"finalizing emitter that was used for abstract emission?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1367, __extension__ __PRETTY_FUNCTION__))
;
1368 assert(!Finalized && "finalizing emitter multiple times")(static_cast <bool> (!Finalized && "finalizing emitter multiple times"
) ? void (0) : __assert_fail ("!Finalized && \"finalizing emitter multiple times\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1368, __extension__ __PRETTY_FUNCTION__))
;
1369 assert(global->getInitializer())(static_cast <bool> (global->getInitializer()) ? void
(0) : __assert_fail ("global->getInitializer()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1369, __extension__ __PRETTY_FUNCTION__))
;
1370
1371 // Note that we might also be Failed.
1372 Finalized = true;
1373
1374 if (!PlaceholderAddresses.empty()) {
1375 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1376 .replaceInInitializer(global->getInitializer());
1377 PlaceholderAddresses.clear(); // satisfy
1378 }
1379}
1380
1381ConstantEmitter::~ConstantEmitter() {
1382 assert((!InitializedNonAbstract || Finalized || Failed) &&(static_cast <bool> ((!InitializedNonAbstract || Finalized
|| Failed) && "not finalized after being initialized for non-abstract emission"
) ? void (0) : __assert_fail ("(!InitializedNonAbstract || Finalized || Failed) && \"not finalized after being initialized for non-abstract emission\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1383, __extension__ __PRETTY_FUNCTION__))
1383 "not finalized after being initialized for non-abstract emission")(static_cast <bool> ((!InitializedNonAbstract || Finalized
|| Failed) && "not finalized after being initialized for non-abstract emission"
) ? void (0) : __assert_fail ("(!InitializedNonAbstract || Finalized || Failed) && \"not finalized after being initialized for non-abstract emission\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1383, __extension__ __PRETTY_FUNCTION__))
;
1384 assert(PlaceholderAddresses.empty() && "unhandled placeholders")(static_cast <bool> (PlaceholderAddresses.empty() &&
"unhandled placeholders") ? void (0) : __assert_fail ("PlaceholderAddresses.empty() && \"unhandled placeholders\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1384, __extension__ __PRETTY_FUNCTION__))
;
1385}
1386
1387static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1388 if (auto AT = type->getAs<AtomicType>()) {
1389 return CGM.getContext().getQualifiedType(AT->getValueType(),
1390 type.getQualifiers());
1391 }
1392 return type;
1393}
1394
1395llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1396 // Make a quick check if variable can be default NULL initialized
1397 // and avoid going through rest of code which may do, for c++11,
1398 // initialization of memory to all NULLs.
1399 if (!D.hasLocalStorage()) {
1400 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1401 if (Ty->isRecordType())
1402 if (const CXXConstructExpr *E =
1403 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1404 const CXXConstructorDecl *CD = E->getConstructor();
1405 if (CD->isTrivial() && CD->isDefaultConstructor())
1406 return CGM.EmitNullConstant(D.getType());
1407 }
1408 }
1409
1410 QualType destType = D.getType();
1411
1412 // Try to emit the initializer. Note that this can allow some things that
1413 // are not allowed by tryEmitPrivateForMemory alone.
1414 if (auto value = D.evaluateValue()) {
1415 return tryEmitPrivateForMemory(*value, destType);
1416 }
1417
1418 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1419 // reference is a constant expression, and the reference binds to a temporary,
1420 // then constant initialization is performed. ConstExprEmitter will
1421 // incorrectly emit a prvalue constant in this case, and the calling code
1422 // interprets that as the (pointer) value of the reference, rather than the
1423 // desired value of the referee.
1424 if (destType->isReferenceType())
1425 return nullptr;
1426
1427 const Expr *E = D.getInit();
1428 assert(E && "No initializer to emit")(static_cast <bool> (E && "No initializer to emit"
) ? void (0) : __assert_fail ("E && \"No initializer to emit\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1428, __extension__ __PRETTY_FUNCTION__))
;
1429
1430 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1431 auto C =
1432 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1433 return (C ? emitForMemory(C, destType) : nullptr);
1434}
1435
1436llvm::Constant *
1437ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1438 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1439 auto C = tryEmitAbstract(E, nonMemoryDestType);
1440 return (C ? emitForMemory(C, destType) : nullptr);
1441}
1442
1443llvm::Constant *
1444ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1445 QualType destType) {
1446 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1447 auto C = tryEmitAbstract(value, nonMemoryDestType);
1448 return (C ? emitForMemory(C, destType) : nullptr);
1449}
1450
1451llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1452 QualType destType) {
1453 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1454 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1455 return (C ? emitForMemory(C, destType) : nullptr);
1456}
1457
1458llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1459 QualType destType) {
1460 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1461 auto C = tryEmitPrivate(value, nonMemoryDestType);
1462 return (C ? emitForMemory(C, destType) : nullptr);
1463}
1464
1465llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1466 llvm::Constant *C,
1467 QualType destType) {
1468 // For an _Atomic-qualified constant, we may need to add tail padding.
1469 if (auto AT = destType->getAs<AtomicType>()) {
1470 QualType destValueType = AT->getValueType();
1471 C = emitForMemory(CGM, C, destValueType);
1472
1473 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1474 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1475 if (innerSize == outerSize)
1476 return C;
1477
1478 assert(innerSize < outerSize && "emitted over-large constant for atomic")(static_cast <bool> (innerSize < outerSize &&
"emitted over-large constant for atomic") ? void (0) : __assert_fail
("innerSize < outerSize && \"emitted over-large constant for atomic\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1478, __extension__ __PRETTY_FUNCTION__))
;
1479 llvm::Constant *elts[] = {
1480 C,
1481 llvm::ConstantAggregateZero::get(
1482 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1483 };
1484 return llvm::ConstantStruct::getAnon(elts);
1485 }
1486
1487 // Zero-extend bool.
1488 if (C->getType()->isIntegerTy(1)) {
1489 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1490 return llvm::ConstantExpr::getZExt(C, boolTy);
1491 }
1492
1493 return C;
1494}
1495
1496llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1497 QualType destType) {
1498 Expr::EvalResult Result;
1499
1500 bool Success = false;
1501
1502 if (destType->isReferenceType())
1503 Success = E->EvaluateAsLValue(Result, CGM.getContext());
1504 else
1505 Success = E->EvaluateAsRValue(Result, CGM.getContext());
1506
1507 llvm::Constant *C;
1508 if (Success && !Result.HasSideEffects)
1509 C = tryEmitPrivate(Result.Val, destType);
1510 else
1511 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1512
1513 return C;
1514}
1515
1516llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1517 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1518}
1519
1520namespace {
1521/// A struct which can be used to peephole certain kinds of finalization
1522/// that normally happen during l-value emission.
1523struct ConstantLValue {
1524 llvm::Constant *Value;
1525 bool HasOffsetApplied;
1526
1527 /*implicit*/ ConstantLValue(llvm::Constant *value,
1528 bool hasOffsetApplied = false)
1529 : Value(value), HasOffsetApplied(false) {}
1530
1531 /*implicit*/ ConstantLValue(ConstantAddress address)
1532 : ConstantLValue(address.getPointer()) {}
1533};
1534
1535/// A helper class for emitting constant l-values.
1536class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1537 ConstantLValue> {
1538 CodeGenModule &CGM;
1539 ConstantEmitter &Emitter;
1540 const APValue &Value;
1541 QualType DestType;
1542
1543 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1544 friend StmtVisitorBase;
1545
1546public:
1547 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1548 QualType destType)
1549 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1550
1551 llvm::Constant *tryEmit();
1552
1553private:
1554 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1555 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1556
1557 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1558 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1559 ConstantLValue VisitStringLiteral(const StringLiteral *E);
1560 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1561 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1562 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1563 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1564 ConstantLValue VisitCallExpr(const CallExpr *E);
1565 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1566 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1567 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1568 ConstantLValue VisitMaterializeTemporaryExpr(
1569 const MaterializeTemporaryExpr *E);
1570
1571 bool hasNonZeroOffset() const {
1572 return !Value.getLValueOffset().isZero();
1573 }
1574
1575 /// Return the value offset.
1576 llvm::Constant *getOffset() {
1577 return llvm::ConstantInt::get(CGM.Int64Ty,
1578 Value.getLValueOffset().getQuantity());
1579 }
1580
1581 /// Apply the value offset to the given constant.
1582 llvm::Constant *applyOffset(llvm::Constant *C) {
1583 if (!hasNonZeroOffset())
1584 return C;
1585
1586 llvm::Type *origPtrTy = C->getType();
1587 unsigned AS = origPtrTy->getPointerAddressSpace();
1588 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1589 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1590 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1591 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1592 return C;
1593 }
1594};
1595
1596}
1597
1598llvm::Constant *ConstantLValueEmitter::tryEmit() {
1599 const APValue::LValueBase &base = Value.getLValueBase();
1600
1601 // Certain special array initializers are represented in APValue
1602 // as l-values referring to the base expression which generates the
1603 // array. This happens with e.g. string literals. These should
1604 // probably just get their own representation kind in APValue.
1605 if (DestType->isArrayType()) {
1606 assert(!hasNonZeroOffset() && "offset on array initializer")(static_cast <bool> (!hasNonZeroOffset() && "offset on array initializer"
) ? void (0) : __assert_fail ("!hasNonZeroOffset() && \"offset on array initializer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1606, __extension__ __PRETTY_FUNCTION__))
;
1607 auto expr = const_cast<Expr*>(base.get<const Expr*>());
1608 return ConstExprEmitter(Emitter).Visit(expr, DestType);
1609 }
1610
1611 // Otherwise, the destination type should be a pointer or reference
1612 // type, but it might also be a cast thereof.
1613 //
1614 // FIXME: the chain of casts required should be reflected in the APValue.
1615 // We need this in order to correctly handle things like a ptrtoint of a
1616 // non-zero null pointer and addrspace casts that aren't trivially
1617 // represented in LLVM IR.
1618 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1619 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy))(static_cast <bool> (isa<llvm::IntegerType>(destTy
) || isa<llvm::PointerType>(destTy)) ? void (0) : __assert_fail
("isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1619, __extension__ __PRETTY_FUNCTION__))
;
1620
1621 // If there's no base at all, this is a null or absolute pointer,
1622 // possibly cast back to an integer type.
1623 if (!base) {
1624 return tryEmitAbsolute(destTy);
1625 }
1626
1627 // Otherwise, try to emit the base.
1628 ConstantLValue result = tryEmitBase(base);
1629
1630 // If that failed, we're done.
1631 llvm::Constant *value = result.Value;
1632 if (!value) return nullptr;
1633
1634 // Apply the offset if necessary and not already done.
1635 if (!result.HasOffsetApplied) {
1636 value = applyOffset(value);
1637 }
1638
1639 // Convert to the appropriate type; this could be an lvalue for
1640 // an integer. FIXME: performAddrSpaceCast
1641 if (isa<llvm::PointerType>(destTy))
1642 return llvm::ConstantExpr::getPointerCast(value, destTy);
1643
1644 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1645}
1646
1647/// Try to emit an absolute l-value, such as a null pointer or an integer
1648/// bitcast to pointer type.
1649llvm::Constant *
1650ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1651 auto offset = getOffset();
1652
1653 // If we're producing a pointer, this is easy.
1654 if (auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1655 if (Value.isNullPointer()) {
1656 // FIXME: integer offsets from non-zero null pointers.
1657 return CGM.getNullPointer(destPtrTy, DestType);
1658 }
1659
1660 // Convert the integer to a pointer-sized integer before converting it
1661 // to a pointer.
1662 // FIXME: signedness depends on the original integer type.
1663 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1664 llvm::Constant *C = offset;
Value stored to 'C' during its initialization is never read
1665 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1666 /*isSigned*/ false);
1667 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1668 return C;
1669 }
1670
1671 // Otherwise, we're basically returning an integer constant.
1672
1673 // FIXME: this does the wrong thing with ptrtoint of a null pointer,
1674 // but since we don't know the original pointer type, there's not much
1675 // we can do about it.
1676
1677 auto C = getOffset();
1678 C = llvm::ConstantExpr::getIntegerCast(C, destTy, /*isSigned*/ false);
1679 return C;
1680}
1681
1682ConstantLValue
1683ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1684 // Handle values.
1685 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1686 if (D->hasAttr<WeakRefAttr>())
1687 return CGM.GetWeakRefReference(D).getPointer();
1688
1689 if (auto FD = dyn_cast<FunctionDecl>(D))
1690 return CGM.GetAddrOfFunction(FD);
1691
1692 if (auto VD = dyn_cast<VarDecl>(D)) {
1693 // We can never refer to a variable with local storage.
1694 if (!VD->hasLocalStorage()) {
1695 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1696 return CGM.GetAddrOfGlobalVar(VD);
1697
1698 if (VD->isLocalVarDecl()) {
1699 return CGM.getOrCreateStaticVarDecl(
1700 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1701 }
1702 }
1703 }
1704
1705 return nullptr;
1706 }
1707
1708 // Otherwise, it must be an expression.
1709 return Visit(base.get<const Expr*>());
1710}
1711
1712ConstantLValue
1713ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1714 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1715}
1716
1717ConstantLValue
1718ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1719 return CGM.GetAddrOfConstantStringFromLiteral(E);
1720}
1721
1722ConstantLValue
1723ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1724 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1725}
1726
1727ConstantLValue
1728ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1729 auto C = CGM.getObjCRuntime().GenerateConstantString(E->getString());
1730 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(E->getType()));
1731}
1732
1733ConstantLValue
1734ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1735 if (auto CGF = Emitter.CGF) {
1736 LValue Res = CGF->EmitPredefinedLValue(E);
1737 return cast<ConstantAddress>(Res.getAddress());
1738 }
1739
1740 auto kind = E->getIdentType();
1741 if (kind == PredefinedExpr::PrettyFunction) {
1742 return CGM.GetAddrOfConstantCString("top level", ".tmp");
1743 }
1744
1745 return CGM.GetAddrOfConstantCString("", ".tmp");
1746}
1747
1748ConstantLValue
1749ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1750 assert(Emitter.CGF && "Invalid address of label expression outside function")(static_cast <bool> (Emitter.CGF && "Invalid address of label expression outside function"
) ? void (0) : __assert_fail ("Emitter.CGF && \"Invalid address of label expression outside function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1750, __extension__ __PRETTY_FUNCTION__))
;
1751 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1752 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1753 CGM.getTypes().ConvertType(E->getType()));
1754 return Ptr;
1755}
1756
1757ConstantLValue
1758ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1759 unsigned builtin = E->getBuiltinCallee();
1760 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1761 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1762 return nullptr;
1763
1764 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1765 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1766 return CGM.getObjCRuntime().GenerateConstantString(literal);
1767 } else {
1768 // FIXME: need to deal with UCN conversion issues.
1769 return CGM.GetAddrOfConstantCFString(literal);
1770 }
1771}
1772
1773ConstantLValue
1774ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1775 StringRef functionName;
1776 if (auto CGF = Emitter.CGF)
1777 functionName = CGF->CurFn->getName();
1778 else
1779 functionName = "global";
1780
1781 return CGM.GetAddrOfGlobalBlock(E, functionName);
1782}
1783
1784ConstantLValue
1785ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1786 QualType T;
1787 if (E->isTypeOperand())
1788 T = E->getTypeOperand(CGM.getContext());
1789 else
1790 T = E->getExprOperand()->getType();
1791 return CGM.GetAddrOfRTTIDescriptor(T);
1792}
1793
1794ConstantLValue
1795ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1796 return CGM.GetAddrOfUuidDescriptor(E);
1797}
1798
1799ConstantLValue
1800ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1801 const MaterializeTemporaryExpr *E) {
1802 assert(E->getStorageDuration() == SD_Static)(static_cast <bool> (E->getStorageDuration() == SD_Static
) ? void (0) : __assert_fail ("E->getStorageDuration() == SD_Static"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1802, __extension__ __PRETTY_FUNCTION__))
;
1803 SmallVector<const Expr *, 2> CommaLHSs;
1804 SmallVector<SubobjectAdjustment, 2> Adjustments;
1805 const Expr *Inner = E->GetTemporaryExpr()
1806 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1807 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1808}
1809
1810llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1811 QualType DestType) {
1812 switch (Value.getKind()) {
1813 case APValue::Uninitialized:
1814 llvm_unreachable("Constant expressions should be initialized.")::llvm::llvm_unreachable_internal("Constant expressions should be initialized."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1814)
;
1815 case APValue::LValue:
1816 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
1817 case APValue::Int:
1818 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
1819 case APValue::ComplexInt: {
1820 llvm::Constant *Complex[2];
1821
1822 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1823 Value.getComplexIntReal());
1824 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1825 Value.getComplexIntImag());
1826
1827 // FIXME: the target may want to specify that this is packed.
1828 llvm::StructType *STy =
1829 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1830 return llvm::ConstantStruct::get(STy, Complex);
1831 }
1832 case APValue::Float: {
1833 const llvm::APFloat &Init = Value.getFloat();
1834 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1835 !CGM.getContext().getLangOpts().NativeHalfType &&
1836 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1837 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1838 Init.bitcastToAPInt());
1839 else
1840 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
1841 }
1842 case APValue::ComplexFloat: {
1843 llvm::Constant *Complex[2];
1844
1845 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1846 Value.getComplexFloatReal());
1847 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1848 Value.getComplexFloatImag());
1849
1850 // FIXME: the target may want to specify that this is packed.
1851 llvm::StructType *STy =
1852 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1853 return llvm::ConstantStruct::get(STy, Complex);
1854 }
1855 case APValue::Vector: {
1856 unsigned NumElts = Value.getVectorLength();
1857 SmallVector<llvm::Constant *, 4> Inits(NumElts);
1858
1859 for (unsigned I = 0; I != NumElts; ++I) {
1860 const APValue &Elt = Value.getVectorElt(I);
1861 if (Elt.isInt())
1862 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
1863 else if (Elt.isFloat())
1864 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
1865 else
1866 llvm_unreachable("unsupported vector element type")::llvm::llvm_unreachable_internal("unsupported vector element type"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1866)
;
1867 }
1868 return llvm::ConstantVector::get(Inits);
1869 }
1870 case APValue::AddrLabelDiff: {
1871 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1872 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1873 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1874 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1875 if (!LHS || !RHS) return nullptr;
1876
1877 // Compute difference
1878 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1879 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1880 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
1881 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1882
1883 // LLVM is a bit sensitive about the exact format of the
1884 // address-of-label difference; make sure to truncate after
1885 // the subtraction.
1886 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1887 }
1888 case APValue::Struct:
1889 case APValue::Union:
1890 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
1891 case APValue::Array: {
1892 const ArrayType *CAT = CGM.getContext().getAsArrayType(DestType);
1893 unsigned NumElements = Value.getArraySize();
1894 unsigned NumInitElts = Value.getArrayInitializedElts();
1895
1896 // Emit array filler, if there is one.
1897 llvm::Constant *Filler = nullptr;
1898 if (Value.hasArrayFiller())
1899 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1900 CAT->getElementType());
1901
1902 // Emit initializer elements.
1903 llvm::Type *CommonElementType =
1904 CGM.getTypes().ConvertType(CAT->getElementType());
1905
1906 // Try to use a ConstantAggregateZero if we can.
1907 if (Filler && Filler->isNullValue() && !NumInitElts) {
1908 llvm::ArrayType *AType =
1909 llvm::ArrayType::get(CommonElementType, NumElements);
1910 return llvm::ConstantAggregateZero::get(AType);
1911 }
1912
1913 SmallVector<llvm::Constant*, 16> Elts;
1914 Elts.reserve(NumElements);
1915 for (unsigned I = 0; I < NumElements; ++I) {
1916 llvm::Constant *C = Filler;
1917 if (I < NumInitElts) {
1918 C = tryEmitPrivateForMemory(Value.getArrayInitializedElt(I),
1919 CAT->getElementType());
1920 } else if (!Filler) {
1921 assert(Value.hasArrayFiller() &&(static_cast <bool> (Value.hasArrayFiller() && "Missing filler for implicit elements of initializer"
) ? void (0) : __assert_fail ("Value.hasArrayFiller() && \"Missing filler for implicit elements of initializer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1922, __extension__ __PRETTY_FUNCTION__))
1922 "Missing filler for implicit elements of initializer")(static_cast <bool> (Value.hasArrayFiller() && "Missing filler for implicit elements of initializer"
) ? void (0) : __assert_fail ("Value.hasArrayFiller() && \"Missing filler for implicit elements of initializer\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1922, __extension__ __PRETTY_FUNCTION__))
;
1923 C = tryEmitPrivateForMemory(Value.getArrayFiller(),
1924 CAT->getElementType());
1925 }
1926 if (!C) return nullptr;
1927
1928 if (I == 0)
1929 CommonElementType = C->getType();
1930 else if (C->getType() != CommonElementType)
1931 CommonElementType = nullptr;
1932 Elts.push_back(C);
1933 }
1934
1935 if (!CommonElementType) {
1936 // FIXME: Try to avoid packing the array
1937 std::vector<llvm::Type*> Types;
1938 Types.reserve(NumElements);
1939 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
1940 Types.push_back(Elts[i]->getType());
1941 llvm::StructType *SType =
1942 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
1943 return llvm::ConstantStruct::get(SType, Elts);
1944 }
1945
1946 llvm::ArrayType *AType =
1947 llvm::ArrayType::get(CommonElementType, NumElements);
1948 return llvm::ConstantArray::get(AType, Elts);
1949 }
1950 case APValue::MemberPointer:
1951 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
1952 }
1953 llvm_unreachable("Unknown APValue kind")::llvm::llvm_unreachable_internal("Unknown APValue kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1953)
;
1954}
1955
1956llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
1957 const CompoundLiteralExpr *E) {
1958 return EmittedCompoundLiterals.lookup(E);
1959}
1960
1961void CodeGenModule::setAddrOfConstantCompoundLiteral(
1962 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
1963 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
1964 (void)Ok;
1965 assert(Ok && "CLE has already been emitted!")(static_cast <bool> (Ok && "CLE has already been emitted!"
) ? void (0) : __assert_fail ("Ok && \"CLE has already been emitted!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1965, __extension__ __PRETTY_FUNCTION__))
;
1966}
1967
1968ConstantAddress
1969CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
1970 assert(E->isFileScope() && "not a file-scope compound literal expr")(static_cast <bool> (E->isFileScope() && "not a file-scope compound literal expr"
) ? void (0) : __assert_fail ("E->isFileScope() && \"not a file-scope compound literal expr\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 1970, __extension__ __PRETTY_FUNCTION__))
;
1971 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
1972}
1973
1974llvm::Constant *
1975CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1976 // Member pointer constants always have a very particular form.
1977 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1978 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1979
1980 // A member function pointer.
1981 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1982 return getCXXABI().EmitMemberFunctionPointer(method);
1983
1984 // Otherwise, a member data pointer.
1985 uint64_t fieldOffset = getContext().getFieldOffset(decl);
1986 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1987 return getCXXABI().EmitMemberDataPointer(type, chars);
1988}
1989
1990static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1991 llvm::Type *baseType,
1992 const CXXRecordDecl *base);
1993
1994static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
1995 const RecordDecl *record,
1996 bool asCompleteObject) {
1997 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1998 llvm::StructType *structure =
1999 (asCompleteObject ? layout.getLLVMType()
2000 : layout.getBaseSubobjectLLVMType());
2001
2002 unsigned numElements = structure->getNumElements();
2003 std::vector<llvm::Constant *> elements(numElements);
2004
2005 auto CXXR = dyn_cast<CXXRecordDecl>(record);
2006 // Fill in all the bases.
2007 if (CXXR) {
2008 for (const auto &I : CXXR->bases()) {
2009 if (I.isVirtual()) {
2010 // Ignore virtual bases; if we're laying out for a complete
2011 // object, we'll lay these out later.
2012 continue;
2013 }
2014
2015 const CXXRecordDecl *base =
2016 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2017
2018 // Ignore empty bases.
2019 if (base->isEmpty() ||
2020 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2021 .isZero())
2022 continue;
2023
2024 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2025 llvm::Type *baseType = structure->getElementType(fieldIndex);
2026 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2027 }
2028 }
2029
2030 // Fill in all the fields.
2031 for (const auto *Field : record->fields()) {
2032 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2033 // will fill in later.)
2034 if (!Field->isBitField()) {
2035 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2036 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2037 }
2038
2039 // For unions, stop after the first named field.
2040 if (record->isUnion()) {
2041 if (Field->getIdentifier())
2042 break;
2043 if (const auto *FieldRD =
2044 dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl()))
2045 if (FieldRD->findFirstNamedDataMember())
2046 break;
2047 }
2048 }
2049
2050 // Fill in the virtual bases, if we're working with the complete object.
2051 if (CXXR && asCompleteObject) {
2052 for (const auto &I : CXXR->vbases()) {
2053 const CXXRecordDecl *base =
2054 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2055
2056 // Ignore empty bases.
2057 if (base->isEmpty())
2058 continue;
2059
2060 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2061
2062 // We might have already laid this field out.
2063 if (elements[fieldIndex]) continue;
2064
2065 llvm::Type *baseType = structure->getElementType(fieldIndex);
2066 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2067 }
2068 }
2069
2070 // Now go through all other fields and zero them out.
2071 for (unsigned i = 0; i != numElements; ++i) {
2072 if (!elements[i])
2073 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2074 }
2075
2076 return llvm::ConstantStruct::get(structure, elements);
2077}
2078
2079/// Emit the null constant for a base subobject.
2080static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2081 llvm::Type *baseType,
2082 const CXXRecordDecl *base) {
2083 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2084
2085 // Just zero out bases that don't have any pointer to data members.
2086 if (baseLayout.isZeroInitializableAsBase())
2087 return llvm::Constant::getNullValue(baseType);
2088
2089 // Otherwise, we can just use its null constant.
2090 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2091}
2092
2093llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2094 QualType T) {
2095 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2096}
2097
2098llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2099 if (T->getAs<PointerType>())
2100 return getNullPointer(
2101 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2102
2103 if (getTypes().isZeroInitializable(T))
2104 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2105
2106 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2107 llvm::ArrayType *ATy =
2108 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2109
2110 QualType ElementTy = CAT->getElementType();
2111
2112 llvm::Constant *Element =
2113 ConstantEmitter::emitNullForMemory(*this, ElementTy);
2114 unsigned NumElements = CAT->getSize().getZExtValue();
2115 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2116 return llvm::ConstantArray::get(ATy, Array);
2117 }
2118
2119 if (const RecordType *RT = T->getAs<RecordType>())
2120 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2121
2122 assert(T->isMemberDataPointerType() &&(static_cast <bool> (T->isMemberDataPointerType() &&
"Should only see pointers to data members here!") ? void (0)
: __assert_fail ("T->isMemberDataPointerType() && \"Should only see pointers to data members here!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2123, __extension__ __PRETTY_FUNCTION__))
2123 "Should only see pointers to data members here!")(static_cast <bool> (T->isMemberDataPointerType() &&
"Should only see pointers to data members here!") ? void (0)
: __assert_fail ("T->isMemberDataPointerType() && \"Should only see pointers to data members here!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/CodeGen/CGExprConstant.cpp"
, 2123, __extension__ __PRETTY_FUNCTION__))
;
2124
2125 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2126}
2127
2128llvm::Constant *
2129CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2130 return ::EmitNullConstant(*this, Record, false);
2131}