1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Constant Expr nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenFunction.h"
14 #include "CGCXXABI.h"
15 #include "CGObjCRuntime.h"
16 #include "CGRecordLayout.h"
17 #include "CodeGenModule.h"
18 #include "ConstantEmitter.h"
19 #include "TargetInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/Builtins.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 //===----------------------------------------------------------------------===//
33 //                            ConstStructBuilder
34 //===----------------------------------------------------------------------===//
35 
36 namespace {
37 class ConstExprEmitter;
38 class ConstStructBuilder {
39   CodeGenModule &CGM;
40   ConstantEmitter &Emitter;
41 
42   bool Packed;
43   CharUnits NextFieldOffsetInChars;
44   CharUnits LLVMStructAlignment;
45   SmallVector<llvm::Constant *, 32> Elements;
46 public:
47   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
48                                      ConstExprEmitter *ExprEmitter,
49                                      llvm::Constant *Base,
50                                      InitListExpr *Updater,
51                                      QualType ValTy);
52   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
53                                      InitListExpr *ILE, QualType StructTy);
54   static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
55                                      const APValue &Value, QualType ValTy);
56 
57 private:
58   ConstStructBuilder(ConstantEmitter &emitter)
59     : CGM(emitter.CGM), Emitter(emitter), Packed(false),
60     NextFieldOffsetInChars(CharUnits::Zero()),
61     LLVMStructAlignment(CharUnits::One()) { }
62 
63   void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
64                    llvm::Constant *InitExpr);
65 
66   void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
67 
68   void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
69                       llvm::ConstantInt *InitExpr);
70 
71   void AppendPadding(CharUnits PadSize);
72 
73   void AppendTailPadding(CharUnits RecordSize);
74 
75   void ConvertStructToPacked();
76 
77   bool Build(InitListExpr *ILE);
78   bool Build(ConstExprEmitter *Emitter, llvm::Constant *Base,
79              InitListExpr *Updater);
80   bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
81              const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
82   llvm::Constant *Finalize(QualType Ty);
83 
84   CharUnits getAlignment(const llvm::Constant *C) const {
85     if (Packed)  return CharUnits::One();
86     return CharUnits::fromQuantity(
87         CGM.getDataLayout().getABITypeAlignment(C->getType()));
88   }
89 
90   CharUnits getSizeInChars(const llvm::Constant *C) const {
91     return CharUnits::fromQuantity(
92         CGM.getDataLayout().getTypeAllocSize(C->getType()));
93   }
94 };
95 
96 void ConstStructBuilder::
97 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
98             llvm::Constant *InitCst) {
99   const ASTContext &Context = CGM.getContext();
100 
101   CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
102 
103   AppendBytes(FieldOffsetInChars, InitCst);
104 }
105 
106 void ConstStructBuilder::
107 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
108 
109   assert(NextFieldOffsetInChars <= FieldOffsetInChars
110          && "Field offset mismatch!");
111 
112   CharUnits FieldAlignment = getAlignment(InitCst);
113 
114   // Round up the field offset to the alignment of the field type.
115   CharUnits AlignedNextFieldOffsetInChars =
116       NextFieldOffsetInChars.alignTo(FieldAlignment);
117 
118   if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
119     // We need to append padding.
120     AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
121 
122     assert(NextFieldOffsetInChars == FieldOffsetInChars &&
123            "Did not add enough padding!");
124 
125     AlignedNextFieldOffsetInChars =
126         NextFieldOffsetInChars.alignTo(FieldAlignment);
127   }
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     }
143     AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
144   }
145 
146   // Add the field.
147   Elements.push_back(InitCst);
148   NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
149                            getSizeInChars(InitCst);
150 
151   if (Packed)
152     assert(LLVMStructAlignment == CharUnits::One() &&
153            "Packed struct not byte-aligned!");
154   else
155     LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
156 }
157 
158 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
159                                         uint64_t FieldOffset,
160                                         llvm::ConstantInt *CI) {
161   const ASTContext &Context = CGM.getContext();
162   const uint64_t CharWidth = Context.getCharWidth();
163   uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
164   if (FieldOffset > NextFieldOffsetInBits) {
165     // We need to add padding.
166     CharUnits PadSize = Context.toCharUnitsFromBits(
167         llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
168                       Context.getTargetInfo().getCharAlign()));
169 
170     AppendPadding(PadSize);
171   }
172 
173   uint64_t FieldSize = Field->getBitWidthValue(Context);
174 
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())
182     FieldValue = FieldValue.zext(FieldSize);
183 
184   // Truncate the size of FieldValue to the bit field size.
185   if (FieldSize < FieldValue.getBitWidth())
186     FieldValue = FieldValue.trunc(FieldSize);
187 
188   NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
189   if (FieldOffset < NextFieldOffsetInBits) {
190     // 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 
194     unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
195 
196     bool FitsCompletelyInPreviousByte =
197       BitsInPreviousByte >= FieldValue.getBitWidth();
198 
199     llvm::APInt Tmp = FieldValue;
200 
201     if (!FitsCompletelyInPreviousByte) {
202       unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
203 
204       if (CGM.getDataLayout().isBigEndian()) {
205         Tmp.lshrInPlace(NewFieldWidth);
206         Tmp = Tmp.trunc(BitsInPreviousByte);
207 
208         // We want the remaining high bits.
209         FieldValue = FieldValue.trunc(NewFieldWidth);
210       } else {
211         Tmp = Tmp.trunc(BitsInPreviousByte);
212 
213         // We want the remaining low bits.
214         FieldValue.lshrInPlace(BitsInPreviousByte);
215         FieldValue = FieldValue.trunc(NewFieldWidth);
216       }
217     }
218 
219     Tmp = Tmp.zext(CharWidth);
220     if (CGM.getDataLayout().isBigEndian()) {
221       if (FitsCompletelyInPreviousByte)
222         Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
223     } else {
224       Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
225     }
226 
227     // '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))
230       Tmp |= Val->getValue();
231     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");
242         llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
243         assert(AT->getElementType()->isIntegerTy(CharWidth) &&
244                AT->getNumElements() != 0 &&
245                "Expected non-empty array padding of undefs");
246 
247         // Remove the padding array.
248         NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
249         Elements.pop_back();
250 
251         // Add the padding back in two chunks.
252         AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
253         AppendPadding(CharUnits::One());
254         assert(isa<llvm::UndefValue>(Elements.back()) &&
255                Elements.back()->getType()->isIntegerTy(CharWidth) &&
256                "Padding addition didn't work right");
257       }
258     }
259 
260     Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
261 
262     if (FitsCompletelyInPreviousByte)
263       return;
264   }
265 
266   while (FieldValue.getBitWidth() > CharWidth) {
267     llvm::APInt Tmp;
268 
269     if (CGM.getDataLayout().isBigEndian()) {
270       // We want the high bits.
271       Tmp =
272         FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
273     } else {
274       // We want the low bits.
275       Tmp = FieldValue.trunc(CharWidth);
276 
277       FieldValue.lshrInPlace(CharWidth);
278     }
279 
280     Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
281     ++NextFieldOffsetInChars;
282 
283     FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
284   }
285 
286   assert(FieldValue.getBitWidth() > 0 &&
287          "Should have at least one bit left!");
288   assert(FieldValue.getBitWidth() <= CharWidth &&
289          "Should not have more than a byte left!");
290 
291   if (FieldValue.getBitWidth() < CharWidth) {
292     if (CGM.getDataLayout().isBigEndian()) {
293       unsigned BitWidth = FieldValue.getBitWidth();
294 
295       FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
296     } else
297       FieldValue = FieldValue.zext(CharWidth);
298   }
299 
300   // Append the last element.
301   Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
302                                             FieldValue));
303   ++NextFieldOffsetInChars;
304 }
305 
306 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
307   if (PadSize.isZero())
308     return;
309 
310   llvm::Type *Ty = CGM.Int8Ty;
311   if (PadSize > CharUnits::One())
312     Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
313 
314   llvm::Constant *C = llvm::UndefValue::get(Ty);
315   Elements.push_back(C);
316   assert(getAlignment(C) == CharUnits::One() &&
317          "Padding must have 1 byte alignment!");
318 
319   NextFieldOffsetInChars += getSizeInChars(C);
320 }
321 
322 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
323   assert(NextFieldOffsetInChars <= RecordSize &&
324          "Size mismatch!");
325 
326   AppendPadding(RecordSize - NextFieldOffsetInChars);
327 }
328 
329 void ConstStructBuilder::ConvertStructToPacked() {
330   SmallVector<llvm::Constant *, 16> PackedElements;
331   CharUnits ElementOffsetInChars = CharUnits::Zero();
332 
333   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
334     llvm::Constant *C = Elements[i];
335 
336     CharUnits ElementAlign = CharUnits::fromQuantity(
337       CGM.getDataLayout().getABITypeAlignment(C->getType()));
338     CharUnits AlignedElementOffsetInChars =
339         ElementOffsetInChars.alignTo(ElementAlign);
340 
341     if (AlignedElementOffsetInChars > ElementOffsetInChars) {
342       // We need some padding.
343       CharUnits NumChars =
344         AlignedElementOffsetInChars - ElementOffsetInChars;
345 
346       llvm::Type *Ty = CGM.Int8Ty;
347       if (NumChars > CharUnits::One())
348         Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
349 
350       llvm::Constant *Padding = llvm::UndefValue::get(Ty);
351       PackedElements.push_back(Padding);
352       ElementOffsetInChars += getSizeInChars(Padding);
353     }
354 
355     PackedElements.push_back(C);
356     ElementOffsetInChars += getSizeInChars(C);
357   }
358 
359   assert(ElementOffsetInChars == NextFieldOffsetInChars &&
360          "Packing the struct changed its size!");
361 
362   Elements.swap(PackedElements);
363   LLVMStructAlignment = CharUnits::One();
364   Packed = true;
365 }
366 
367 bool 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;
373 
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 
381   for (RecordDecl::field_iterator Field = RD->field_begin(),
382        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
383     // If this is a union, skip all the fields that aren't being initialized.
384     if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
385       continue;
386 
387     // Don't emit anonymous bitfields, they just affect layout.
388     if (Field->isUnnamedBitfield())
389       continue;
390 
391     // 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())
395       EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
396                                                 Field->getType());
397     else
398       EltInit = Emitter.emitNullForMemory(Field->getType());
399 
400     if (!EltInit)
401       return false;
402 
403     if (!Field->isBitField()) {
404       // Handle non-bitfield members.
405       AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
406     } else {
407       // Otherwise we have a bitfield.
408       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       }
415     }
416   }
417 
418   return true;
419 }
420 
421 namespace {
422 struct 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 };
433 }
434 
435 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
436                                bool IsPrimaryBase,
437                                const CXXRecordDecl *VTableClass,
438                                CharUnits Offset) {
439   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
440 
441   if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
442     // Add a vtable pointer, if we need one and it hasn't already been added.
443     if (CD->isDynamicClass() && !IsPrimaryBase) {
444       llvm::Constant *VTableAddressPoint =
445           CGM.getCXXABI().getVTableAddressPointForConstExpr(
446               BaseSubobject(CD, Offset), VTableClass);
447       AppendBytes(Offset, VTableAddressPoint);
448     }
449 
450     // Accumulate and sort bases, in order to visit them in address order, which
451     // may not be the same as declaration order.
452     SmallVector<BaseInfo, 8> Bases;
453     Bases.reserve(CD->getNumBases());
454     unsigned BaseNo = 0;
455     for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
456          BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
457       assert(!Base->isVirtual() && "should not have virtual bases here");
458       const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
459       CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
460       Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
461     }
462     std::stable_sort(Bases.begin(), Bases.end());
463 
464     for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
465       BaseInfo &Base = Bases[I];
466 
467       bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
468       Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
469             VTableClass, Offset + Base.Offset);
470     }
471   }
472 
473   unsigned FieldNo = 0;
474   uint64_t OffsetBits = CGM.getContext().toBits(Offset);
475 
476   for (RecordDecl::field_iterator Field = RD->field_begin(),
477        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
478     // If this is a union, skip all the fields that aren't being initialized.
479     if (RD->isUnion() && Val.getUnionField() != *Field)
480       continue;
481 
482     // Don't emit anonymous bitfields, they just affect layout.
483     if (Field->isUnnamedBitfield())
484       continue;
485 
486     // Emit the value of the initializer.
487     const APValue &FieldValue =
488       RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
489     llvm::Constant *EltInit =
490       Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
491     if (!EltInit)
492       return false;
493 
494     if (!Field->isBitField()) {
495       // Handle non-bitfield members.
496       AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
497     } else {
498       // Otherwise we have a bitfield.
499       AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
500                      cast<llvm::ConstantInt>(EltInit));
501     }
502   }
503 
504   return true;
505 }
506 
507 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
508   RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
509   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
510 
511   CharUnits LayoutSizeInChars = Layout.getSize();
512 
513   if (NextFieldOffsetInChars > LayoutSizeInChars) {
514     // 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!");
518 
519     // No tail padding is necessary.
520   } else {
521     // Append tail padding if necessary.
522     CharUnits LLVMSizeInChars =
523         NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
524 
525     if (LLVMSizeInChars != LayoutSizeInChars)
526       AppendTailPadding(LayoutSizeInChars);
527 
528     LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
529 
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 
540     LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
541 
542     assert(LayoutSizeInChars == LLVMSizeInChars &&
543            "Tail padding mismatch!");
544   }
545 
546   // 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.
548   llvm::StructType *STy =
549       llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
550                                                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;
555   }
556 
557   llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
558 
559   assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
560              getSizeInChars(Result) &&
561          "Size mismatch!");
562 
563   return Result;
564 }
565 
566 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
567                                                 ConstExprEmitter *ExprEmitter,
568                                                 llvm::Constant *Base,
569                                                 InitListExpr *Updater,
570                                                 QualType ValTy) {
571   ConstStructBuilder Builder(Emitter);
572   if (!Builder.Build(ExprEmitter, Base, Updater))
573     return nullptr;
574   return Builder.Finalize(ValTy);
575 }
576 
577 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
578                                                 InitListExpr *ILE,
579                                                 QualType ValTy) {
580   ConstStructBuilder Builder(Emitter);
581 
582   if (!Builder.Build(ILE))
583     return nullptr;
584 
585   return Builder.Finalize(ValTy);
586 }
587 
588 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
589                                                 const APValue &Val,
590                                                 QualType ValTy) {
591   ConstStructBuilder Builder(Emitter);
592 
593   const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
594   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
595   if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
596     return nullptr;
597 
598   return Builder.Finalize(ValTy);
599 }
600 
601 
602 //===----------------------------------------------------------------------===//
603 //                             ConstExprEmitter
604 //===----------------------------------------------------------------------===//
605 
606 static 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 
614   LangAS addressSpace = E->getType().getAddressSpace();
615 
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 
637 static llvm::Constant *
638 EmitArrayConstant(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");
661 
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(
666           llvm::ArrayType::get(CommonElementType, NonzeroLength),
667           makeArrayRef(Elements).take_front(NonzeroLength));
668       Elements.resize(2);
669       Elements[0] = Initial;
670     } else {
671       Elements.resize(NonzeroLength + 1);
672     }
673 
674     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 
703 // 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.
709 class ConstExprEmitter :
710   public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
711   CodeGenModule &CGM;
712   ConstantEmitter &Emitter;
713   llvm::LLVMContext &VMContext;
714 public:
715   ConstExprEmitter(ConstantEmitter &emitter)
716     : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
717   }
718 
719   //===--------------------------------------------------------------------===//
720   //                            Visitor Methods
721   //===--------------------------------------------------------------------===//
722 
723   llvm::Constant *VisitStmt(Stmt *S, QualType T) {
724     return nullptr;
725   }
726 
727   llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
728     return Visit(CE->getSubExpr(), T);
729   }
730 
731   llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
732     return Visit(PE->getSubExpr(), T);
733   }
734 
735   llvm::Constant *
736   VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
737                                     QualType T) {
738     return Visit(PE->getReplacement(), T);
739   }
740 
741   llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
742                                             QualType T) {
743     return Visit(GE->getResultExpr(), T);
744   }
745 
746   llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
747     return Visit(CE->getChosenSubExpr(), T);
748   }
749 
750   llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
751     return Visit(E->getInitializer(), T);
752   }
753 
754   llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
755     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
756       CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
757     Expr *subExpr = E->getSubExpr();
758 
759     switch (E->getCastKind()) {
760     case CK_ToUnion: {
761       // GCC cast to union extension
762       assert(E->getType()->isUnionType() &&
763              "Destination type is not union type!");
764 
765       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 
773       // Build a struct with the union sub-element as the first member,
774       // and padded to the appropriate size.
775       SmallVector<llvm::Constant*, 2> Elts;
776       SmallVector<llvm::Type*, 2> Types;
777       Elts.push_back(C);
778       Types.push_back(C->getType());
779       unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
780       unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
781 
782       assert(CurSize <= TotalSize && "Union size mismatch!");
783       if (unsigned NumPadBytes = TotalSize - CurSize) {
784         llvm::Type *Ty = CGM.Int8Ty;
785         if (NumPadBytes > 1)
786           Ty = llvm::ArrayType::get(Ty, NumPadBytes);
787 
788         Elts.push_back(llvm::UndefValue::get(Ty));
789         Types.push_back(Ty);
790       }
791 
792       llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
793       return llvm::ConstantStruct::get(STy, Elts);
794     }
795 
796     case CK_AddressSpaceConversion: {
797       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
798       if (!C) return nullptr;
799       LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
800       LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
801       llvm::Type *destTy = ConvertType(E->getType());
802       return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
803                                                              destAS, destTy);
804     }
805 
806     case CK_LValueToRValue:
807     case CK_AtomicToNonAtomic:
808     case CK_NonAtomicToAtomic:
809     case CK_NoOp:
810     case CK_ConstructorConversion:
811       return Visit(subExpr, destType);
812 
813     case CK_IntToOCLSampler:
814       llvm_unreachable("global sampler variables are not generated");
815 
816     case CK_Dependent: llvm_unreachable("saw dependent cast!");
817 
818     case CK_BuiltinFnToFnPtr:
819       llvm_unreachable("builtin functions are handled elsewhere");
820 
821     case CK_ReinterpretMemberPointer:
822     case CK_DerivedToBaseMemberPointer:
823     case CK_BaseToDerivedMemberPointer: {
824       auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
825       if (!C) return nullptr;
826       return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
827     }
828 
829     // These will never be supported.
830     case CK_ObjCObjectLValueCast:
831     case CK_ARCProduceObject:
832     case CK_ARCConsumeObject:
833     case CK_ARCReclaimReturnedObject:
834     case CK_ARCExtendBlockObject:
835     case CK_CopyAndAutoreleaseBlockObject:
836       return nullptr;
837 
838     // These don't need to be handled here because Evaluate knows how to
839     // evaluate them in the cases where they can be folded.
840     case CK_BitCast:
841     case CK_ToVoid:
842     case CK_Dynamic:
843     case CK_LValueBitCast:
844     case CK_NullToMemberPointer:
845     case CK_UserDefinedConversion:
846     case CK_CPointerToObjCPointerCast:
847     case CK_BlockPointerToObjCPointerCast:
848     case CK_AnyPointerToBlockPointerCast:
849     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:
866     case CK_PointerToIntegral:
867     case CK_PointerToBoolean:
868     case CK_NullToPointer:
869     case CK_IntegralCast:
870     case CK_BooleanToSignedIntegral:
871     case CK_IntegralToPointer:
872     case CK_IntegralToBoolean:
873     case CK_IntegralToFloating:
874     case CK_FloatingToIntegral:
875     case CK_FloatingToBoolean:
876     case CK_FloatingCast:
877     case CK_FixedPointCast:
878     case CK_FixedPointToBoolean:
879     case CK_FixedPointToIntegral:
880     case CK_IntegralToFixedPoint:
881     case CK_ZeroToOCLOpaqueType:
882       return nullptr;
883     }
884     llvm_unreachable("Invalid CastKind");
885   }
886 
887   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
888     return Visit(DAE->getExpr(), T);
889   }
890 
891   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
892     // No need for a DefaultInitExprScope: we don't handle 'this' in a
893     // constant expression.
894     return Visit(DIE->getExpr(), T);
895   }
896 
897   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
898     if (!E->cleanupsHaveSideEffects())
899       return Visit(E->getSubExpr(), T);
900     return nullptr;
901   }
902 
903   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
904                                                 QualType T) {
905     return Visit(E->GetTemporaryExpr(), T);
906   }
907 
908   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
909     auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
910     assert(CAT && "can't emit array init for non-constant-bound array");
911     unsigned NumInitElements = ILE->getNumInits();
912     unsigned NumElements = CAT->getSize().getZExtValue();
913 
914     // Initialising an array requires us to automatically
915     // initialise any elements that have not been initialised explicitly
916     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
917 
918     QualType EltType = CAT->getElementType();
919 
920     // Initialize remaining array elements.
921     llvm::Constant *fillC = nullptr;
922     if (Expr *filler = ILE->getArrayFiller()) {
923       fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
924       if (!fillC)
925         return nullptr;
926     }
927 
928     // Copy initializer elements.
929     SmallVector<llvm::Constant*, 16> Elts;
930     if (fillC && fillC->isNullValue())
931       Elts.reserve(NumInitableElts + 1);
932     else
933       Elts.reserve(NumElements);
934 
935     llvm::Type *CommonElementType = nullptr;
936     for (unsigned i = 0; i < NumInitableElts; ++i) {
937       Expr *Init = ILE->getInit(i);
938       llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
939       if (!C)
940         return nullptr;
941       if (i == 0)
942         CommonElementType = C->getType();
943       else if (C->getType() != CommonElementType)
944         CommonElementType = nullptr;
945       Elts.push_back(C);
946     }
947 
948     return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
949                              fillC);
950   }
951 
952   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
953     return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
954   }
955 
956   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
957                                              QualType T) {
958     return CGM.EmitNullConstant(T);
959   }
960 
961   llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
962     if (ILE->isTransparent())
963       return Visit(ILE->getInit(0), T);
964 
965     if (ILE->getType()->isArrayType())
966       return EmitArrayInitialization(ILE, T);
967 
968     if (ILE->getType()->isRecordType())
969       return EmitRecordInitialization(ILE, T);
970 
971     return nullptr;
972   }
973 
974   llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
975                                             InitListExpr *Updater,
976                                             QualType destType) {
977     if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
978       llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
979       llvm::Type *ElemType = AType->getElementType();
980 
981       unsigned NumInitElements = Updater->getNumInits();
982       unsigned NumElements = AType->getNumElements();
983 
984       std::vector<llvm::Constant *> Elts;
985       Elts.reserve(NumElements);
986 
987       QualType destElemType = destAT->getElementType();
988 
989       if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
990         for (unsigned i = 0; i != NumElements; ++i)
991           Elts.push_back(DataArray->getElementAsConstant(i));
992       else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
993         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))
1001           fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
1002       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))
1014           Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1015         else
1016           Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
1017 
1018        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 
1036     if (destType->isRecordType())
1037       return ConstStructBuilder::BuildStruct(Emitter, this, Base, Updater,
1038                                              destType);
1039 
1040     return nullptr;
1041   }
1042 
1043   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);
1048   }
1049 
1050   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1051     if (!E->getConstructor()->isTrivial())
1052       return nullptr;
1053 
1054     // FIXME: We should not have to call getBaseElementType here.
1055     const RecordType *RT =
1056       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1057     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1058 
1059     // If the class doesn't have a trivial destructor, we can't emit it as a
1060     // constant expr.
1061     if (!RD->hasTrivialDestructor())
1062       return nullptr;
1063 
1064     // Only copy and default constructors can be trivial.
1065 
1066 
1067     if (E->getNumArgs()) {
1068       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1069       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1070              "trivial ctor has argument but isn't a copy/move ctor");
1071 
1072       Expr *Arg = E->getArg(0);
1073       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1074              "argument to copy ctor is of wrong type");
1075 
1076       return Visit(Arg, Ty);
1077     }
1078 
1079     return CGM.EmitNullConstant(Ty);
1080   }
1081 
1082   llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1083     // This is a string literal initializing an array in an initializer.
1084     return CGM.GetConstantArrayFromStringLiteral(E);
1085   }
1086 
1087   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1088     // 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);
1093     const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1094 
1095     // Resize the string to the right size, adding zeros at the end, or
1096     // truncating as needed.
1097     Str.resize(CAT->getSize().getZExtValue(), '\0');
1098     return llvm::ConstantDataArray::getString(VMContext, Str, false);
1099   }
1100 
1101   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1102     return Visit(E->getSubExpr(), T);
1103   }
1104 
1105   // Utility methods
1106   llvm::Type *ConvertType(QualType T) {
1107     return CGM.getTypes().ConvertType(T);
1108   }
1109 };
1110 
1111 }  // end anonymous namespace.
1112 
1113 bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1114                                llvm::Constant *Base,
1115                                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(
1122       cast<llvm::StructType>(Base->getType()));
1123   unsigned FieldNo = -1;
1124   unsigned ElementNo = 0;
1125 
1126   // 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 
1133   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 
1143     llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
1144 
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))
1161       EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1162                                                        Field->getType());
1163     else
1164       EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
1165 
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 
1183 llvm::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 
1195 llvm::Constant *
1196 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1197   auto state = pushAbstract();
1198   auto C = tryEmitPrivateForVarInit(D);
1199   return validateAndPopAbstract(C, state);
1200 }
1201 
1202 llvm::Constant *
1203 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1204   auto state = pushAbstract();
1205   auto C = tryEmitPrivate(E, destType);
1206   return validateAndPopAbstract(C, state);
1207 }
1208 
1209 llvm::Constant *
1210 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1211   auto state = pushAbstract();
1212   auto C = tryEmitPrivate(value, destType);
1213   return validateAndPopAbstract(C, state);
1214 }
1215 
1216 llvm::Constant *
1217 ConstantEmitter::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 
1229 llvm::Constant *
1230 ConstantEmitter::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 
1243 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1244   initializeNonAbstract(D.getType().getAddressSpace());
1245   return markIfFailed(tryEmitPrivateForVarInit(D));
1246 }
1247 
1248 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1249                                                        LangAS destAddrSpace,
1250                                                        QualType destType) {
1251   initializeNonAbstract(destAddrSpace);
1252   return markIfFailed(tryEmitPrivateForMemory(E, destType));
1253 }
1254 
1255 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1256                                                     LangAS destAddrSpace,
1257                                                     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 
1264 llvm::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 
1284 void 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 
1292 namespace {
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 
1419 void 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 
1435 ConstantEmitter::~ConstantEmitter() {
1436   assert((!InitializedNonAbstract || Finalized || Failed) &&
1437          "not finalized after being initialized for non-abstract emission");
1438   assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1439 }
1440 
1441 static 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 
1449 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1450   // 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.
1453   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       }
1462     InConstantContext = true;
1463   }
1464 
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   }
1472 
1473   // 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.
1479   if (destType->isReferenceType())
1480     return nullptr;
1481 
1482   const Expr *E = D.getInit();
1483   assert(E && "No initializer to emit");
1484 
1485   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 
1491 llvm::Constant *
1492 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1493   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1494   auto C = tryEmitAbstract(E, nonMemoryDestType);
1495   return (C ? emitForMemory(C, destType) : nullptr);
1496 }
1497 
1498 llvm::Constant *
1499 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1500                                           QualType destType) {
1501   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1502   auto C = tryEmitAbstract(value, nonMemoryDestType);
1503   return (C ? emitForMemory(C, destType) : nullptr);
1504 }
1505 
1506 llvm::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 
1513 llvm::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 
1520 llvm::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);
1540   }
1541 
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 
1548   return C;
1549 }
1550 
1551 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1552                                                 QualType destType) {
1553   Expr::EvalResult Result;
1554 
1555   bool Success = false;
1556 
1557   if (destType->isReferenceType())
1558     Success = E->EvaluateAsLValue(Result, CGM.getContext());
1559   else
1560     Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1561 
1562   llvm::Constant *C;
1563   if (Success && !Result.HasSideEffects)
1564     C = tryEmitPrivate(Result.Val, destType);
1565   else
1566     C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1567 
1568   return C;
1569 }
1570 
1571 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1572   return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1573 }
1574 
1575 namespace {
1576 /// A struct which can be used to peephole certain kinds of finalization
1577 /// that normally happen during l-value emission.
1578 struct 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.
1591 class 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 
1601 public:
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 
1608 private:
1609   llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1610   ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1611 
1612   ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1613   ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1614   ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1615   ConstantLValue VisitStringLiteral(const StringLiteral *E);
1616   ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1617   ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1618   ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1619   ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1620   ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1621   ConstantLValue VisitCallExpr(const CallExpr *E);
1622   ConstantLValue VisitBlockExpr(const BlockExpr *E);
1623   ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1624   ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1625   ConstantLValue VisitMaterializeTemporaryExpr(
1626                                          const MaterializeTemporaryExpr *E);
1627 
1628   bool hasNonZeroOffset() const {
1629     return !Value.getLValueOffset().isZero();
1630   }
1631 
1632   /// Return the value offset.
1633   llvm::Constant *getOffset() {
1634     return llvm::ConstantInt::get(CGM.Int64Ty,
1635                                   Value.getLValueOffset().getQuantity());
1636   }
1637 
1638   /// Apply the value offset to the given constant.
1639   llvm::Constant *applyOffset(llvm::Constant *C) {
1640     if (!hasNonZeroOffset())
1641       return C;
1642 
1643     llvm::Type *origPtrTy = C->getType();
1644     unsigned AS = origPtrTy->getPointerAddressSpace();
1645     llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1646     C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1647     C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1648     C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1649     return C;
1650   }
1651 };
1652 
1653 }
1654 
1655 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1656   const APValue::LValueBase &base = Value.getLValueBase();
1657 
1658   // The destination type should be a pointer or reference
1659   // type, but it might also be a cast thereof.
1660   //
1661   // FIXME: the chain of casts required should be reflected in the APValue.
1662   // We need this in order to correctly handle things like a ptrtoint of a
1663   // non-zero null pointer and addrspace casts that aren't trivially
1664   // represented in LLVM IR.
1665   auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1666   assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1667 
1668   // If there's no base at all, this is a null or absolute pointer,
1669   // possibly cast back to an integer type.
1670   if (!base) {
1671     return tryEmitAbsolute(destTy);
1672   }
1673 
1674   // Otherwise, try to emit the base.
1675   ConstantLValue result = tryEmitBase(base);
1676 
1677   // If that failed, we're done.
1678   llvm::Constant *value = result.Value;
1679   if (!value) return nullptr;
1680 
1681   // Apply the offset if necessary and not already done.
1682   if (!result.HasOffsetApplied) {
1683     value = applyOffset(value);
1684   }
1685 
1686   // Convert to the appropriate type; this could be an lvalue for
1687   // an integer.  FIXME: performAddrSpaceCast
1688   if (isa<llvm::PointerType>(destTy))
1689     return llvm::ConstantExpr::getPointerCast(value, destTy);
1690 
1691   return llvm::ConstantExpr::getPtrToInt(value, destTy);
1692 }
1693 
1694 /// Try to emit an absolute l-value, such as a null pointer or an integer
1695 /// bitcast to pointer type.
1696 llvm::Constant *
1697 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1698   auto offset = getOffset();
1699 
1700   // If we're producing a pointer, this is easy.
1701   auto destPtrTy = cast<llvm::PointerType>(destTy);
1702   if (Value.isNullPointer()) {
1703     // FIXME: integer offsets from non-zero null pointers.
1704     return CGM.getNullPointer(destPtrTy, DestType);
1705   }
1706 
1707   // Convert the integer to a pointer-sized integer before converting it
1708   // to a pointer.
1709   // FIXME: signedness depends on the original integer type.
1710   auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1711   llvm::Constant *C = offset;
1712   C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1713                                          /*isSigned*/ false);
1714   C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1715   return C;
1716 }
1717 
1718 ConstantLValue
1719 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1720   // Handle values.
1721   if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1722     if (D->hasAttr<WeakRefAttr>())
1723       return CGM.GetWeakRefReference(D).getPointer();
1724 
1725     if (auto FD = dyn_cast<FunctionDecl>(D))
1726       return CGM.GetAddrOfFunction(FD);
1727 
1728     if (auto VD = dyn_cast<VarDecl>(D)) {
1729       // We can never refer to a variable with local storage.
1730       if (!VD->hasLocalStorage()) {
1731         if (VD->isFileVarDecl() || VD->hasExternalStorage())
1732           return CGM.GetAddrOfGlobalVar(VD);
1733 
1734         if (VD->isLocalVarDecl()) {
1735           return CGM.getOrCreateStaticVarDecl(
1736               *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1737         }
1738       }
1739     }
1740 
1741     return nullptr;
1742   }
1743 
1744   // Otherwise, it must be an expression.
1745   return Visit(base.get<const Expr*>());
1746 }
1747 
1748 ConstantLValue
1749 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1750   return Visit(E->getSubExpr());
1751 }
1752 
1753 ConstantLValue
1754 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1755   return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1756 }
1757 
1758 ConstantLValue
1759 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1760   return CGM.GetAddrOfConstantStringFromLiteral(E);
1761 }
1762 
1763 ConstantLValue
1764 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1765   return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1766 }
1767 
1768 static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1769                                                     QualType T,
1770                                                     CodeGenModule &CGM) {
1771   auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1772   return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1773 }
1774 
1775 ConstantLValue
1776 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1777   return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1778 }
1779 
1780 ConstantLValue
1781 ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1782   assert(E->isExpressibleAsConstantInitializer() &&
1783          "this boxed expression can't be emitted as a compile-time constant");
1784   auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1785   return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
1786 }
1787 
1788 ConstantLValue
1789 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1790   return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1791 }
1792 
1793 ConstantLValue
1794 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1795   assert(Emitter.CGF && "Invalid address of label expression outside function");
1796   llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1797   Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1798                                    CGM.getTypes().ConvertType(E->getType()));
1799   return Ptr;
1800 }
1801 
1802 ConstantLValue
1803 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1804   unsigned builtin = E->getBuiltinCallee();
1805   if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1806       builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1807     return nullptr;
1808 
1809   auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1810   if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1811     return CGM.getObjCRuntime().GenerateConstantString(literal);
1812   } else {
1813     // FIXME: need to deal with UCN conversion issues.
1814     return CGM.GetAddrOfConstantCFString(literal);
1815   }
1816 }
1817 
1818 ConstantLValue
1819 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1820   StringRef functionName;
1821   if (auto CGF = Emitter.CGF)
1822     functionName = CGF->CurFn->getName();
1823   else
1824     functionName = "global";
1825 
1826   return CGM.GetAddrOfGlobalBlock(E, functionName);
1827 }
1828 
1829 ConstantLValue
1830 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1831   QualType T;
1832   if (E->isTypeOperand())
1833     T = E->getTypeOperand(CGM.getContext());
1834   else
1835     T = E->getExprOperand()->getType();
1836   return CGM.GetAddrOfRTTIDescriptor(T);
1837 }
1838 
1839 ConstantLValue
1840 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1841   return CGM.GetAddrOfUuidDescriptor(E);
1842 }
1843 
1844 ConstantLValue
1845 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1846                                             const MaterializeTemporaryExpr *E) {
1847   assert(E->getStorageDuration() == SD_Static);
1848   SmallVector<const Expr *, 2> CommaLHSs;
1849   SmallVector<SubobjectAdjustment, 2> Adjustments;
1850   const Expr *Inner = E->GetTemporaryExpr()
1851       ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1852   return CGM.GetAddrOfGlobalTemporary(E, Inner);
1853 }
1854 
1855 llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1856                                                 QualType DestType) {
1857   switch (Value.getKind()) {
1858   case APValue::Uninitialized:
1859     llvm_unreachable("Constant expressions should be initialized.");
1860   case APValue::LValue:
1861     return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
1862   case APValue::Int:
1863     return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
1864   case APValue::FixedPoint:
1865     return llvm::ConstantInt::get(CGM.getLLVMContext(),
1866                                   Value.getFixedPoint().getValue());
1867   case APValue::ComplexInt: {
1868     llvm::Constant *Complex[2];
1869 
1870     Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1871                                         Value.getComplexIntReal());
1872     Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1873                                         Value.getComplexIntImag());
1874 
1875     // FIXME: the target may want to specify that this is packed.
1876     llvm::StructType *STy =
1877         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1878     return llvm::ConstantStruct::get(STy, Complex);
1879   }
1880   case APValue::Float: {
1881     const llvm::APFloat &Init = Value.getFloat();
1882     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1883         !CGM.getContext().getLangOpts().NativeHalfType &&
1884         CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1885       return llvm::ConstantInt::get(CGM.getLLVMContext(),
1886                                     Init.bitcastToAPInt());
1887     else
1888       return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
1889   }
1890   case APValue::ComplexFloat: {
1891     llvm::Constant *Complex[2];
1892 
1893     Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1894                                        Value.getComplexFloatReal());
1895     Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1896                                        Value.getComplexFloatImag());
1897 
1898     // FIXME: the target may want to specify that this is packed.
1899     llvm::StructType *STy =
1900         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1901     return llvm::ConstantStruct::get(STy, Complex);
1902   }
1903   case APValue::Vector: {
1904     unsigned NumElts = Value.getVectorLength();
1905     SmallVector<llvm::Constant *, 4> Inits(NumElts);
1906 
1907     for (unsigned I = 0; I != NumElts; ++I) {
1908       const APValue &Elt = Value.getVectorElt(I);
1909       if (Elt.isInt())
1910         Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
1911       else if (Elt.isFloat())
1912         Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
1913       else
1914         llvm_unreachable("unsupported vector element type");
1915     }
1916     return llvm::ConstantVector::get(Inits);
1917   }
1918   case APValue::AddrLabelDiff: {
1919     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1920     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1921     llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1922     llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1923     if (!LHS || !RHS) return nullptr;
1924 
1925     // Compute difference
1926     llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1927     LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1928     RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
1929     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1930 
1931     // LLVM is a bit sensitive about the exact format of the
1932     // address-of-label difference; make sure to truncate after
1933     // the subtraction.
1934     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1935   }
1936   case APValue::Struct:
1937   case APValue::Union:
1938     return ConstStructBuilder::BuildStruct(*this, Value, DestType);
1939   case APValue::Array: {
1940     const ConstantArrayType *CAT =
1941         CGM.getContext().getAsConstantArrayType(DestType);
1942     unsigned NumElements = Value.getArraySize();
1943     unsigned NumInitElts = Value.getArrayInitializedElts();
1944 
1945     // Emit array filler, if there is one.
1946     llvm::Constant *Filler = nullptr;
1947     if (Value.hasArrayFiller()) {
1948       Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1949                                         CAT->getElementType());
1950       if (!Filler)
1951         return nullptr;
1952     }
1953 
1954     // Emit initializer elements.
1955     SmallVector<llvm::Constant*, 16> Elts;
1956     if (Filler && Filler->isNullValue())
1957       Elts.reserve(NumInitElts + 1);
1958     else
1959       Elts.reserve(NumElements);
1960 
1961     llvm::Type *CommonElementType = nullptr;
1962     for (unsigned I = 0; I < NumInitElts; ++I) {
1963       llvm::Constant *C = tryEmitPrivateForMemory(
1964           Value.getArrayInitializedElt(I), CAT->getElementType());
1965       if (!C) return nullptr;
1966 
1967       if (I == 0)
1968         CommonElementType = C->getType();
1969       else if (C->getType() != CommonElementType)
1970         CommonElementType = nullptr;
1971       Elts.push_back(C);
1972     }
1973 
1974     // This means that the array type is probably "IncompleteType" or some
1975     // type that is not ConstantArray.
1976     if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1977       const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1978       CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1979       llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1980                                                     NumElements);
1981       return llvm::ConstantAggregateZero::get(AType);
1982     }
1983 
1984     return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1985                              Filler);
1986   }
1987   case APValue::MemberPointer:
1988     return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
1989   }
1990   llvm_unreachable("Unknown APValue kind");
1991 }
1992 
1993 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
1994     const CompoundLiteralExpr *E) {
1995   return EmittedCompoundLiterals.lookup(E);
1996 }
1997 
1998 void CodeGenModule::setAddrOfConstantCompoundLiteral(
1999     const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2000   bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2001   (void)Ok;
2002   assert(Ok && "CLE has already been emitted!");
2003 }
2004 
2005 ConstantAddress
2006 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2007   assert(E->isFileScope() && "not a file-scope compound literal expr");
2008   return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2009 }
2010 
2011 llvm::Constant *
2012 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2013   // Member pointer constants always have a very particular form.
2014   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2015   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2016 
2017   // A member function pointer.
2018   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2019     return getCXXABI().EmitMemberFunctionPointer(method);
2020 
2021   // Otherwise, a member data pointer.
2022   uint64_t fieldOffset = getContext().getFieldOffset(decl);
2023   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2024   return getCXXABI().EmitMemberDataPointer(type, chars);
2025 }
2026 
2027 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2028                                                llvm::Type *baseType,
2029                                                const CXXRecordDecl *base);
2030 
2031 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2032                                         const RecordDecl *record,
2033                                         bool asCompleteObject) {
2034   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2035   llvm::StructType *structure =
2036     (asCompleteObject ? layout.getLLVMType()
2037                       : layout.getBaseSubobjectLLVMType());
2038 
2039   unsigned numElements = structure->getNumElements();
2040   std::vector<llvm::Constant *> elements(numElements);
2041 
2042   auto CXXR = dyn_cast<CXXRecordDecl>(record);
2043   // Fill in all the bases.
2044   if (CXXR) {
2045     for (const auto &I : CXXR->bases()) {
2046       if (I.isVirtual()) {
2047         // Ignore virtual bases; if we're laying out for a complete
2048         // object, we'll lay these out later.
2049         continue;
2050       }
2051 
2052       const CXXRecordDecl *base =
2053         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2054 
2055       // Ignore empty bases.
2056       if (base->isEmpty() ||
2057           CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2058               .isZero())
2059         continue;
2060 
2061       unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2062       llvm::Type *baseType = structure->getElementType(fieldIndex);
2063       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2064     }
2065   }
2066 
2067   // Fill in all the fields.
2068   for (const auto *Field : record->fields()) {
2069     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2070     // will fill in later.)
2071     if (!Field->isBitField()) {
2072       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2073       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2074     }
2075 
2076     // For unions, stop after the first named field.
2077     if (record->isUnion()) {
2078       if (Field->getIdentifier())
2079         break;
2080       if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2081         if (FieldRD->findFirstNamedDataMember())
2082           break;
2083     }
2084   }
2085 
2086   // Fill in the virtual bases, if we're working with the complete object.
2087   if (CXXR && asCompleteObject) {
2088     for (const auto &I : CXXR->vbases()) {
2089       const CXXRecordDecl *base =
2090         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2091 
2092       // Ignore empty bases.
2093       if (base->isEmpty())
2094         continue;
2095 
2096       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2097 
2098       // We might have already laid this field out.
2099       if (elements[fieldIndex]) continue;
2100 
2101       llvm::Type *baseType = structure->getElementType(fieldIndex);
2102       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2103     }
2104   }
2105 
2106   // Now go through all other fields and zero them out.
2107   for (unsigned i = 0; i != numElements; ++i) {
2108     if (!elements[i])
2109       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2110   }
2111 
2112   return llvm::ConstantStruct::get(structure, elements);
2113 }
2114 
2115 /// Emit the null constant for a base subobject.
2116 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2117                                                llvm::Type *baseType,
2118                                                const CXXRecordDecl *base) {
2119   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2120 
2121   // Just zero out bases that don't have any pointer to data members.
2122   if (baseLayout.isZeroInitializableAsBase())
2123     return llvm::Constant::getNullValue(baseType);
2124 
2125   // Otherwise, we can just use its null constant.
2126   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2127 }
2128 
2129 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2130                                                    QualType T) {
2131   return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2132 }
2133 
2134 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2135   if (T->getAs<PointerType>())
2136     return getNullPointer(
2137         cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2138 
2139   if (getTypes().isZeroInitializable(T))
2140     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2141 
2142   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2143     llvm::ArrayType *ATy =
2144       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2145 
2146     QualType ElementTy = CAT->getElementType();
2147 
2148     llvm::Constant *Element =
2149       ConstantEmitter::emitNullForMemory(*this, ElementTy);
2150     unsigned NumElements = CAT->getSize().getZExtValue();
2151     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2152     return llvm::ConstantArray::get(ATy, Array);
2153   }
2154 
2155   if (const RecordType *RT = T->getAs<RecordType>())
2156     return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2157 
2158   assert(T->isMemberDataPointerType() &&
2159          "Should only see pointers to data members here!");
2160 
2161   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2162 }
2163 
2164 llvm::Constant *
2165 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2166   return ::EmitNullConstant(*this, Record, false);
2167 }
2168