blob: 64ad582c58111d4ae57e2d057e60b0bfbad2681e [file] [log] [blame]
Anders Carlsson610ee712008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson610ee712008-01-26 01:36:00 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Constant Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000015#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000016#include "CGRecordLayout.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000019#include "TargetInfo.h"
Chris Lattnere50e9012008-10-06 05:59:01 +000020#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000029using namespace clang;
30using namespace CodeGen;
31
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000032//===----------------------------------------------------------------------===//
33// ConstStructBuilder
34//===----------------------------------------------------------------------===//
35
36namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000037class ConstExprEmitter;
Benjamin Kramer337e3a52009-11-28 19:45:26 +000038class ConstStructBuilder {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000039 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +000040 ConstantEmitter &Emitter;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000041
Mike Stump11289f42009-09-09 15:08:12 +000042 bool Packed;
Ken Dyckdb205d12011-03-17 01:33:18 +000043 CharUnits NextFieldOffsetInChars;
Ken Dycka1b35102011-03-18 01:26:17 +000044 CharUnits LLVMStructAlignment;
Bill Wendling7ac74722012-02-07 00:54:58 +000045 SmallVector<llvm::Constant *, 32> Elements;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000046public:
John McCallde0fe072017-08-15 21:42:52 +000047 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
48 ConstExprEmitter *ExprEmitter,
Erik Pilkingtone3b71442018-11-02 17:36:58 +000049 llvm::Constant *Base,
John McCallde0fe072017-08-15 21:42:52 +000050 InitListExpr *Updater,
51 QualType ValTy);
52 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
53 InitListExpr *ILE, QualType StructTy);
54 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +000055 const APValue &Value, QualType ValTy);
56
57private:
John McCallde0fe072017-08-15 21:42:52 +000058 ConstStructBuilder(ConstantEmitter &emitter)
Fangrui Song6907ce22018-07-30 19:24:48 +000059 : CGM(emitter.CGM), Emitter(emitter), Packed(false),
Ken Dyckdb205d12011-03-17 01:33:18 +000060 NextFieldOffsetInChars(CharUnits::Zero()),
Ken Dycka1b35102011-03-18 01:26:17 +000061 LLVMStructAlignment(CharUnits::One()) { }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000062
Richard Smithdafff942012-01-14 04:30:29 +000063 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
Chris Lattnerff0e2a32010-04-13 18:16:19 +000064 llvm::Constant *InitExpr);
Mike Stump11289f42009-09-09 15:08:12 +000065
Richard Smithc8998922012-02-23 08:33:23 +000066 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
67
Chris Lattner9a3459f2010-07-05 17:04:23 +000068 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
69 llvm::ConstantInt *InitExpr);
Mike Stump11289f42009-09-09 15:08:12 +000070
Ken Dyck30a87e32011-03-11 23:42:54 +000071 void AppendPadding(CharUnits PadSize);
Mike Stump11289f42009-09-09 15:08:12 +000072
Ken Dyck327b77a2011-03-11 02:17:05 +000073 void AppendTailPadding(CharUnits RecordSize);
Anders Carlssonba4c6d12009-07-27 01:23:51 +000074
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000075 void ConvertStructToPacked();
Richard Smithdafff942012-01-14 04:30:29 +000076
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000077 bool Build(InitListExpr *ILE);
Erik Pilkingtone3b71442018-11-02 17:36:58 +000078 bool Build(ConstExprEmitter *Emitter, llvm::Constant *Base,
Yunzhong Gaocb779302015-06-10 00:27:52 +000079 InitListExpr *Updater);
John McCallde0fe072017-08-15 21:42:52 +000080 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000081 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
Richard Smithdafff942012-01-14 04:30:29 +000082 llvm::Constant *Finalize(QualType Ty);
Mike Stump11289f42009-09-09 15:08:12 +000083
Ken Dycka1b35102011-03-18 01:26:17 +000084 CharUnits getAlignment(const llvm::Constant *C) const {
85 if (Packed) return CharUnits::One();
86 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000087 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000088 }
Mike Stump11289f42009-09-09 15:08:12 +000089
Ken Dyck33fa9ee2011-03-18 01:12:13 +000090 CharUnits getSizeInChars(const llvm::Constant *C) const {
91 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000092 CGM.getDataLayout().getTypeAllocSize(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000093 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000094};
Mike Stump11289f42009-09-09 15:08:12 +000095
Richard Smithdafff942012-01-14 04:30:29 +000096void ConstStructBuilder::
Chris Lattnerff0e2a32010-04-13 18:16:19 +000097AppendField(const FieldDecl *Field, uint64_t FieldOffset,
98 llvm::Constant *InitCst) {
Ken Dyck1c80fd12011-03-15 01:09:02 +000099 const ASTContext &Context = CGM.getContext();
100
101 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000102
Richard Smithc8998922012-02-23 08:33:23 +0000103 AppendBytes(FieldOffsetInChars, InitCst);
104}
105
106void ConstStructBuilder::
107AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
108
Ken Dyckdb205d12011-03-17 01:33:18 +0000109 assert(NextFieldOffsetInChars <= FieldOffsetInChars
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000110 && "Field offset mismatch!");
111
Ken Dycka1b35102011-03-18 01:26:17 +0000112 CharUnits FieldAlignment = getAlignment(InitCst);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000113
114 // Round up the field offset to the alignment of the field type.
Ken Dyckdb205d12011-03-17 01:33:18 +0000115 CharUnits AlignedNextFieldOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000116 NextFieldOffsetInChars.alignTo(FieldAlignment);
Chandler Carruthbf972bb2014-10-19 19:41:46 +0000117
Ken Dyckdb205d12011-03-17 01:33:18 +0000118 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000119 // We need to append padding.
Richard Smithdafff942012-01-14 04:30:29 +0000120 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000121
Ken Dyckdb205d12011-03-17 01:33:18 +0000122 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000123 "Did not add enough padding!");
124
David Majnemer8e133962014-10-19 23:40:06 +0000125 AlignedNextFieldOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000126 NextFieldOffsetInChars.alignTo(FieldAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000127 }
128
129 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
130 assert(!Packed && "Alignment is wrong even with a packed struct!");
131
132 // Convert the struct to a packed struct.
133 ConvertStructToPacked();
134
135 // After we pack the struct, we may need to insert padding.
136 if (NextFieldOffsetInChars < FieldOffsetInChars) {
137 // We need to append padding.
138 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
139
140 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
141 "Did not add enough padding!");
142 }
Ken Dyckdb205d12011-03-17 01:33:18 +0000143 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000144 }
145
146 // Add the field.
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000147 Elements.push_back(InitCst);
Ken Dyckdb205d12011-03-17 01:33:18 +0000148 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000149 getSizeInChars(InitCst);
Richard Smithdafff942012-01-14 04:30:29 +0000150
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000151 if (Packed)
Richard Smithdafff942012-01-14 04:30:29 +0000152 assert(LLVMStructAlignment == CharUnits::One() &&
Ken Dycka1b35102011-03-18 01:26:17 +0000153 "Packed struct not byte-aligned!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000154 else
155 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000156}
157
Chris Lattner9a3459f2010-07-05 17:04:23 +0000158void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
159 uint64_t FieldOffset,
160 llvm::ConstantInt *CI) {
Ken Dycka862d952011-03-12 12:03:11 +0000161 const ASTContext &Context = CGM.getContext();
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000162 const uint64_t CharWidth = Context.getCharWidth();
Ken Dyckdb205d12011-03-17 01:33:18 +0000163 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
164 if (FieldOffset > NextFieldOffsetInBits) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000165 // We need to add padding.
Ken Dycka862d952011-03-12 12:03:11 +0000166 CharUnits PadSize = Context.toCharUnitsFromBits(
Rui Ueyama83aa9792016-01-14 21:00:27 +0000167 llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
168 Context.getTargetInfo().getCharAlign()));
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000169
Ken Dycka862d952011-03-12 12:03:11 +0000170 AppendPadding(PadSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000171 }
172
Richard Smithcaf33902011-10-10 18:28:20 +0000173 uint64_t FieldSize = Field->getBitWidthValue(Context);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000174
175 llvm::APInt FieldValue = CI->getValue();
176
177 // Promote the size of FieldValue if necessary
178 // FIXME: This should never occur, but currently it can because initializer
179 // constants are cast to bool, and because clang is not enforcing bitfield
180 // width limits.
181 if (FieldSize > FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000182 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000183
184 // Truncate the size of FieldValue to the bit field size.
185 if (FieldSize < FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000186 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000187
Ken Dyckdb205d12011-03-17 01:33:18 +0000188 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
189 if (FieldOffset < NextFieldOffsetInBits) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000190 // Either part of the field or the entire field can go into the previous
191 // byte.
192 assert(!Elements.empty() && "Elements can't be empty!");
193
Ken Dyckdb205d12011-03-17 01:33:18 +0000194 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000195
196 bool FitsCompletelyInPreviousByte =
197 BitsInPreviousByte >= FieldValue.getBitWidth();
198
199 llvm::APInt Tmp = FieldValue;
200
201 if (!FitsCompletelyInPreviousByte) {
202 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
203
Micah Villmowdd31ca12012-10-08 16:25:52 +0000204 if (CGM.getDataLayout().isBigEndian()) {
Craig Topper73daaa82017-04-19 05:17:33 +0000205 Tmp.lshrInPlace(NewFieldWidth);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000206 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000207
208 // We want the remaining high bits.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000209 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000210 } else {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000211 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000212
213 // We want the remaining low bits.
Craig Topper73daaa82017-04-19 05:17:33 +0000214 FieldValue.lshrInPlace(BitsInPreviousByte);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000215 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000216 }
217 }
218
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000219 Tmp = Tmp.zext(CharWidth);
Micah Villmowdd31ca12012-10-08 16:25:52 +0000220 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000221 if (FitsCompletelyInPreviousByte)
222 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
223 } else {
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000224 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000225 }
226
Chris Lattner53b479f2010-07-05 18:03:30 +0000227 // 'or' in the bits that go into the previous byte.
228 llvm::Value *LastElt = Elements.back();
229 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000230 Tmp |= Val->getValue();
Chris Lattner53b479f2010-07-05 18:03:30 +0000231 else {
232 assert(isa<llvm::UndefValue>(LastElt));
233 // If there is an undef field that we're adding to, it can either be a
234 // scalar undef (in which case, we just replace it with our field) or it
235 // is an array. If it is an array, we have to pull one byte off the
236 // array so that the other undef bytes stay around.
237 if (!isa<llvm::IntegerType>(LastElt->getType())) {
238 // The undef padding will be a multibyte array, create a new smaller
239 // padding and then an hole for our i8 to get plopped into.
240 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
241 "Expected array padding of undefs");
Chris Lattner2192fe52011-07-18 04:24:23 +0000242 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000243 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
Chris Lattner53b479f2010-07-05 18:03:30 +0000244 AT->getNumElements() != 0 &&
245 "Expected non-empty array padding of undefs");
Fangrui Song6907ce22018-07-30 19:24:48 +0000246
Chris Lattner53b479f2010-07-05 18:03:30 +0000247 // Remove the padding array.
Ken Dyckdb205d12011-03-17 01:33:18 +0000248 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
Chris Lattner53b479f2010-07-05 18:03:30 +0000249 Elements.pop_back();
Fangrui Song6907ce22018-07-30 19:24:48 +0000250
Chris Lattner53b479f2010-07-05 18:03:30 +0000251 // Add the padding back in two chunks.
Ken Dyck30a87e32011-03-11 23:42:54 +0000252 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
253 AppendPadding(CharUnits::One());
Chris Lattner53b479f2010-07-05 18:03:30 +0000254 assert(isa<llvm::UndefValue>(Elements.back()) &&
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000255 Elements.back()->getType()->isIntegerTy(CharWidth) &&
Chris Lattner53b479f2010-07-05 18:03:30 +0000256 "Padding addition didn't work right");
257 }
258 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000259
260 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
261
262 if (FitsCompletelyInPreviousByte)
Chris Lattner9a3459f2010-07-05 17:04:23 +0000263 return;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000264 }
265
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000266 while (FieldValue.getBitWidth() > CharWidth) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000267 llvm::APInt Tmp;
268
Micah Villmowdd31ca12012-10-08 16:25:52 +0000269 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000270 // We want the high bits.
Fangrui Song6907ce22018-07-30 19:24:48 +0000271 Tmp =
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000272 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000273 } else {
274 // We want the low bits.
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000275 Tmp = FieldValue.trunc(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000276
Craig Topper73daaa82017-04-19 05:17:33 +0000277 FieldValue.lshrInPlace(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000278 }
279
280 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
Ken Dyck6d470d92011-03-19 01:28:06 +0000281 ++NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000282
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000283 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000284 }
285
286 assert(FieldValue.getBitWidth() > 0 &&
287 "Should have at least one bit left!");
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000288 assert(FieldValue.getBitWidth() <= CharWidth &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000289 "Should not have more than a byte left!");
290
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000291 if (FieldValue.getBitWidth() < CharWidth) {
Micah Villmowdd31ca12012-10-08 16:25:52 +0000292 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000293 unsigned BitWidth = FieldValue.getBitWidth();
294
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000295 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000296 } else
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000297 FieldValue = FieldValue.zext(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000298 }
299
300 // Append the last element.
301 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
302 FieldValue));
Ken Dyck6d470d92011-03-19 01:28:06 +0000303 ++NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000304}
305
Ken Dyck30a87e32011-03-11 23:42:54 +0000306void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
307 if (PadSize.isZero())
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000308 return;
309
Chris Lattnerece04092012-02-07 00:39:47 +0000310 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyck30a87e32011-03-11 23:42:54 +0000311 if (PadSize > CharUnits::One())
312 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000313
Nuno Lopes5863c992010-04-16 20:56:35 +0000314 llvm::Constant *C = llvm::UndefValue::get(Ty);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000315 Elements.push_back(C);
Fangrui Song6907ce22018-07-30 19:24:48 +0000316 assert(getAlignment(C) == CharUnits::One() &&
Ken Dycka1b35102011-03-18 01:26:17 +0000317 "Padding must have 1 byte alignment!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000318
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000319 NextFieldOffsetInChars += getSizeInChars(C);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000320}
321
Ken Dyck327b77a2011-03-11 02:17:05 +0000322void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000323 assert(NextFieldOffsetInChars <= RecordSize &&
Ken Dyck327b77a2011-03-11 02:17:05 +0000324 "Size mismatch!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000325
Ken Dyckdb205d12011-03-17 01:33:18 +0000326 AppendPadding(RecordSize - NextFieldOffsetInChars);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000327}
328
329void ConstStructBuilder::ConvertStructToPacked() {
Bill Wendling1e375fa2012-02-07 00:04:27 +0000330 SmallVector<llvm::Constant *, 16> PackedElements;
Ken Dyck4e54dca2011-03-18 00:55:06 +0000331 CharUnits ElementOffsetInChars = CharUnits::Zero();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000332
333 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
334 llvm::Constant *C = Elements[i];
335
Ken Dycka1b35102011-03-18 01:26:17 +0000336 CharUnits ElementAlign = CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +0000337 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Ken Dyck4e54dca2011-03-18 00:55:06 +0000338 CharUnits AlignedElementOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000339 ElementOffsetInChars.alignTo(ElementAlign);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000340
Ken Dyck4e54dca2011-03-18 00:55:06 +0000341 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000342 // We need some padding.
Ken Dyck4e54dca2011-03-18 00:55:06 +0000343 CharUnits NumChars =
344 AlignedElementOffsetInChars - ElementOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000345
Chris Lattnerece04092012-02-07 00:39:47 +0000346 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyck4e54dca2011-03-18 00:55:06 +0000347 if (NumChars > CharUnits::One())
348 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000349
Nuno Lopes5863c992010-04-16 20:56:35 +0000350 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000351 PackedElements.push_back(Padding);
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000352 ElementOffsetInChars += getSizeInChars(Padding);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000353 }
354
355 PackedElements.push_back(C);
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000356 ElementOffsetInChars += getSizeInChars(C);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000357 }
358
Ken Dyck4e54dca2011-03-18 00:55:06 +0000359 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000360 "Packing the struct changed its size!");
361
Bill Wendling1e375fa2012-02-07 00:04:27 +0000362 Elements.swap(PackedElements);
Ken Dycka1b35102011-03-18 01:26:17 +0000363 LLVMStructAlignment = CharUnits::One();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000364 Packed = true;
365}
Fangrui Song6907ce22018-07-30 19:24:48 +0000366
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000367bool ConstStructBuilder::Build(InitListExpr *ILE) {
368 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
369 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
370
371 unsigned FieldNo = 0;
372 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000373
374 // Bail out if we have base classes. We could support these, but they only
375 // arise in C++1z where we will have already constant folded most interesting
376 // cases. FIXME: There are still a few more cases we can handle this way.
377 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
378 if (CXXRD->getNumBases())
379 return false;
380
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000381 for (RecordDecl::field_iterator Field = RD->field_begin(),
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000382 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000383 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000384 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000385 continue;
386
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000387 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000388 if (Field->isUnnamedBitfield())
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000389 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000390
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000391 // Get the initializer. A struct can include fields without initializers,
392 // we just use explicit null values for them.
393 llvm::Constant *EltInit;
394 if (ElementNo < ILE->getNumInits())
John McCallde0fe072017-08-15 21:42:52 +0000395 EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
396 Field->getType());
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000397 else
John McCallde0fe072017-08-15 21:42:52 +0000398 EltInit = Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000399
400 if (!EltInit)
401 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000402
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000403 if (!Field->isBitField()) {
404 // Handle non-bitfield members.
David Blaikie40ed2972012-06-06 20:45:41 +0000405 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000406 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000407 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000408 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
409 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
410 } else {
411 // We are trying to initialize a bitfield with a non-trivial constant,
412 // this must require run-time code.
413 return false;
414 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000415 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000416 }
417
Richard Smithdafff942012-01-14 04:30:29 +0000418 return true;
419}
420
Richard Smithc8998922012-02-23 08:33:23 +0000421namespace {
422struct BaseInfo {
423 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
424 : Decl(Decl), Offset(Offset), Index(Index) {
425 }
426
427 const CXXRecordDecl *Decl;
428 CharUnits Offset;
429 unsigned Index;
430
431 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
432};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000433}
Richard Smithc8998922012-02-23 08:33:23 +0000434
John McCallde0fe072017-08-15 21:42:52 +0000435bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000436 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000437 const CXXRecordDecl *VTableClass,
438 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000439 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
440
Richard Smithc8998922012-02-23 08:33:23 +0000441 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
442 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000443 if (CD->isDynamicClass() && !IsPrimaryBase) {
444 llvm::Constant *VTableAddressPoint =
445 CGM.getCXXABI().getVTableAddressPointForConstExpr(
446 BaseSubobject(CD, Offset), VTableClass);
447 AppendBytes(Offset, VTableAddressPoint);
448 }
Richard Smithc8998922012-02-23 08:33:23 +0000449
450 // Accumulate and sort bases, in order to visit them in address order, which
451 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000452 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000453 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000454 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000455 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000456 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000457 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000458 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
459 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000460 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
461 }
462 std::stable_sort(Bases.begin(), Bases.end());
Richard Smithdafff942012-01-14 04:30:29 +0000463
Richard Smithc8998922012-02-23 08:33:23 +0000464 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
465 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000466
Richard Smithc8998922012-02-23 08:33:23 +0000467 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
468 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000469 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000470 }
471 }
472
473 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000474 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000475
476 for (RecordDecl::field_iterator Field = RD->field_begin(),
477 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000478 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000479 if (RD->isUnion() && Val.getUnionField() != *Field)
Richard Smithdafff942012-01-14 04:30:29 +0000480 continue;
481
482 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000483 if (Field->isUnnamedBitfield())
Richard Smithdafff942012-01-14 04:30:29 +0000484 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000485
486 // Emit the value of the initializer.
487 const APValue &FieldValue =
488 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
489 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000490 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
491 if (!EltInit)
492 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000493
494 if (!Field->isBitField()) {
495 // Handle non-bitfield members.
David Blaikie40ed2972012-06-06 20:45:41 +0000496 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
Richard Smithdafff942012-01-14 04:30:29 +0000497 } else {
498 // Otherwise we have a bitfield.
David Blaikie40ed2972012-06-06 20:45:41 +0000499 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smithdafff942012-01-14 04:30:29 +0000500 cast<llvm::ConstantInt>(EltInit));
501 }
502 }
John McCallde0fe072017-08-15 21:42:52 +0000503
504 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000505}
506
507llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
508 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
509 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
510
Ken Dyckdb205d12011-03-17 01:33:18 +0000511 CharUnits LayoutSizeInChars = Layout.getSize();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000512
Ken Dyckdb205d12011-03-17 01:33:18 +0000513 if (NextFieldOffsetInChars > LayoutSizeInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000514 // If the struct is bigger than the size of the record type,
515 // we must have a flexible array member at the end.
516 assert(RD->hasFlexibleArrayMember() &&
517 "Must have flexible array member if struct is bigger than type!");
Richard Smithdafff942012-01-14 04:30:29 +0000518
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000519 // No tail padding is necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000520 } else {
521 // Append tail padding if necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000522 CharUnits LLVMSizeInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000523 NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000524
525 if (LLVMSizeInChars != LayoutSizeInChars)
526 AppendTailPadding(LayoutSizeInChars);
527
Rui Ueyama83aa9792016-01-14 21:00:27 +0000528 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
Richard Smithdafff942012-01-14 04:30:29 +0000529
530 // Check if we need to convert the struct to a packed struct.
531 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
532 LLVMSizeInChars > LayoutSizeInChars) {
533 assert(!Packed && "Size mismatch!");
534
535 ConvertStructToPacked();
536 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
537 "Converting to packed did not help!");
538 }
539
Rui Ueyama83aa9792016-01-14 21:00:27 +0000540 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000541
542 assert(LayoutSizeInChars == LLVMSizeInChars &&
Richard Smithdafff942012-01-14 04:30:29 +0000543 "Tail padding mismatch!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000544 }
545
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000546 // Pick the type to use. If the type is layout identical to the ConvertType
547 // type then use it, otherwise use whatever the builder produced for us.
Chris Lattner2192fe52011-07-18 04:24:23 +0000548 llvm::StructType *STy =
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000549 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +0000550 Elements, Packed);
551 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
552 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
553 if (ValSTy->isLayoutIdentical(STy))
554 STy = ValSTy;
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000555 }
Richard Smithdafff942012-01-14 04:30:29 +0000556
557 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
558
Rui Ueyama83aa9792016-01-14 21:00:27 +0000559 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
560 getSizeInChars(Result) &&
561 "Size mismatch!");
Richard Smithdafff942012-01-14 04:30:29 +0000562
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000563 return Result;
564}
565
John McCallde0fe072017-08-15 21:42:52 +0000566llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
567 ConstExprEmitter *ExprEmitter,
Erik Pilkingtone3b71442018-11-02 17:36:58 +0000568 llvm::Constant *Base,
John McCallde0fe072017-08-15 21:42:52 +0000569 InitListExpr *Updater,
570 QualType ValTy) {
571 ConstStructBuilder Builder(Emitter);
572 if (!Builder.Build(ExprEmitter, Base, Updater))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000573 return nullptr;
John McCallde0fe072017-08-15 21:42:52 +0000574 return Builder.Finalize(ValTy);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000575}
576
John McCallde0fe072017-08-15 21:42:52 +0000577llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
578 InitListExpr *ILE,
579 QualType ValTy) {
580 ConstStructBuilder Builder(Emitter);
Richard Smithdafff942012-01-14 04:30:29 +0000581
582 if (!Builder.Build(ILE))
Craig Topper8a13c412014-05-21 05:09:00 +0000583 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000584
John McCallde0fe072017-08-15 21:42:52 +0000585 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000586}
587
John McCallde0fe072017-08-15 21:42:52 +0000588llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000589 const APValue &Val,
590 QualType ValTy) {
John McCallde0fe072017-08-15 21:42:52 +0000591 ConstStructBuilder Builder(Emitter);
Richard Smithc8998922012-02-23 08:33:23 +0000592
593 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
594 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000595 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
596 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000597
Richard Smithdafff942012-01-14 04:30:29 +0000598 return Builder.Finalize(ValTy);
599}
600
601
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000602//===----------------------------------------------------------------------===//
603// ConstExprEmitter
604//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000605
John McCallde0fe072017-08-15 21:42:52 +0000606static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
607 CodeGenFunction *CGF,
608 const CompoundLiteralExpr *E) {
609 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
610 if (llvm::GlobalVariable *Addr =
611 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
612 return ConstantAddress(Addr, Align);
613
Alexander Richardson6d989432017-10-15 18:48:14 +0000614 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000615
616 ConstantEmitter emitter(CGM, CGF);
617 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
618 addressSpace, E->getType());
619 if (!C) {
620 assert(!E->isFileScope() &&
621 "file-scope compound literal did not have constant initializer!");
622 return ConstantAddress::invalid();
623 }
624
625 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
626 CGM.isTypeConstant(E->getType(), true),
627 llvm::GlobalValue::InternalLinkage,
628 C, ".compoundliteral", nullptr,
629 llvm::GlobalVariable::NotThreadLocal,
630 CGM.getContext().getTargetAddressSpace(addressSpace));
631 emitter.finalize(GV);
632 GV->setAlignment(Align.getQuantity());
633 CGM.setAddrOfConstantCompoundLiteral(E, GV);
634 return ConstantAddress(GV, Align);
635}
636
Richard Smith3e268632018-05-23 23:41:38 +0000637static llvm::Constant *
638EmitArrayConstant(CodeGenModule &CGM, const ConstantArrayType *DestType,
639 llvm::Type *CommonElementType, unsigned ArrayBound,
640 SmallVectorImpl<llvm::Constant *> &Elements,
641 llvm::Constant *Filler) {
642 // Figure out how long the initial prefix of non-zero elements is.
643 unsigned NonzeroLength = ArrayBound;
644 if (Elements.size() < NonzeroLength && Filler->isNullValue())
645 NonzeroLength = Elements.size();
646 if (NonzeroLength == Elements.size()) {
647 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
648 --NonzeroLength;
649 }
650
651 if (NonzeroLength == 0) {
652 return llvm::ConstantAggregateZero::get(
653 CGM.getTypes().ConvertType(QualType(DestType, 0)));
654 }
655
656 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
657 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
658 if (TrailingZeroes >= 8) {
659 assert(Elements.size() >= NonzeroLength &&
660 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000661
662 // If all the elements had the same type up to the trailing zeroes, emit a
663 // struct of two arrays (the nonzero data and the zeroinitializer).
664 if (CommonElementType && NonzeroLength >= 8) {
665 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000666 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000667 makeArrayRef(Elements).take_front(NonzeroLength));
668 Elements.resize(2);
669 Elements[0] = Initial;
670 } else {
671 Elements.resize(NonzeroLength + 1);
672 }
673
Richard Smith3e268632018-05-23 23:41:38 +0000674 auto *FillerType =
675 CommonElementType
676 ? CommonElementType
677 : CGM.getTypes().ConvertType(DestType->getElementType());
678 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
679 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
680 CommonElementType = nullptr;
681 } else if (Elements.size() != ArrayBound) {
682 // Otherwise pad to the right size with the filler if necessary.
683 Elements.resize(ArrayBound, Filler);
684 if (Filler->getType() != CommonElementType)
685 CommonElementType = nullptr;
686 }
687
688 // If all elements have the same type, just emit an array constant.
689 if (CommonElementType)
690 return llvm::ConstantArray::get(
691 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
692
693 // We have mixed types. Use a packed struct.
694 llvm::SmallVector<llvm::Type *, 16> Types;
695 Types.reserve(Elements.size());
696 for (llvm::Constant *Elt : Elements)
697 Types.push_back(Elt->getType());
698 llvm::StructType *SType =
699 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
700 return llvm::ConstantStruct::get(SType, Elements);
701}
702
Eli Friedman7f98e3c2019-02-08 21:36:04 +0000703// This class only needs to handle arrays, structs and unions. Outside C++11
704// mode, we don't currently constant fold those types. All other types are
705// handled by constant folding.
706//
707// Constant folding is currently missing support for a few features supported
708// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000709class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000710 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000711 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000712 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000713 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +0000714public:
John McCallde0fe072017-08-15 21:42:52 +0000715 ConstExprEmitter(ConstantEmitter &emitter)
716 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +0000717 }
Mike Stump11289f42009-09-09 15:08:12 +0000718
Anders Carlsson610ee712008-01-26 01:36:00 +0000719 //===--------------------------------------------------------------------===//
720 // Visitor Methods
721 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000722
John McCallde0fe072017-08-15 21:42:52 +0000723 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +0000724 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000725 }
Mike Stump11289f42009-09-09 15:08:12 +0000726
Bill Wendling8003edc2018-11-09 00:41:36 +0000727 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
728 return Visit(CE->getSubExpr(), T);
729 }
730
John McCallde0fe072017-08-15 21:42:52 +0000731 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
732 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +0000733 }
Mike Stump11289f42009-09-09 15:08:12 +0000734
John McCall7c454bb2011-07-15 05:09:51 +0000735 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +0000736 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
737 QualType T) {
738 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +0000739 }
740
John McCallde0fe072017-08-15 21:42:52 +0000741 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
742 QualType T) {
743 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +0000744 }
745
John McCallde0fe072017-08-15 21:42:52 +0000746 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
747 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +0000748 }
749
John McCallde0fe072017-08-15 21:42:52 +0000750 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
751 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +0000752 }
John McCallf3a88602011-02-03 08:15:49 +0000753
John McCallde0fe072017-08-15 21:42:52 +0000754 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000755 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +0000756 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +0000757 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +0000758
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000759 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +0000760 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000761 // GCC cast to union extension
762 assert(E->getType()->isUnionType() &&
763 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +0000764
John McCallde0fe072017-08-15 21:42:52 +0000765 auto field = E->getTargetUnionField();
766
767 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
768 if (!C) return nullptr;
769
770 auto destTy = ConvertType(destType);
771 if (C->getType() == destTy) return C;
772
Anders Carlssond65ab042009-07-31 21:38:39 +0000773 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +0000774 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +0000775 SmallVector<llvm::Constant*, 2> Elts;
776 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +0000777 Elts.push_back(C);
778 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +0000779 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +0000780 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +0000781
Anders Carlssond65ab042009-07-31 21:38:39 +0000782 assert(CurSize <= TotalSize && "Union size mismatch!");
783 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +0000784 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +0000785 if (NumPadBytes > 1)
786 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000787
Nuno Lopes5863c992010-04-16 20:56:35 +0000788 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +0000789 Types.push_back(Ty);
790 }
Mike Stump11289f42009-09-09 15:08:12 +0000791
John McCallde0fe072017-08-15 21:42:52 +0000792 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +0000793 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +0000794 }
Anders Carlsson9500ad12009-10-18 20:31:03 +0000795
John McCallde0fe072017-08-15 21:42:52 +0000796 case CK_AddressSpaceConversion: {
797 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
798 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +0000799 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
800 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000801 llvm::Type *destTy = ConvertType(E->getType());
802 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
803 destAS, destTy);
804 }
David Tweede1468322013-12-11 13:39:46 +0000805
John McCall2de87f62011-03-15 21:17:48 +0000806 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +0000807 case CK_AtomicToNonAtomic:
808 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +0000809 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +0000810 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +0000811 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +0000812
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +0000813 case CK_IntToOCLSampler:
814 llvm_unreachable("global sampler variables are not generated");
815
John McCall2de87f62011-03-15 21:17:48 +0000816 case CK_Dependent: llvm_unreachable("saw dependent cast!");
817
Eli Friedman34866c72012-08-31 00:14:07 +0000818 case CK_BuiltinFnToFnPtr:
819 llvm_unreachable("builtin functions are handled elsewhere");
820
John McCallc62bb392012-02-15 01:22:51 +0000821 case CK_ReinterpretMemberPointer:
822 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +0000823 case CK_BaseToDerivedMemberPointer: {
824 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
825 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +0000826 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +0000827 }
John McCallc62bb392012-02-15 01:22:51 +0000828
John McCall2de87f62011-03-15 21:17:48 +0000829 // These will never be supported.
830 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +0000831 case CK_ARCProduceObject:
832 case CK_ARCConsumeObject:
833 case CK_ARCReclaimReturnedObject:
834 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +0000835 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +0000836 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +0000837
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000838 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +0000839 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +0000840 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +0000841 case CK_ToVoid:
842 case CK_Dynamic:
843 case CK_LValueBitCast:
844 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +0000845 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000846 case CK_CPointerToObjCPointerCast:
847 case CK_BlockPointerToObjCPointerCast:
848 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +0000849 case CK_ArrayToPointerDecay:
850 case CK_FunctionToPointerDecay:
851 case CK_BaseToDerived:
852 case CK_DerivedToBase:
853 case CK_UncheckedDerivedToBase:
854 case CK_MemberPointerToBoolean:
855 case CK_VectorSplat:
856 case CK_FloatingRealToComplex:
857 case CK_FloatingComplexToReal:
858 case CK_FloatingComplexToBoolean:
859 case CK_FloatingComplexCast:
860 case CK_FloatingComplexToIntegralComplex:
861 case CK_IntegralRealToComplex:
862 case CK_IntegralComplexToReal:
863 case CK_IntegralComplexToBoolean:
864 case CK_IntegralComplexCast:
865 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +0000866 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +0000867 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000868 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000869 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000870 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000871 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +0000872 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000873 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +0000874 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +0000875 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000876 case CK_FloatingCast:
Leonard Chan99bda372018-10-15 16:07:02 +0000877 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +0000878 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +0000879 case CK_FixedPointToIntegral:
880 case CK_IntegralToFixedPoint:
Andrew Savonichevb555b762018-10-23 15:19:20 +0000881 case CK_ZeroToOCLOpaqueType:
Craig Topper8a13c412014-05-21 05:09:00 +0000882 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000883 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +0000884 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +0000885 }
Devang Patela703a672008-02-05 02:39:50 +0000886
John McCallde0fe072017-08-15 21:42:52 +0000887 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
888 return Visit(DAE->getExpr(), T);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000889 }
890
John McCallde0fe072017-08-15 21:42:52 +0000891 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +0000892 // No need for a DefaultInitExprScope: we don't handle 'this' in a
893 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +0000894 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +0000895 }
896
John McCallde0fe072017-08-15 21:42:52 +0000897 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Tim Shen4a05bb82016-06-21 20:29:17 +0000898 if (!E->cleanupsHaveSideEffects())
John McCallde0fe072017-08-15 21:42:52 +0000899 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +0000900 return nullptr;
901 }
902
John McCallde0fe072017-08-15 21:42:52 +0000903 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
904 QualType T) {
905 return Visit(E->GetTemporaryExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +0000906 }
907
John McCallde0fe072017-08-15 21:42:52 +0000908 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +0000909 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
910 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +0000911 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +0000912 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +0000913
Mike Stump11289f42009-09-09 15:08:12 +0000914 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +0000915 // initialise any elements that have not been initialised explicitly
916 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
917
Richard Smith3e268632018-05-23 23:41:38 +0000918 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +0000919
David Majnemer90d85442014-12-28 23:46:59 +0000920 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +0000921 llvm::Constant *fillC = nullptr;
922 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +0000923 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +0000924 if (!fillC)
925 return nullptr;
926 }
David Majnemer90d85442014-12-28 23:46:59 +0000927
Devang Patela703a672008-02-05 02:39:50 +0000928 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +0000929 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +0000930 if (fillC && fillC->isNullValue())
931 Elts.reserve(NumInitableElts + 1);
932 else
933 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +0000934
Richard Smith3e268632018-05-23 23:41:38 +0000935 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +0000936 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +0000937 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +0000938 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +0000939 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +0000940 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +0000941 if (i == 0)
942 CommonElementType = C->getType();
943 else if (C->getType() != CommonElementType)
944 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +0000945 Elts.push_back(C);
946 }
Eli Friedman34994cb2008-05-30 19:58:50 +0000947
Richard Smith3e268632018-05-23 23:41:38 +0000948 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
949 fillC);
Devang Patela703a672008-02-05 02:39:50 +0000950 }
951
John McCallde0fe072017-08-15 21:42:52 +0000952 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
953 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +0000954 }
955
John McCallde0fe072017-08-15 21:42:52 +0000956 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
957 QualType T) {
958 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
John McCallde0fe072017-08-15 21:42:52 +0000961 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +0000962 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +0000963 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +0000964
Eli Friedmana2eaffc2008-05-30 10:24:46 +0000965 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +0000966 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +0000967
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +0000968 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +0000969 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +0000970
Craig Topper8a13c412014-05-21 05:09:00 +0000971 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000972 }
Eli Friedmana2433112008-02-21 17:57:49 +0000973
Yunzhong Gaocb779302015-06-10 00:27:52 +0000974 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
John McCallde0fe072017-08-15 21:42:52 +0000975 InitListExpr *Updater,
976 QualType destType) {
977 if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
978 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
Yunzhong Gaocb779302015-06-10 00:27:52 +0000979 llvm::Type *ElemType = AType->getElementType();
980
981 unsigned NumInitElements = Updater->getNumInits();
982 unsigned NumElements = AType->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +0000983
Yunzhong Gaocb779302015-06-10 00:27:52 +0000984 std::vector<llvm::Constant *> Elts;
985 Elts.reserve(NumElements);
986
John McCallde0fe072017-08-15 21:42:52 +0000987 QualType destElemType = destAT->getElementType();
988
989 if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000990 for (unsigned i = 0; i != NumElements; ++i)
991 Elts.push_back(DataArray->getElementAsConstant(i));
John McCallde0fe072017-08-15 21:42:52 +0000992 else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000993 for (unsigned i = 0; i != NumElements; ++i)
994 Elts.push_back(Array->getOperand(i));
995 else
996 return nullptr; // FIXME: other array types not implemented
997
998 llvm::Constant *fillC = nullptr;
999 if (Expr *filler = Updater->getArrayFiller())
1000 if (!isa<NoInitExpr>(filler))
John McCallde0fe072017-08-15 21:42:52 +00001001 fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001002 bool RewriteType = (fillC && fillC->getType() != ElemType);
1003
1004 for (unsigned i = 0; i != NumElements; ++i) {
1005 Expr *Init = nullptr;
1006 if (i < NumInitElements)
1007 Init = Updater->getInit(i);
1008
1009 if (!Init && fillC)
1010 Elts[i] = fillC;
1011 else if (!Init || isa<NoInitExpr>(Init))
1012 ; // Do nothing.
1013 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
John McCallde0fe072017-08-15 21:42:52 +00001014 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001015 else
John McCallde0fe072017-08-15 21:42:52 +00001016 Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001017
Yunzhong Gaocb779302015-06-10 00:27:52 +00001018 if (!Elts[i])
1019 return nullptr;
1020 RewriteType |= (Elts[i]->getType() != ElemType);
1021 }
1022
1023 if (RewriteType) {
1024 std::vector<llvm::Type *> Types;
1025 Types.reserve(NumElements);
1026 for (unsigned i = 0; i != NumElements; ++i)
1027 Types.push_back(Elts[i]->getType());
1028 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1029 Types, true);
1030 return llvm::ConstantStruct::get(SType, Elts);
1031 }
1032
1033 return llvm::ConstantArray::get(AType, Elts);
1034 }
1035
John McCallde0fe072017-08-15 21:42:52 +00001036 if (destType->isRecordType())
Erik Pilkingtone3b71442018-11-02 17:36:58 +00001037 return ConstStructBuilder::BuildStruct(Emitter, this, Base, Updater,
1038 destType);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001039
1040 return nullptr;
1041 }
1042
John McCallde0fe072017-08-15 21:42:52 +00001043 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1044 QualType destType) {
1045 auto C = Visit(E->getBase(), destType);
1046 if (!C) return nullptr;
1047 return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001048 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001049
John McCallde0fe072017-08-15 21:42:52 +00001050 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001051 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001052 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001053
Anders Carlssoncb86e102010-02-05 18:38:45 +00001054 // FIXME: We should not have to call getBaseElementType here.
Fangrui Song6907ce22018-07-30 19:24:48 +00001055 const RecordType *RT =
Anders Carlssoncb86e102010-02-05 18:38:45 +00001056 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1057 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001058
Anders Carlssoncb86e102010-02-05 18:38:45 +00001059 // If the class doesn't have a trivial destructor, we can't emit it as a
1060 // constant expr.
1061 if (!RD->hasTrivialDestructor())
Craig Topper8a13c412014-05-21 05:09:00 +00001062 return nullptr;
1063
John McCall49786a62010-02-02 08:02:49 +00001064 // Only copy and default constructors can be trivial.
1065
John McCall49786a62010-02-02 08:02:49 +00001066
1067 if (E->getNumArgs()) {
1068 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001069 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1070 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001071
1072 Expr *Arg = E->getArg(0);
1073 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1074 "argument to copy ctor is of wrong type");
1075
John McCallde0fe072017-08-15 21:42:52 +00001076 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001077 }
1078
1079 return CGM.EmitNullConstant(Ty);
1080 }
1081
John McCallde0fe072017-08-15 21:42:52 +00001082 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001083 // This is a string literal initializing an array in an initializer.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001084 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001085 }
1086
John McCallde0fe072017-08-15 21:42:52 +00001087 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001088 // This must be an @encode initializing an array in a static initializer.
1089 // Don't emit it as the address of the string, emit the string data itself
1090 // as an inline array.
1091 std::string Str;
1092 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001093 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001094
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001095 // Resize the string to the right size, adding zeros at the end, or
1096 // truncating as needed.
1097 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001098 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
John McCallde0fe072017-08-15 21:42:52 +00001101 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1102 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001103 }
Mike Stumpa6703322009-02-19 22:01:56 +00001104
Anders Carlsson610ee712008-01-26 01:36:00 +00001105 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001106 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001107 return CGM.getTypes().ConvertType(T);
1108 }
Anders Carlssona4139112008-01-26 02:08:50 +00001109};
Mike Stump11289f42009-09-09 15:08:12 +00001110
Anders Carlsson610ee712008-01-26 01:36:00 +00001111} // end anonymous namespace.
1112
John McCallde0fe072017-08-15 21:42:52 +00001113bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
Erik Pilkingtone3b71442018-11-02 17:36:58 +00001114 llvm::Constant *Base,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001115 InitListExpr *Updater) {
1116 assert(Base && "base expression should not be empty");
1117
1118 QualType ExprType = Updater->getType();
1119 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1120 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1121 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
Erik Pilkingtone3b71442018-11-02 17:36:58 +00001122 cast<llvm::StructType>(Base->getType()));
Yunzhong Gaocb779302015-06-10 00:27:52 +00001123 unsigned FieldNo = -1;
1124 unsigned ElementNo = 0;
1125
Richard Smith872307e2016-03-08 22:17:41 +00001126 // Bail out if we have base classes. We could support these, but they only
1127 // arise in C++1z where we will have already constant folded most interesting
1128 // cases. FIXME: There are still a few more cases we can handle this way.
1129 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1130 if (CXXRD->getNumBases())
1131 return false;
1132
Yunzhong Gaocb779302015-06-10 00:27:52 +00001133 for (FieldDecl *Field : RD->fields()) {
1134 ++FieldNo;
1135
1136 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1137 continue;
1138
1139 // Skip anonymous bitfields.
1140 if (Field->isUnnamedBitfield())
1141 continue;
1142
Erik Pilkingtone3b71442018-11-02 17:36:58 +00001143 llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001144
1145 // Bail out if the type of the ConstantStruct does not have the same layout
1146 // as the type of the InitListExpr.
1147 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1148 Layout.getFieldOffset(ElementNo) !=
1149 BaseLayout->getElementOffsetInBits(ElementNo))
1150 return false;
1151
1152 // Get the initializer. If we encounter an empty field or a NoInitExpr,
1153 // we use values from the base expression.
1154 Expr *Init = nullptr;
1155 if (ElementNo < Updater->getNumInits())
1156 Init = Updater->getInit(ElementNo);
1157
1158 if (!Init || isa<NoInitExpr>(Init))
1159 ; // Do nothing.
1160 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
John McCallde0fe072017-08-15 21:42:52 +00001161 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1162 Field->getType());
Yunzhong Gaocb779302015-06-10 00:27:52 +00001163 else
John McCallde0fe072017-08-15 21:42:52 +00001164 EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
Yunzhong Gaocb779302015-06-10 00:27:52 +00001165
1166 ++ElementNo;
1167
1168 if (!EltInit)
1169 return false;
1170
1171 if (!Field->isBitField())
1172 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1173 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1174 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1175 else
1176 // Initializing a bitfield with a non-trivial constant?
1177 return false;
1178 }
1179
1180 return true;
1181}
1182
John McCallde0fe072017-08-15 21:42:52 +00001183llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1184 AbstractState saved) {
1185 Abstract = saved.OldValue;
1186
1187 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1188 "created a placeholder while doing an abstract emission?");
1189
1190 // No validation necessary for now.
1191 // No cleanup to do for now.
1192 return C;
1193}
1194
1195llvm::Constant *
1196ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1197 auto state = pushAbstract();
1198 auto C = tryEmitPrivateForVarInit(D);
1199 return validateAndPopAbstract(C, state);
1200}
1201
1202llvm::Constant *
1203ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1204 auto state = pushAbstract();
1205 auto C = tryEmitPrivate(E, destType);
1206 return validateAndPopAbstract(C, state);
1207}
1208
1209llvm::Constant *
1210ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1211 auto state = pushAbstract();
1212 auto C = tryEmitPrivate(value, destType);
1213 return validateAndPopAbstract(C, state);
1214}
1215
1216llvm::Constant *
1217ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1218 auto state = pushAbstract();
1219 auto C = tryEmitPrivate(E, destType);
1220 C = validateAndPopAbstract(C, state);
1221 if (!C) {
1222 CGM.Error(E->getExprLoc(),
1223 "internal error: could not emit constant value \"abstractly\"");
1224 C = CGM.EmitNullConstant(destType);
1225 }
1226 return C;
1227}
1228
1229llvm::Constant *
1230ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1231 QualType destType) {
1232 auto state = pushAbstract();
1233 auto C = tryEmitPrivate(value, destType);
1234 C = validateAndPopAbstract(C, state);
1235 if (!C) {
1236 CGM.Error(loc,
1237 "internal error: could not emit constant value \"abstractly\"");
1238 C = CGM.EmitNullConstant(destType);
1239 }
1240 return C;
1241}
1242
1243llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1244 initializeNonAbstract(D.getType().getAddressSpace());
1245 return markIfFailed(tryEmitPrivateForVarInit(D));
1246}
1247
1248llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001249 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001250 QualType destType) {
1251 initializeNonAbstract(destAddrSpace);
1252 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1253}
1254
1255llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001256 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001257 QualType destType) {
1258 initializeNonAbstract(destAddrSpace);
1259 auto C = tryEmitPrivateForMemory(value, destType);
1260 assert(C && "couldn't emit constant value non-abstractly?");
1261 return C;
1262}
1263
1264llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1265 assert(!Abstract && "cannot get current address for abstract constant");
1266
1267
1268
1269 // Make an obviously ill-formed global that should blow up compilation
1270 // if it survives.
1271 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1272 llvm::GlobalValue::PrivateLinkage,
1273 /*init*/ nullptr,
1274 /*name*/ "",
1275 /*before*/ nullptr,
1276 llvm::GlobalVariable::NotThreadLocal,
1277 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1278
1279 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1280
1281 return global;
1282}
1283
1284void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1285 llvm::GlobalValue *placeholder) {
1286 assert(!PlaceholderAddresses.empty());
1287 assert(PlaceholderAddresses.back().first == nullptr);
1288 assert(PlaceholderAddresses.back().second == placeholder);
1289 PlaceholderAddresses.back().first = signal;
1290}
1291
1292namespace {
1293 struct ReplacePlaceholders {
1294 CodeGenModule &CGM;
1295
1296 /// The base address of the global.
1297 llvm::Constant *Base;
1298 llvm::Type *BaseValueTy = nullptr;
1299
1300 /// The placeholder addresses that were registered during emission.
1301 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1302
1303 /// The locations of the placeholder signals.
1304 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1305
1306 /// The current index stack. We use a simple unsigned stack because
1307 /// we assume that placeholders will be relatively sparse in the
1308 /// initializer, but we cache the index values we find just in case.
1309 llvm::SmallVector<unsigned, 8> Indices;
1310 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1311
1312 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1313 ArrayRef<std::pair<llvm::Constant*,
1314 llvm::GlobalVariable*>> addresses)
1315 : CGM(CGM), Base(base),
1316 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1317 }
1318
1319 void replaceInInitializer(llvm::Constant *init) {
1320 // Remember the type of the top-most initializer.
1321 BaseValueTy = init->getType();
1322
1323 // Initialize the stack.
1324 Indices.push_back(0);
1325 IndexValues.push_back(nullptr);
1326
1327 // Recurse into the initializer.
1328 findLocations(init);
1329
1330 // Check invariants.
1331 assert(IndexValues.size() == Indices.size() && "mismatch");
1332 assert(Indices.size() == 1 && "didn't pop all indices");
1333
1334 // Do the replacement; this basically invalidates 'init'.
1335 assert(Locations.size() == PlaceholderAddresses.size() &&
1336 "missed a placeholder?");
1337
1338 // We're iterating over a hashtable, so this would be a source of
1339 // non-determinism in compiler output *except* that we're just
1340 // messing around with llvm::Constant structures, which never itself
1341 // does anything that should be visible in compiler output.
1342 for (auto &entry : Locations) {
1343 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1344 entry.first->replaceAllUsesWith(entry.second);
1345 entry.first->eraseFromParent();
1346 }
1347 }
1348
1349 private:
1350 void findLocations(llvm::Constant *init) {
1351 // Recurse into aggregates.
1352 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1353 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1354 Indices.push_back(i);
1355 IndexValues.push_back(nullptr);
1356
1357 findLocations(agg->getOperand(i));
1358
1359 IndexValues.pop_back();
1360 Indices.pop_back();
1361 }
1362 return;
1363 }
1364
1365 // Otherwise, check for registered constants.
1366 while (true) {
1367 auto it = PlaceholderAddresses.find(init);
1368 if (it != PlaceholderAddresses.end()) {
1369 setLocation(it->second);
1370 break;
1371 }
1372
1373 // Look through bitcasts or other expressions.
1374 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1375 init = expr->getOperand(0);
1376 } else {
1377 break;
1378 }
1379 }
1380 }
1381
1382 void setLocation(llvm::GlobalVariable *placeholder) {
1383 assert(Locations.find(placeholder) == Locations.end() &&
1384 "already found location for placeholder!");
1385
1386 // Lazily fill in IndexValues with the values from Indices.
1387 // We do this in reverse because we should always have a strict
1388 // prefix of indices from the start.
1389 assert(Indices.size() == IndexValues.size());
1390 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1391 if (IndexValues[i]) {
1392#ifndef NDEBUG
1393 for (size_t j = 0; j != i + 1; ++j) {
1394 assert(IndexValues[j] &&
1395 isa<llvm::ConstantInt>(IndexValues[j]) &&
1396 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1397 == Indices[j]);
1398 }
1399#endif
1400 break;
1401 }
1402
1403 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1404 }
1405
1406 // Form a GEP and then bitcast to the placeholder type so that the
1407 // replacement will succeed.
1408 llvm::Constant *location =
1409 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1410 Base, IndexValues);
1411 location = llvm::ConstantExpr::getBitCast(location,
1412 placeholder->getType());
1413
1414 Locations.insert({placeholder, location});
1415 }
1416 };
1417}
1418
1419void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1420 assert(InitializedNonAbstract &&
1421 "finalizing emitter that was used for abstract emission?");
1422 assert(!Finalized && "finalizing emitter multiple times");
1423 assert(global->getInitializer());
1424
1425 // Note that we might also be Failed.
1426 Finalized = true;
1427
1428 if (!PlaceholderAddresses.empty()) {
1429 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1430 .replaceInInitializer(global->getInitializer());
1431 PlaceholderAddresses.clear(); // satisfy
1432 }
1433}
1434
1435ConstantEmitter::~ConstantEmitter() {
1436 assert((!InitializedNonAbstract || Finalized || Failed) &&
1437 "not finalized after being initialized for non-abstract emission");
1438 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1439}
1440
1441static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1442 if (auto AT = type->getAs<AtomicType>()) {
1443 return CGM.getContext().getQualifiedType(AT->getValueType(),
1444 type.getQualifiers());
1445 }
1446 return type;
1447}
1448
1449llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001450 // Make a quick check if variable can be default NULL initialized
1451 // and avoid going through rest of code which may do, for c++11,
1452 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001453 if (!D.hasLocalStorage()) {
1454 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1455 if (Ty->isRecordType())
1456 if (const CXXConstructExpr *E =
1457 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1458 const CXXConstructorDecl *CD = E->getConstructor();
1459 if (CD->isTrivial() && CD->isDefaultConstructor())
1460 return CGM.EmitNullConstant(D.getType());
1461 }
Bill Wendling958b94d2018-12-01 09:06:26 +00001462 InConstantContext = true;
Richard Smith3f1d6de2018-05-21 20:36:58 +00001463 }
John McCallde0fe072017-08-15 21:42:52 +00001464
1465 QualType destType = D.getType();
1466
1467 // Try to emit the initializer. Note that this can allow some things that
1468 // are not allowed by tryEmitPrivateForMemory alone.
1469 if (auto value = D.evaluateValue()) {
1470 return tryEmitPrivateForMemory(*value, destType);
1471 }
Richard Smithdafff942012-01-14 04:30:29 +00001472
Richard Smith6331c402012-02-13 22:16:19 +00001473 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1474 // reference is a constant expression, and the reference binds to a temporary,
1475 // then constant initialization is performed. ConstExprEmitter will
1476 // incorrectly emit a prvalue constant in this case, and the calling code
1477 // interprets that as the (pointer) value of the reference, rather than the
1478 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001479 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001480 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001481
Richard Smithdafff942012-01-14 04:30:29 +00001482 const Expr *E = D.getInit();
1483 assert(E && "No initializer to emit");
1484
John McCallde0fe072017-08-15 21:42:52 +00001485 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1486 auto C =
1487 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1488 return (C ? emitForMemory(C, destType) : nullptr);
1489}
1490
1491llvm::Constant *
1492ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1493 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1494 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001495 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001496}
1497
1498llvm::Constant *
1499ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1500 QualType destType) {
1501 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1502 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001503 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001504}
1505
1506llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1507 QualType destType) {
1508 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1509 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1510 return (C ? emitForMemory(C, destType) : nullptr);
1511}
1512
1513llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1514 QualType destType) {
1515 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1516 auto C = tryEmitPrivate(value, nonMemoryDestType);
1517 return (C ? emitForMemory(C, destType) : nullptr);
1518}
1519
1520llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1521 llvm::Constant *C,
1522 QualType destType) {
1523 // For an _Atomic-qualified constant, we may need to add tail padding.
1524 if (auto AT = destType->getAs<AtomicType>()) {
1525 QualType destValueType = AT->getValueType();
1526 C = emitForMemory(CGM, C, destValueType);
1527
1528 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1529 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1530 if (innerSize == outerSize)
1531 return C;
1532
1533 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1534 llvm::Constant *elts[] = {
1535 C,
1536 llvm::ConstantAggregateZero::get(
1537 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1538 };
1539 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001540 }
John McCallde0fe072017-08-15 21:42:52 +00001541
1542 // Zero-extend bool.
1543 if (C->getType()->isIntegerTy(1)) {
1544 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1545 return llvm::ConstantExpr::getZExt(C, boolTy);
1546 }
1547
Richard Smithdafff942012-01-14 04:30:29 +00001548 return C;
1549}
1550
John McCallde0fe072017-08-15 21:42:52 +00001551llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1552 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001553 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001554
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001555 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001556
John McCallde0fe072017-08-15 21:42:52 +00001557 if (destType->isReferenceType())
1558 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001559 else
Bill Wendling2a81f662018-12-01 08:29:36 +00001560 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
Mike Stump11289f42009-09-09 15:08:12 +00001561
John McCallde0fe072017-08-15 21:42:52 +00001562 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001563 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001564 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001565 else
John McCallde0fe072017-08-15 21:42:52 +00001566 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001567
Eli Friedman10c24172008-06-01 15:31:44 +00001568 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001569}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001570
Yaxun Liu402804b2016-12-15 08:09:08 +00001571llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1572 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1573}
1574
John McCall99e5e982017-08-17 05:03:55 +00001575namespace {
1576/// A struct which can be used to peephole certain kinds of finalization
1577/// that normally happen during l-value emission.
1578struct ConstantLValue {
1579 llvm::Constant *Value;
1580 bool HasOffsetApplied;
1581
1582 /*implicit*/ ConstantLValue(llvm::Constant *value,
1583 bool hasOffsetApplied = false)
1584 : Value(value), HasOffsetApplied(false) {}
1585
1586 /*implicit*/ ConstantLValue(ConstantAddress address)
1587 : ConstantLValue(address.getPointer()) {}
1588};
1589
1590/// A helper class for emitting constant l-values.
1591class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1592 ConstantLValue> {
1593 CodeGenModule &CGM;
1594 ConstantEmitter &Emitter;
1595 const APValue &Value;
1596 QualType DestType;
1597
1598 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1599 friend StmtVisitorBase;
1600
1601public:
1602 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1603 QualType destType)
1604 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1605
1606 llvm::Constant *tryEmit();
1607
1608private:
1609 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1610 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1611
1612 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
Bill Wendling8003edc2018-11-09 00:41:36 +00001613 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001614 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1615 ConstantLValue VisitStringLiteral(const StringLiteral *E);
1616 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1617 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1618 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1619 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1620 ConstantLValue VisitCallExpr(const CallExpr *E);
1621 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1622 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1623 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1624 ConstantLValue VisitMaterializeTemporaryExpr(
1625 const MaterializeTemporaryExpr *E);
1626
1627 bool hasNonZeroOffset() const {
1628 return !Value.getLValueOffset().isZero();
1629 }
1630
1631 /// Return the value offset.
1632 llvm::Constant *getOffset() {
1633 return llvm::ConstantInt::get(CGM.Int64Ty,
1634 Value.getLValueOffset().getQuantity());
1635 }
1636
1637 /// Apply the value offset to the given constant.
1638 llvm::Constant *applyOffset(llvm::Constant *C) {
1639 if (!hasNonZeroOffset())
1640 return C;
1641
1642 llvm::Type *origPtrTy = C->getType();
1643 unsigned AS = origPtrTy->getPointerAddressSpace();
1644 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1645 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1646 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1647 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1648 return C;
1649 }
1650};
1651
1652}
1653
1654llvm::Constant *ConstantLValueEmitter::tryEmit() {
1655 const APValue::LValueBase &base = Value.getLValueBase();
1656
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001657 // The destination type should be a pointer or reference
John McCall99e5e982017-08-17 05:03:55 +00001658 // type, but it might also be a cast thereof.
1659 //
1660 // FIXME: the chain of casts required should be reflected in the APValue.
1661 // We need this in order to correctly handle things like a ptrtoint of a
1662 // non-zero null pointer and addrspace casts that aren't trivially
1663 // represented in LLVM IR.
1664 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1665 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1666
1667 // If there's no base at all, this is a null or absolute pointer,
1668 // possibly cast back to an integer type.
1669 if (!base) {
1670 return tryEmitAbsolute(destTy);
1671 }
1672
1673 // Otherwise, try to emit the base.
1674 ConstantLValue result = tryEmitBase(base);
1675
1676 // If that failed, we're done.
1677 llvm::Constant *value = result.Value;
1678 if (!value) return nullptr;
1679
1680 // Apply the offset if necessary and not already done.
1681 if (!result.HasOffsetApplied) {
1682 value = applyOffset(value);
1683 }
1684
1685 // Convert to the appropriate type; this could be an lvalue for
1686 // an integer. FIXME: performAddrSpaceCast
1687 if (isa<llvm::PointerType>(destTy))
1688 return llvm::ConstantExpr::getPointerCast(value, destTy);
1689
1690 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1691}
1692
1693/// Try to emit an absolute l-value, such as a null pointer or an integer
1694/// bitcast to pointer type.
1695llvm::Constant *
1696ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1697 auto offset = getOffset();
1698
1699 // If we're producing a pointer, this is easy.
1700 if (auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1701 if (Value.isNullPointer()) {
1702 // FIXME: integer offsets from non-zero null pointers.
1703 return CGM.getNullPointer(destPtrTy, DestType);
1704 }
1705
1706 // Convert the integer to a pointer-sized integer before converting it
1707 // to a pointer.
1708 // FIXME: signedness depends on the original integer type.
1709 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1710 llvm::Constant *C = offset;
1711 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1712 /*isSigned*/ false);
1713 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1714 return C;
1715 }
1716
1717 // Otherwise, we're basically returning an integer constant.
1718
1719 // FIXME: this does the wrong thing with ptrtoint of a null pointer,
1720 // but since we don't know the original pointer type, there's not much
1721 // we can do about it.
1722
1723 auto C = getOffset();
1724 C = llvm::ConstantExpr::getIntegerCast(C, destTy, /*isSigned*/ false);
1725 return C;
1726}
1727
1728ConstantLValue
1729ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1730 // Handle values.
1731 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1732 if (D->hasAttr<WeakRefAttr>())
1733 return CGM.GetWeakRefReference(D).getPointer();
1734
1735 if (auto FD = dyn_cast<FunctionDecl>(D))
1736 return CGM.GetAddrOfFunction(FD);
1737
1738 if (auto VD = dyn_cast<VarDecl>(D)) {
1739 // We can never refer to a variable with local storage.
1740 if (!VD->hasLocalStorage()) {
1741 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1742 return CGM.GetAddrOfGlobalVar(VD);
1743
1744 if (VD->isLocalVarDecl()) {
1745 return CGM.getOrCreateStaticVarDecl(
1746 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1747 }
1748 }
1749 }
1750
1751 return nullptr;
1752 }
1753
1754 // Otherwise, it must be an expression.
1755 return Visit(base.get<const Expr*>());
1756}
1757
1758ConstantLValue
Bill Wendling8003edc2018-11-09 00:41:36 +00001759ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1760 return Visit(E->getSubExpr());
1761}
1762
1763ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001764ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1765 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1766}
1767
1768ConstantLValue
1769ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1770 return CGM.GetAddrOfConstantStringFromLiteral(E);
1771}
1772
1773ConstantLValue
1774ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1775 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1776}
1777
1778ConstantLValue
1779ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1780 auto C = CGM.getObjCRuntime().GenerateConstantString(E->getString());
1781 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(E->getType()));
1782}
1783
1784ConstantLValue
1785ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
Eli Friedman3f82f9e2019-01-22 00:11:17 +00001786 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
John McCall99e5e982017-08-17 05:03:55 +00001787}
1788
1789ConstantLValue
1790ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1791 assert(Emitter.CGF && "Invalid address of label expression outside function");
1792 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1793 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1794 CGM.getTypes().ConvertType(E->getType()));
1795 return Ptr;
1796}
1797
1798ConstantLValue
1799ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1800 unsigned builtin = E->getBuiltinCallee();
1801 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1802 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1803 return nullptr;
1804
1805 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1806 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1807 return CGM.getObjCRuntime().GenerateConstantString(literal);
1808 } else {
1809 // FIXME: need to deal with UCN conversion issues.
1810 return CGM.GetAddrOfConstantCFString(literal);
1811 }
1812}
1813
1814ConstantLValue
1815ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1816 StringRef functionName;
1817 if (auto CGF = Emitter.CGF)
1818 functionName = CGF->CurFn->getName();
1819 else
1820 functionName = "global";
1821
1822 return CGM.GetAddrOfGlobalBlock(E, functionName);
1823}
1824
1825ConstantLValue
1826ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1827 QualType T;
1828 if (E->isTypeOperand())
1829 T = E->getTypeOperand(CGM.getContext());
1830 else
1831 T = E->getExprOperand()->getType();
1832 return CGM.GetAddrOfRTTIDescriptor(T);
1833}
1834
1835ConstantLValue
1836ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1837 return CGM.GetAddrOfUuidDescriptor(E);
1838}
1839
1840ConstantLValue
1841ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1842 const MaterializeTemporaryExpr *E) {
1843 assert(E->getStorageDuration() == SD_Static);
1844 SmallVector<const Expr *, 2> CommaLHSs;
1845 SmallVector<SubobjectAdjustment, 2> Adjustments;
1846 const Expr *Inner = E->GetTemporaryExpr()
1847 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1848 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1849}
1850
John McCallde0fe072017-08-15 21:42:52 +00001851llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1852 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00001853 switch (Value.getKind()) {
1854 case APValue::Uninitialized:
1855 llvm_unreachable("Constant expressions should be initialized.");
John McCall99e5e982017-08-17 05:03:55 +00001856 case APValue::LValue:
1857 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00001858 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00001859 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Leonard Chan86285d22019-01-16 18:53:05 +00001860 case APValue::FixedPoint:
1861 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1862 Value.getFixedPoint().getValue());
Richard Smithdafff942012-01-14 04:30:29 +00001863 case APValue::ComplexInt: {
1864 llvm::Constant *Complex[2];
1865
John McCallde0fe072017-08-15 21:42:52 +00001866 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001867 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00001868 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001869 Value.getComplexIntImag());
1870
1871 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00001872 llvm::StructType *STy =
1873 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00001874 return llvm::ConstantStruct::get(STy, Complex);
1875 }
1876 case APValue::Float: {
1877 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001878 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00001879 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00001880 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00001881 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1882 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00001883 else
John McCallde0fe072017-08-15 21:42:52 +00001884 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00001885 }
1886 case APValue::ComplexFloat: {
1887 llvm::Constant *Complex[2];
1888
John McCallde0fe072017-08-15 21:42:52 +00001889 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001890 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00001891 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001892 Value.getComplexFloatImag());
1893
1894 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00001895 llvm::StructType *STy =
1896 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00001897 return llvm::ConstantStruct::get(STy, Complex);
1898 }
1899 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00001900 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00001901 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00001902
George Burgess IV533ff002015-12-11 00:23:35 +00001903 for (unsigned I = 0; I != NumElts; ++I) {
1904 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00001905 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00001906 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00001907 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00001908 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00001909 else
George Burgess IV533ff002015-12-11 00:23:35 +00001910 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00001911 }
1912 return llvm::ConstantVector::get(Inits);
1913 }
1914 case APValue::AddrLabelDiff: {
1915 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1916 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00001917 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1918 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1919 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00001920
1921 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00001922 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1923 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1924 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00001925 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1926
1927 // LLVM is a bit sensitive about the exact format of the
1928 // address-of-label difference; make sure to truncate after
1929 // the subtraction.
1930 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1931 }
1932 case APValue::Struct:
1933 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00001934 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001935 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00001936 const ConstantArrayType *CAT =
1937 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001938 unsigned NumElements = Value.getArraySize();
1939 unsigned NumInitElts = Value.getArrayInitializedElts();
1940
Richard Smithdafff942012-01-14 04:30:29 +00001941 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00001942 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001943 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001944 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1945 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00001946 if (!Filler)
1947 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00001948 }
David Majnemer90d85442014-12-28 23:46:59 +00001949
Richard Smith3e268632018-05-23 23:41:38 +00001950 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001951 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001952 if (Filler && Filler->isNullValue())
1953 Elts.reserve(NumInitElts + 1);
1954 else
1955 Elts.reserve(NumElements);
1956
1957 llvm::Type *CommonElementType = nullptr;
1958 for (unsigned I = 0; I < NumInitElts; ++I) {
1959 llvm::Constant *C = tryEmitPrivateForMemory(
1960 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00001961 if (!C) return nullptr;
1962
Richard Smithdafff942012-01-14 04:30:29 +00001963 if (I == 0)
1964 CommonElementType = C->getType();
1965 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00001966 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00001967 Elts.push_back(C);
1968 }
1969
Balaji V. Iyer749e8282018-08-08 00:01:21 +00001970 // This means that the array type is probably "IncompleteType" or some
1971 // type that is not ConstantArray.
1972 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1973 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1974 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1975 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1976 NumElements);
1977 return llvm::ConstantAggregateZero::get(AType);
1978 }
1979
Richard Smith3e268632018-05-23 23:41:38 +00001980 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1981 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00001982 }
1983 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001984 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001985 }
1986 llvm_unreachable("Unknown APValue kind");
1987}
1988
George Burgess IV1a39b862016-12-28 07:27:40 +00001989llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
1990 const CompoundLiteralExpr *E) {
1991 return EmittedCompoundLiterals.lookup(E);
1992}
1993
1994void CodeGenModule::setAddrOfConstantCompoundLiteral(
1995 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
1996 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
1997 (void)Ok;
1998 assert(Ok && "CLE has already been emitted!");
1999}
2000
John McCall7f416cc2015-09-08 08:05:57 +00002001ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002002CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2003 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002004 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002005}
2006
John McCallf3a88602011-02-03 08:15:49 +00002007llvm::Constant *
2008CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2009 // Member pointer constants always have a very particular form.
2010 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2011 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2012
2013 // A member function pointer.
2014 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002015 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002016
2017 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002018 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002019 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2020 return getCXXABI().EmitMemberDataPointer(type, chars);
2021}
2022
John McCall0217dfc22011-02-15 06:40:56 +00002023static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002024 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002025 const CXXRecordDecl *base);
2026
Anders Carlsson849ea412010-11-22 18:42:14 +00002027static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002028 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002029 bool asCompleteObject) {
2030 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002031 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002032 (asCompleteObject ? layout.getLLVMType()
2033 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002034
John McCall0217dfc22011-02-15 06:40:56 +00002035 unsigned numElements = structure->getNumElements();
2036 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002037
Yaxun Liu402804b2016-12-15 08:09:08 +00002038 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002039 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002040 if (CXXR) {
2041 for (const auto &I : CXXR->bases()) {
2042 if (I.isVirtual()) {
2043 // Ignore virtual bases; if we're laying out for a complete
2044 // object, we'll lay these out later.
2045 continue;
2046 }
2047
2048 const CXXRecordDecl *base =
2049 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2050
2051 // Ignore empty bases.
2052 if (base->isEmpty() ||
2053 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2054 .isZero())
2055 continue;
2056
2057 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2058 llvm::Type *baseType = structure->getElementType(fieldIndex);
2059 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002060 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002061 }
2062
John McCall0217dfc22011-02-15 06:40:56 +00002063 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002064 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002065 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2066 // will fill in later.)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002067 if (!Field->isBitField()) {
2068 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2069 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002070 }
2071
2072 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002073 if (record->isUnion()) {
2074 if (Field->getIdentifier())
2075 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002076 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002077 if (FieldRD->findFirstNamedDataMember())
2078 break;
2079 }
John McCall0217dfc22011-02-15 06:40:56 +00002080 }
2081
2082 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002083 if (CXXR && asCompleteObject) {
2084 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002085 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002086 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002087
2088 // Ignore empty bases.
2089 if (base->isEmpty())
2090 continue;
2091
2092 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2093
2094 // We might have already laid this field out.
2095 if (elements[fieldIndex]) continue;
2096
Chris Lattner2192fe52011-07-18 04:24:23 +00002097 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002098 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2099 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002100 }
2101
2102 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002103 for (unsigned i = 0; i != numElements; ++i) {
2104 if (!elements[i])
2105 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002106 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002107
John McCall0217dfc22011-02-15 06:40:56 +00002108 return llvm::ConstantStruct::get(structure, elements);
2109}
2110
2111/// Emit the null constant for a base subobject.
2112static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002113 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002114 const CXXRecordDecl *base) {
2115 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2116
2117 // Just zero out bases that don't have any pointer to data members.
2118 if (baseLayout.isZeroInitializableAsBase())
2119 return llvm::Constant::getNullValue(baseType);
2120
David Majnemer2213bfe2014-10-17 01:00:43 +00002121 // Otherwise, we can just use its null constant.
2122 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002123}
2124
John McCallde0fe072017-08-15 21:42:52 +00002125llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2126 QualType T) {
2127 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2128}
2129
Eli Friedman20bb5e02009-04-13 21:47:26 +00002130llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002131 if (T->getAs<PointerType>())
2132 return getNullPointer(
2133 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2134
John McCall614dbdc2010-08-22 21:01:12 +00002135 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002136 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002137
Anders Carlssonf48123b2009-08-09 18:26:27 +00002138 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002139 llvm::ArrayType *ATy =
2140 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002141
Anders Carlssonf48123b2009-08-09 18:26:27 +00002142 QualType ElementTy = CAT->getElementType();
2143
John McCallde0fe072017-08-15 21:42:52 +00002144 llvm::Constant *Element =
2145 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002146 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002147 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002148 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002149 }
Anders Carlssond606de72009-08-23 01:25:01 +00002150
Yaxun Liu402804b2016-12-15 08:09:08 +00002151 if (const RecordType *RT = T->getAs<RecordType>())
2152 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002153
David Majnemer5fd33e02015-04-24 01:25:08 +00002154 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002155 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002156
John McCallf3a88602011-02-03 08:15:49 +00002157 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002158}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002159
2160llvm::Constant *
2161CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2162 return ::EmitNullConstant(*this, Record, false);
2163}