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_ZeroToOCLOpaqueType:
880       return nullptr;
881     }
882     llvm_unreachable("Invalid CastKind");
883   }
884 
885   llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
886     return Visit(DAE->getExpr(), T);
887   }
888 
889   llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
890     // No need for a DefaultInitExprScope: we don't handle 'this' in a
891     // constant expression.
892     return Visit(DIE->getExpr(), T);
893   }
894 
895   llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
896     if (!E->cleanupsHaveSideEffects())
897       return Visit(E->getSubExpr(), T);
898     return nullptr;
899   }
900 
901   llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
902                                                 QualType T) {
903     return Visit(E->GetTemporaryExpr(), T);
904   }
905 
906   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
907     auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
908     assert(CAT && "can't emit array init for non-constant-bound array");
909     unsigned NumInitElements = ILE->getNumInits();
910     unsigned NumElements = CAT->getSize().getZExtValue();
911 
912     // Initialising an array requires us to automatically
913     // initialise any elements that have not been initialised explicitly
914     unsigned NumInitableElts = std::min(NumInitElements, NumElements);
915 
916     QualType EltType = CAT->getElementType();
917 
918     // Initialize remaining array elements.
919     llvm::Constant *fillC = nullptr;
920     if (Expr *filler = ILE->getArrayFiller()) {
921       fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
922       if (!fillC)
923         return nullptr;
924     }
925 
926     // Copy initializer elements.
927     SmallVector<llvm::Constant*, 16> Elts;
928     if (fillC && fillC->isNullValue())
929       Elts.reserve(NumInitableElts + 1);
930     else
931       Elts.reserve(NumElements);
932 
933     llvm::Type *CommonElementType = nullptr;
934     for (unsigned i = 0; i < NumInitableElts; ++i) {
935       Expr *Init = ILE->getInit(i);
936       llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
937       if (!C)
938         return nullptr;
939       if (i == 0)
940         CommonElementType = C->getType();
941       else if (C->getType() != CommonElementType)
942         CommonElementType = nullptr;
943       Elts.push_back(C);
944     }
945 
946     return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
947                              fillC);
948   }
949 
950   llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
951     return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
952   }
953 
954   llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
955                                              QualType T) {
956     return CGM.EmitNullConstant(T);
957   }
958 
959   llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
960     if (ILE->isTransparent())
961       return Visit(ILE->getInit(0), T);
962 
963     if (ILE->getType()->isArrayType())
964       return EmitArrayInitialization(ILE, T);
965 
966     if (ILE->getType()->isRecordType())
967       return EmitRecordInitialization(ILE, T);
968 
969     return nullptr;
970   }
971 
972   llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
973                                             InitListExpr *Updater,
974                                             QualType destType) {
975     if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
976       llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
977       llvm::Type *ElemType = AType->getElementType();
978 
979       unsigned NumInitElements = Updater->getNumInits();
980       unsigned NumElements = AType->getNumElements();
981 
982       std::vector<llvm::Constant *> Elts;
983       Elts.reserve(NumElements);
984 
985       QualType destElemType = destAT->getElementType();
986 
987       if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
988         for (unsigned i = 0; i != NumElements; ++i)
989           Elts.push_back(DataArray->getElementAsConstant(i));
990       else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
991         for (unsigned i = 0; i != NumElements; ++i)
992           Elts.push_back(Array->getOperand(i));
993       else
994         return nullptr; // FIXME: other array types not implemented
995 
996       llvm::Constant *fillC = nullptr;
997       if (Expr *filler = Updater->getArrayFiller())
998         if (!isa<NoInitExpr>(filler))
999           fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
1000       bool RewriteType = (fillC && fillC->getType() != ElemType);
1001 
1002       for (unsigned i = 0; i != NumElements; ++i) {
1003         Expr *Init = nullptr;
1004         if (i < NumInitElements)
1005           Init = Updater->getInit(i);
1006 
1007         if (!Init && fillC)
1008           Elts[i] = fillC;
1009         else if (!Init || isa<NoInitExpr>(Init))
1010           ; // Do nothing.
1011         else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1012           Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1013         else
1014           Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
1015 
1016        if (!Elts[i])
1017           return nullptr;
1018         RewriteType |= (Elts[i]->getType() != ElemType);
1019       }
1020 
1021       if (RewriteType) {
1022         std::vector<llvm::Type *> Types;
1023         Types.reserve(NumElements);
1024         for (unsigned i = 0; i != NumElements; ++i)
1025           Types.push_back(Elts[i]->getType());
1026         llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1027                                                         Types, true);
1028         return llvm::ConstantStruct::get(SType, Elts);
1029       }
1030 
1031       return llvm::ConstantArray::get(AType, Elts);
1032     }
1033 
1034     if (destType->isRecordType())
1035       return ConstStructBuilder::BuildStruct(Emitter, this, Base, Updater,
1036                                              destType);
1037 
1038     return nullptr;
1039   }
1040 
1041   llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1042                                                 QualType destType) {
1043     auto C = Visit(E->getBase(), destType);
1044     if (!C) return nullptr;
1045     return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
1046   }
1047 
1048   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1049     if (!E->getConstructor()->isTrivial())
1050       return nullptr;
1051 
1052     // FIXME: We should not have to call getBaseElementType here.
1053     const RecordType *RT =
1054       CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1055     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1056 
1057     // If the class doesn't have a trivial destructor, we can't emit it as a
1058     // constant expr.
1059     if (!RD->hasTrivialDestructor())
1060       return nullptr;
1061 
1062     // Only copy and default constructors can be trivial.
1063 
1064 
1065     if (E->getNumArgs()) {
1066       assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1067       assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1068              "trivial ctor has argument but isn't a copy/move ctor");
1069 
1070       Expr *Arg = E->getArg(0);
1071       assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1072              "argument to copy ctor is of wrong type");
1073 
1074       return Visit(Arg, Ty);
1075     }
1076 
1077     return CGM.EmitNullConstant(Ty);
1078   }
1079 
1080   llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1081     // This is a string literal initializing an array in an initializer.
1082     return CGM.GetConstantArrayFromStringLiteral(E);
1083   }
1084 
1085   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1086     // This must be an @encode initializing an array in a static initializer.
1087     // Don't emit it as the address of the string, emit the string data itself
1088     // as an inline array.
1089     std::string Str;
1090     CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1091     const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1092 
1093     // Resize the string to the right size, adding zeros at the end, or
1094     // truncating as needed.
1095     Str.resize(CAT->getSize().getZExtValue(), '\0');
1096     return llvm::ConstantDataArray::getString(VMContext, Str, false);
1097   }
1098 
1099   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1100     return Visit(E->getSubExpr(), T);
1101   }
1102 
1103   // Utility methods
1104   llvm::Type *ConvertType(QualType T) {
1105     return CGM.getTypes().ConvertType(T);
1106   }
1107 };
1108 
1109 }  // end anonymous namespace.
1110 
1111 bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1112                                llvm::Constant *Base,
1113                                InitListExpr *Updater) {
1114   assert(Base && "base expression should not be empty");
1115 
1116   QualType ExprType = Updater->getType();
1117   RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1118   const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1119   const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1120       cast<llvm::StructType>(Base->getType()));
1121   unsigned FieldNo = -1;
1122   unsigned ElementNo = 0;
1123 
1124   // Bail out if we have base classes. We could support these, but they only
1125   // arise in C++1z where we will have already constant folded most interesting
1126   // cases. FIXME: There are still a few more cases we can handle this way.
1127   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1128     if (CXXRD->getNumBases())
1129       return false;
1130 
1131   for (FieldDecl *Field : RD->fields()) {
1132     ++FieldNo;
1133 
1134     if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1135       continue;
1136 
1137     // Skip anonymous bitfields.
1138     if (Field->isUnnamedBitfield())
1139       continue;
1140 
1141     llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
1142 
1143     // Bail out if the type of the ConstantStruct does not have the same layout
1144     // as the type of the InitListExpr.
1145     if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1146         Layout.getFieldOffset(ElementNo) !=
1147           BaseLayout->getElementOffsetInBits(ElementNo))
1148       return false;
1149 
1150     // Get the initializer. If we encounter an empty field or a NoInitExpr,
1151     // we use values from the base expression.
1152     Expr *Init = nullptr;
1153     if (ElementNo < Updater->getNumInits())
1154       Init = Updater->getInit(ElementNo);
1155 
1156     if (!Init || isa<NoInitExpr>(Init))
1157       ; // Do nothing.
1158     else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1159       EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1160                                                        Field->getType());
1161     else
1162       EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
1163 
1164     ++ElementNo;
1165 
1166     if (!EltInit)
1167       return false;
1168 
1169     if (!Field->isBitField())
1170       AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1171     else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1172       AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1173     else
1174       // Initializing a bitfield with a non-trivial constant?
1175       return false;
1176   }
1177 
1178   return true;
1179 }
1180 
1181 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1182                                                         AbstractState saved) {
1183   Abstract = saved.OldValue;
1184 
1185   assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1186          "created a placeholder while doing an abstract emission?");
1187 
1188   // No validation necessary for now.
1189   // No cleanup to do for now.
1190   return C;
1191 }
1192 
1193 llvm::Constant *
1194 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1195   auto state = pushAbstract();
1196   auto C = tryEmitPrivateForVarInit(D);
1197   return validateAndPopAbstract(C, state);
1198 }
1199 
1200 llvm::Constant *
1201 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1202   auto state = pushAbstract();
1203   auto C = tryEmitPrivate(E, destType);
1204   return validateAndPopAbstract(C, state);
1205 }
1206 
1207 llvm::Constant *
1208 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1209   auto state = pushAbstract();
1210   auto C = tryEmitPrivate(value, destType);
1211   return validateAndPopAbstract(C, state);
1212 }
1213 
1214 llvm::Constant *
1215 ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1216   auto state = pushAbstract();
1217   auto C = tryEmitPrivate(E, destType);
1218   C = validateAndPopAbstract(C, state);
1219   if (!C) {
1220     CGM.Error(E->getExprLoc(),
1221               "internal error: could not emit constant value \"abstractly\"");
1222     C = CGM.EmitNullConstant(destType);
1223   }
1224   return C;
1225 }
1226 
1227 llvm::Constant *
1228 ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1229                               QualType destType) {
1230   auto state = pushAbstract();
1231   auto C = tryEmitPrivate(value, destType);
1232   C = validateAndPopAbstract(C, state);
1233   if (!C) {
1234     CGM.Error(loc,
1235               "internal error: could not emit constant value \"abstractly\"");
1236     C = CGM.EmitNullConstant(destType);
1237   }
1238   return C;
1239 }
1240 
1241 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1242   initializeNonAbstract(D.getType().getAddressSpace());
1243   return markIfFailed(tryEmitPrivateForVarInit(D));
1244 }
1245 
1246 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1247                                                        LangAS destAddrSpace,
1248                                                        QualType destType) {
1249   initializeNonAbstract(destAddrSpace);
1250   return markIfFailed(tryEmitPrivateForMemory(E, destType));
1251 }
1252 
1253 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1254                                                     LangAS destAddrSpace,
1255                                                     QualType destType) {
1256   initializeNonAbstract(destAddrSpace);
1257   auto C = tryEmitPrivateForMemory(value, destType);
1258   assert(C && "couldn't emit constant value non-abstractly?");
1259   return C;
1260 }
1261 
1262 llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1263   assert(!Abstract && "cannot get current address for abstract constant");
1264 
1265 
1266 
1267   // Make an obviously ill-formed global that should blow up compilation
1268   // if it survives.
1269   auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1270                                          llvm::GlobalValue::PrivateLinkage,
1271                                          /*init*/ nullptr,
1272                                          /*name*/ "",
1273                                          /*before*/ nullptr,
1274                                          llvm::GlobalVariable::NotThreadLocal,
1275                                          CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1276 
1277   PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1278 
1279   return global;
1280 }
1281 
1282 void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1283                                            llvm::GlobalValue *placeholder) {
1284   assert(!PlaceholderAddresses.empty());
1285   assert(PlaceholderAddresses.back().first == nullptr);
1286   assert(PlaceholderAddresses.back().second == placeholder);
1287   PlaceholderAddresses.back().first = signal;
1288 }
1289 
1290 namespace {
1291   struct ReplacePlaceholders {
1292     CodeGenModule &CGM;
1293 
1294     /// The base address of the global.
1295     llvm::Constant *Base;
1296     llvm::Type *BaseValueTy = nullptr;
1297 
1298     /// The placeholder addresses that were registered during emission.
1299     llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1300 
1301     /// The locations of the placeholder signals.
1302     llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1303 
1304     /// The current index stack.  We use a simple unsigned stack because
1305     /// we assume that placeholders will be relatively sparse in the
1306     /// initializer, but we cache the index values we find just in case.
1307     llvm::SmallVector<unsigned, 8> Indices;
1308     llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1309 
1310     ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1311                         ArrayRef<std::pair<llvm::Constant*,
1312                                            llvm::GlobalVariable*>> addresses)
1313         : CGM(CGM), Base(base),
1314           PlaceholderAddresses(addresses.begin(), addresses.end()) {
1315     }
1316 
1317     void replaceInInitializer(llvm::Constant *init) {
1318       // Remember the type of the top-most initializer.
1319       BaseValueTy = init->getType();
1320 
1321       // Initialize the stack.
1322       Indices.push_back(0);
1323       IndexValues.push_back(nullptr);
1324 
1325       // Recurse into the initializer.
1326       findLocations(init);
1327 
1328       // Check invariants.
1329       assert(IndexValues.size() == Indices.size() && "mismatch");
1330       assert(Indices.size() == 1 && "didn't pop all indices");
1331 
1332       // Do the replacement; this basically invalidates 'init'.
1333       assert(Locations.size() == PlaceholderAddresses.size() &&
1334              "missed a placeholder?");
1335 
1336       // We're iterating over a hashtable, so this would be a source of
1337       // non-determinism in compiler output *except* that we're just
1338       // messing around with llvm::Constant structures, which never itself
1339       // does anything that should be visible in compiler output.
1340       for (auto &entry : Locations) {
1341         assert(entry.first->getParent() == nullptr && "not a placeholder!");
1342         entry.first->replaceAllUsesWith(entry.second);
1343         entry.first->eraseFromParent();
1344       }
1345     }
1346 
1347   private:
1348     void findLocations(llvm::Constant *init) {
1349       // Recurse into aggregates.
1350       if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1351         for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1352           Indices.push_back(i);
1353           IndexValues.push_back(nullptr);
1354 
1355           findLocations(agg->getOperand(i));
1356 
1357           IndexValues.pop_back();
1358           Indices.pop_back();
1359         }
1360         return;
1361       }
1362 
1363       // Otherwise, check for registered constants.
1364       while (true) {
1365         auto it = PlaceholderAddresses.find(init);
1366         if (it != PlaceholderAddresses.end()) {
1367           setLocation(it->second);
1368           break;
1369         }
1370 
1371         // Look through bitcasts or other expressions.
1372         if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1373           init = expr->getOperand(0);
1374         } else {
1375           break;
1376         }
1377       }
1378     }
1379 
1380     void setLocation(llvm::GlobalVariable *placeholder) {
1381       assert(Locations.find(placeholder) == Locations.end() &&
1382              "already found location for placeholder!");
1383 
1384       // Lazily fill in IndexValues with the values from Indices.
1385       // We do this in reverse because we should always have a strict
1386       // prefix of indices from the start.
1387       assert(Indices.size() == IndexValues.size());
1388       for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1389         if (IndexValues[i]) {
1390 #ifndef NDEBUG
1391           for (size_t j = 0; j != i + 1; ++j) {
1392             assert(IndexValues[j] &&
1393                    isa<llvm::ConstantInt>(IndexValues[j]) &&
1394                    cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1395                      == Indices[j]);
1396           }
1397 #endif
1398           break;
1399         }
1400 
1401         IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1402       }
1403 
1404       // Form a GEP and then bitcast to the placeholder type so that the
1405       // replacement will succeed.
1406       llvm::Constant *location =
1407         llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1408                                                      Base, IndexValues);
1409       location = llvm::ConstantExpr::getBitCast(location,
1410                                                 placeholder->getType());
1411 
1412       Locations.insert({placeholder, location});
1413     }
1414   };
1415 }
1416 
1417 void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1418   assert(InitializedNonAbstract &&
1419          "finalizing emitter that was used for abstract emission?");
1420   assert(!Finalized && "finalizing emitter multiple times");
1421   assert(global->getInitializer());
1422 
1423   // Note that we might also be Failed.
1424   Finalized = true;
1425 
1426   if (!PlaceholderAddresses.empty()) {
1427     ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1428       .replaceInInitializer(global->getInitializer());
1429     PlaceholderAddresses.clear(); // satisfy
1430   }
1431 }
1432 
1433 ConstantEmitter::~ConstantEmitter() {
1434   assert((!InitializedNonAbstract || Finalized || Failed) &&
1435          "not finalized after being initialized for non-abstract emission");
1436   assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1437 }
1438 
1439 static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1440   if (auto AT = type->getAs<AtomicType>()) {
1441     return CGM.getContext().getQualifiedType(AT->getValueType(),
1442                                              type.getQualifiers());
1443   }
1444   return type;
1445 }
1446 
1447 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1448   // Make a quick check if variable can be default NULL initialized
1449   // and avoid going through rest of code which may do, for c++11,
1450   // initialization of memory to all NULLs.
1451   if (!D.hasLocalStorage()) {
1452     QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1453     if (Ty->isRecordType())
1454       if (const CXXConstructExpr *E =
1455           dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1456         const CXXConstructorDecl *CD = E->getConstructor();
1457         if (CD->isTrivial() && CD->isDefaultConstructor())
1458           return CGM.EmitNullConstant(D.getType());
1459       }
1460     InConstantContext = true;
1461   }
1462 
1463   QualType destType = D.getType();
1464 
1465   // Try to emit the initializer.  Note that this can allow some things that
1466   // are not allowed by tryEmitPrivateForMemory alone.
1467   if (auto value = D.evaluateValue()) {
1468     return tryEmitPrivateForMemory(*value, destType);
1469   }
1470 
1471   // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1472   // reference is a constant expression, and the reference binds to a temporary,
1473   // then constant initialization is performed. ConstExprEmitter will
1474   // incorrectly emit a prvalue constant in this case, and the calling code
1475   // interprets that as the (pointer) value of the reference, rather than the
1476   // desired value of the referee.
1477   if (destType->isReferenceType())
1478     return nullptr;
1479 
1480   const Expr *E = D.getInit();
1481   assert(E && "No initializer to emit");
1482 
1483   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1484   auto C =
1485     ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1486   return (C ? emitForMemory(C, destType) : nullptr);
1487 }
1488 
1489 llvm::Constant *
1490 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1491   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1492   auto C = tryEmitAbstract(E, nonMemoryDestType);
1493   return (C ? emitForMemory(C, destType) : nullptr);
1494 }
1495 
1496 llvm::Constant *
1497 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1498                                           QualType destType) {
1499   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1500   auto C = tryEmitAbstract(value, nonMemoryDestType);
1501   return (C ? emitForMemory(C, destType) : nullptr);
1502 }
1503 
1504 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1505                                                          QualType destType) {
1506   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1507   llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1508   return (C ? emitForMemory(C, destType) : nullptr);
1509 }
1510 
1511 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1512                                                          QualType destType) {
1513   auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1514   auto C = tryEmitPrivate(value, nonMemoryDestType);
1515   return (C ? emitForMemory(C, destType) : nullptr);
1516 }
1517 
1518 llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1519                                                llvm::Constant *C,
1520                                                QualType destType) {
1521   // For an _Atomic-qualified constant, we may need to add tail padding.
1522   if (auto AT = destType->getAs<AtomicType>()) {
1523     QualType destValueType = AT->getValueType();
1524     C = emitForMemory(CGM, C, destValueType);
1525 
1526     uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1527     uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1528     if (innerSize == outerSize)
1529       return C;
1530 
1531     assert(innerSize < outerSize && "emitted over-large constant for atomic");
1532     llvm::Constant *elts[] = {
1533       C,
1534       llvm::ConstantAggregateZero::get(
1535           llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1536     };
1537     return llvm::ConstantStruct::getAnon(elts);
1538   }
1539 
1540   // Zero-extend bool.
1541   if (C->getType()->isIntegerTy(1)) {
1542     llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1543     return llvm::ConstantExpr::getZExt(C, boolTy);
1544   }
1545 
1546   return C;
1547 }
1548 
1549 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1550                                                 QualType destType) {
1551   Expr::EvalResult Result;
1552 
1553   bool Success = false;
1554 
1555   if (destType->isReferenceType())
1556     Success = E->EvaluateAsLValue(Result, CGM.getContext());
1557   else
1558     Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1559 
1560   llvm::Constant *C;
1561   if (Success && !Result.HasSideEffects)
1562     C = tryEmitPrivate(Result.Val, destType);
1563   else
1564     C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1565 
1566   return C;
1567 }
1568 
1569 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1570   return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1571 }
1572 
1573 namespace {
1574 /// A struct which can be used to peephole certain kinds of finalization
1575 /// that normally happen during l-value emission.
1576 struct ConstantLValue {
1577   llvm::Constant *Value;
1578   bool HasOffsetApplied;
1579 
1580   /*implicit*/ ConstantLValue(llvm::Constant *value,
1581                               bool hasOffsetApplied = false)
1582     : Value(value), HasOffsetApplied(false) {}
1583 
1584   /*implicit*/ ConstantLValue(ConstantAddress address)
1585     : ConstantLValue(address.getPointer()) {}
1586 };
1587 
1588 /// A helper class for emitting constant l-values.
1589 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1590                                                       ConstantLValue> {
1591   CodeGenModule &CGM;
1592   ConstantEmitter &Emitter;
1593   const APValue &Value;
1594   QualType DestType;
1595 
1596   // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1597   friend StmtVisitorBase;
1598 
1599 public:
1600   ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1601                         QualType destType)
1602     : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1603 
1604   llvm::Constant *tryEmit();
1605 
1606 private:
1607   llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1608   ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1609 
1610   ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1611   ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1612   ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1613   ConstantLValue VisitStringLiteral(const StringLiteral *E);
1614   ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1615   ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1616   ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1617   ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1618   ConstantLValue VisitCallExpr(const CallExpr *E);
1619   ConstantLValue VisitBlockExpr(const BlockExpr *E);
1620   ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1621   ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1622   ConstantLValue VisitMaterializeTemporaryExpr(
1623                                          const MaterializeTemporaryExpr *E);
1624 
1625   bool hasNonZeroOffset() const {
1626     return !Value.getLValueOffset().isZero();
1627   }
1628 
1629   /// Return the value offset.
1630   llvm::Constant *getOffset() {
1631     return llvm::ConstantInt::get(CGM.Int64Ty,
1632                                   Value.getLValueOffset().getQuantity());
1633   }
1634 
1635   /// Apply the value offset to the given constant.
1636   llvm::Constant *applyOffset(llvm::Constant *C) {
1637     if (!hasNonZeroOffset())
1638       return C;
1639 
1640     llvm::Type *origPtrTy = C->getType();
1641     unsigned AS = origPtrTy->getPointerAddressSpace();
1642     llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1643     C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1644     C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1645     C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1646     return C;
1647   }
1648 };
1649 
1650 }
1651 
1652 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1653   const APValue::LValueBase &base = Value.getLValueBase();
1654 
1655   // The destination type should be a pointer or reference
1656   // type, but it might also be a cast thereof.
1657   //
1658   // FIXME: the chain of casts required should be reflected in the APValue.
1659   // We need this in order to correctly handle things like a ptrtoint of a
1660   // non-zero null pointer and addrspace casts that aren't trivially
1661   // represented in LLVM IR.
1662   auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1663   assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1664 
1665   // If there's no base at all, this is a null or absolute pointer,
1666   // possibly cast back to an integer type.
1667   if (!base) {
1668     return tryEmitAbsolute(destTy);
1669   }
1670 
1671   // Otherwise, try to emit the base.
1672   ConstantLValue result = tryEmitBase(base);
1673 
1674   // If that failed, we're done.
1675   llvm::Constant *value = result.Value;
1676   if (!value) return nullptr;
1677 
1678   // Apply the offset if necessary and not already done.
1679   if (!result.HasOffsetApplied) {
1680     value = applyOffset(value);
1681   }
1682 
1683   // Convert to the appropriate type; this could be an lvalue for
1684   // an integer.  FIXME: performAddrSpaceCast
1685   if (isa<llvm::PointerType>(destTy))
1686     return llvm::ConstantExpr::getPointerCast(value, destTy);
1687 
1688   return llvm::ConstantExpr::getPtrToInt(value, destTy);
1689 }
1690 
1691 /// Try to emit an absolute l-value, such as a null pointer or an integer
1692 /// bitcast to pointer type.
1693 llvm::Constant *
1694 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1695   auto offset = getOffset();
1696 
1697   // If we're producing a pointer, this is easy.
1698   if (auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1699     if (Value.isNullPointer()) {
1700       // FIXME: integer offsets from non-zero null pointers.
1701       return CGM.getNullPointer(destPtrTy, DestType);
1702     }
1703 
1704     // Convert the integer to a pointer-sized integer before converting it
1705     // to a pointer.
1706     // FIXME: signedness depends on the original integer type.
1707     auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1708     llvm::Constant *C = offset;
1709     C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1710                                            /*isSigned*/ false);
1711     C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1712     return C;
1713   }
1714 
1715   // Otherwise, we're basically returning an integer constant.
1716 
1717   // FIXME: this does the wrong thing with ptrtoint of a null pointer,
1718   // but since we don't know the original pointer type, there's not much
1719   // we can do about it.
1720 
1721   auto C = getOffset();
1722   C = llvm::ConstantExpr::getIntegerCast(C, destTy, /*isSigned*/ false);
1723   return C;
1724 }
1725 
1726 ConstantLValue
1727 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1728   // Handle values.
1729   if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1730     if (D->hasAttr<WeakRefAttr>())
1731       return CGM.GetWeakRefReference(D).getPointer();
1732 
1733     if (auto FD = dyn_cast<FunctionDecl>(D))
1734       return CGM.GetAddrOfFunction(FD);
1735 
1736     if (auto VD = dyn_cast<VarDecl>(D)) {
1737       // We can never refer to a variable with local storage.
1738       if (!VD->hasLocalStorage()) {
1739         if (VD->isFileVarDecl() || VD->hasExternalStorage())
1740           return CGM.GetAddrOfGlobalVar(VD);
1741 
1742         if (VD->isLocalVarDecl()) {
1743           return CGM.getOrCreateStaticVarDecl(
1744               *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1745         }
1746       }
1747     }
1748 
1749     return nullptr;
1750   }
1751 
1752   // Otherwise, it must be an expression.
1753   return Visit(base.get<const Expr*>());
1754 }
1755 
1756 ConstantLValue
1757 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1758   return Visit(E->getSubExpr());
1759 }
1760 
1761 ConstantLValue
1762 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1763   return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1764 }
1765 
1766 ConstantLValue
1767 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1768   return CGM.GetAddrOfConstantStringFromLiteral(E);
1769 }
1770 
1771 ConstantLValue
1772 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1773   return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1774 }
1775 
1776 ConstantLValue
1777 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1778   auto C = CGM.getObjCRuntime().GenerateConstantString(E->getString());
1779   return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(E->getType()));
1780 }
1781 
1782 ConstantLValue
1783 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1784   return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1785 }
1786 
1787 ConstantLValue
1788 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1789   assert(Emitter.CGF && "Invalid address of label expression outside function");
1790   llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1791   Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1792                                    CGM.getTypes().ConvertType(E->getType()));
1793   return Ptr;
1794 }
1795 
1796 ConstantLValue
1797 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1798   unsigned builtin = E->getBuiltinCallee();
1799   if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1800       builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1801     return nullptr;
1802 
1803   auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1804   if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1805     return CGM.getObjCRuntime().GenerateConstantString(literal);
1806   } else {
1807     // FIXME: need to deal with UCN conversion issues.
1808     return CGM.GetAddrOfConstantCFString(literal);
1809   }
1810 }
1811 
1812 ConstantLValue
1813 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1814   StringRef functionName;
1815   if (auto CGF = Emitter.CGF)
1816     functionName = CGF->CurFn->getName();
1817   else
1818     functionName = "global";
1819 
1820   return CGM.GetAddrOfGlobalBlock(E, functionName);
1821 }
1822 
1823 ConstantLValue
1824 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1825   QualType T;
1826   if (E->isTypeOperand())
1827     T = E->getTypeOperand(CGM.getContext());
1828   else
1829     T = E->getExprOperand()->getType();
1830   return CGM.GetAddrOfRTTIDescriptor(T);
1831 }
1832 
1833 ConstantLValue
1834 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1835   return CGM.GetAddrOfUuidDescriptor(E);
1836 }
1837 
1838 ConstantLValue
1839 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1840                                             const MaterializeTemporaryExpr *E) {
1841   assert(E->getStorageDuration() == SD_Static);
1842   SmallVector<const Expr *, 2> CommaLHSs;
1843   SmallVector<SubobjectAdjustment, 2> Adjustments;
1844   const Expr *Inner = E->GetTemporaryExpr()
1845       ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1846   return CGM.GetAddrOfGlobalTemporary(E, Inner);
1847 }
1848 
1849 llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1850                                                 QualType DestType) {
1851   switch (Value.getKind()) {
1852   case APValue::Uninitialized:
1853     llvm_unreachable("Constant expressions should be initialized.");
1854   case APValue::LValue:
1855     return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
1856   case APValue::Int:
1857     return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
1858   case APValue::FixedPoint:
1859     return llvm::ConstantInt::get(CGM.getLLVMContext(),
1860                                   Value.getFixedPoint().getValue());
1861   case APValue::ComplexInt: {
1862     llvm::Constant *Complex[2];
1863 
1864     Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1865                                         Value.getComplexIntReal());
1866     Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1867                                         Value.getComplexIntImag());
1868 
1869     // FIXME: the target may want to specify that this is packed.
1870     llvm::StructType *STy =
1871         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1872     return llvm::ConstantStruct::get(STy, Complex);
1873   }
1874   case APValue::Float: {
1875     const llvm::APFloat &Init = Value.getFloat();
1876     if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1877         !CGM.getContext().getLangOpts().NativeHalfType &&
1878         CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
1879       return llvm::ConstantInt::get(CGM.getLLVMContext(),
1880                                     Init.bitcastToAPInt());
1881     else
1882       return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
1883   }
1884   case APValue::ComplexFloat: {
1885     llvm::Constant *Complex[2];
1886 
1887     Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1888                                        Value.getComplexFloatReal());
1889     Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1890                                        Value.getComplexFloatImag());
1891 
1892     // FIXME: the target may want to specify that this is packed.
1893     llvm::StructType *STy =
1894         llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1895     return llvm::ConstantStruct::get(STy, Complex);
1896   }
1897   case APValue::Vector: {
1898     unsigned NumElts = Value.getVectorLength();
1899     SmallVector<llvm::Constant *, 4> Inits(NumElts);
1900 
1901     for (unsigned I = 0; I != NumElts; ++I) {
1902       const APValue &Elt = Value.getVectorElt(I);
1903       if (Elt.isInt())
1904         Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
1905       else if (Elt.isFloat())
1906         Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
1907       else
1908         llvm_unreachable("unsupported vector element type");
1909     }
1910     return llvm::ConstantVector::get(Inits);
1911   }
1912   case APValue::AddrLabelDiff: {
1913     const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1914     const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1915     llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1916     llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1917     if (!LHS || !RHS) return nullptr;
1918 
1919     // Compute difference
1920     llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1921     LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1922     RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
1923     llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1924 
1925     // LLVM is a bit sensitive about the exact format of the
1926     // address-of-label difference; make sure to truncate after
1927     // the subtraction.
1928     return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1929   }
1930   case APValue::Struct:
1931   case APValue::Union:
1932     return ConstStructBuilder::BuildStruct(*this, Value, DestType);
1933   case APValue::Array: {
1934     const ConstantArrayType *CAT =
1935         CGM.getContext().getAsConstantArrayType(DestType);
1936     unsigned NumElements = Value.getArraySize();
1937     unsigned NumInitElts = Value.getArrayInitializedElts();
1938 
1939     // Emit array filler, if there is one.
1940     llvm::Constant *Filler = nullptr;
1941     if (Value.hasArrayFiller()) {
1942       Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1943                                         CAT->getElementType());
1944       if (!Filler)
1945         return nullptr;
1946     }
1947 
1948     // Emit initializer elements.
1949     SmallVector<llvm::Constant*, 16> Elts;
1950     if (Filler && Filler->isNullValue())
1951       Elts.reserve(NumInitElts + 1);
1952     else
1953       Elts.reserve(NumElements);
1954 
1955     llvm::Type *CommonElementType = nullptr;
1956     for (unsigned I = 0; I < NumInitElts; ++I) {
1957       llvm::Constant *C = tryEmitPrivateForMemory(
1958           Value.getArrayInitializedElt(I), CAT->getElementType());
1959       if (!C) return nullptr;
1960 
1961       if (I == 0)
1962         CommonElementType = C->getType();
1963       else if (C->getType() != CommonElementType)
1964         CommonElementType = nullptr;
1965       Elts.push_back(C);
1966     }
1967 
1968     // This means that the array type is probably "IncompleteType" or some
1969     // type that is not ConstantArray.
1970     if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1971       const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1972       CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1973       llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1974                                                     NumElements);
1975       return llvm::ConstantAggregateZero::get(AType);
1976     }
1977 
1978     return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1979                              Filler);
1980   }
1981   case APValue::MemberPointer:
1982     return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
1983   }
1984   llvm_unreachable("Unknown APValue kind");
1985 }
1986 
1987 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
1988     const CompoundLiteralExpr *E) {
1989   return EmittedCompoundLiterals.lookup(E);
1990 }
1991 
1992 void CodeGenModule::setAddrOfConstantCompoundLiteral(
1993     const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
1994   bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
1995   (void)Ok;
1996   assert(Ok && "CLE has already been emitted!");
1997 }
1998 
1999 ConstantAddress
2000 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2001   assert(E->isFileScope() && "not a file-scope compound literal expr");
2002   return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2003 }
2004 
2005 llvm::Constant *
2006 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2007   // Member pointer constants always have a very particular form.
2008   const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2009   const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2010 
2011   // A member function pointer.
2012   if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2013     return getCXXABI().EmitMemberFunctionPointer(method);
2014 
2015   // Otherwise, a member data pointer.
2016   uint64_t fieldOffset = getContext().getFieldOffset(decl);
2017   CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2018   return getCXXABI().EmitMemberDataPointer(type, chars);
2019 }
2020 
2021 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2022                                                llvm::Type *baseType,
2023                                                const CXXRecordDecl *base);
2024 
2025 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2026                                         const RecordDecl *record,
2027                                         bool asCompleteObject) {
2028   const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2029   llvm::StructType *structure =
2030     (asCompleteObject ? layout.getLLVMType()
2031                       : layout.getBaseSubobjectLLVMType());
2032 
2033   unsigned numElements = structure->getNumElements();
2034   std::vector<llvm::Constant *> elements(numElements);
2035 
2036   auto CXXR = dyn_cast<CXXRecordDecl>(record);
2037   // Fill in all the bases.
2038   if (CXXR) {
2039     for (const auto &I : CXXR->bases()) {
2040       if (I.isVirtual()) {
2041         // Ignore virtual bases; if we're laying out for a complete
2042         // object, we'll lay these out later.
2043         continue;
2044       }
2045 
2046       const CXXRecordDecl *base =
2047         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2048 
2049       // Ignore empty bases.
2050       if (base->isEmpty() ||
2051           CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2052               .isZero())
2053         continue;
2054 
2055       unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2056       llvm::Type *baseType = structure->getElementType(fieldIndex);
2057       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2058     }
2059   }
2060 
2061   // Fill in all the fields.
2062   for (const auto *Field : record->fields()) {
2063     // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2064     // will fill in later.)
2065     if (!Field->isBitField()) {
2066       unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2067       elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2068     }
2069 
2070     // For unions, stop after the first named field.
2071     if (record->isUnion()) {
2072       if (Field->getIdentifier())
2073         break;
2074       if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2075         if (FieldRD->findFirstNamedDataMember())
2076           break;
2077     }
2078   }
2079 
2080   // Fill in the virtual bases, if we're working with the complete object.
2081   if (CXXR && asCompleteObject) {
2082     for (const auto &I : CXXR->vbases()) {
2083       const CXXRecordDecl *base =
2084         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2085 
2086       // Ignore empty bases.
2087       if (base->isEmpty())
2088         continue;
2089 
2090       unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2091 
2092       // We might have already laid this field out.
2093       if (elements[fieldIndex]) continue;
2094 
2095       llvm::Type *baseType = structure->getElementType(fieldIndex);
2096       elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2097     }
2098   }
2099 
2100   // Now go through all other fields and zero them out.
2101   for (unsigned i = 0; i != numElements; ++i) {
2102     if (!elements[i])
2103       elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2104   }
2105 
2106   return llvm::ConstantStruct::get(structure, elements);
2107 }
2108 
2109 /// Emit the null constant for a base subobject.
2110 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2111                                                llvm::Type *baseType,
2112                                                const CXXRecordDecl *base) {
2113   const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2114 
2115   // Just zero out bases that don't have any pointer to data members.
2116   if (baseLayout.isZeroInitializableAsBase())
2117     return llvm::Constant::getNullValue(baseType);
2118 
2119   // Otherwise, we can just use its null constant.
2120   return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2121 }
2122 
2123 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2124                                                    QualType T) {
2125   return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2126 }
2127 
2128 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2129   if (T->getAs<PointerType>())
2130     return getNullPointer(
2131         cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2132 
2133   if (getTypes().isZeroInitializable(T))
2134     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2135 
2136   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2137     llvm::ArrayType *ATy =
2138       cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2139 
2140     QualType ElementTy = CAT->getElementType();
2141 
2142     llvm::Constant *Element =
2143       ConstantEmitter::emitNullForMemory(*this, ElementTy);
2144     unsigned NumElements = CAT->getSize().getZExtValue();
2145     SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2146     return llvm::ConstantArray::get(ATy, Array);
2147   }
2148 
2149   if (const RecordType *RT = T->getAs<RecordType>())
2150     return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2151 
2152   assert(T->isMemberDataPointerType() &&
2153          "Should only see pointers to data members here!");
2154 
2155   return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2156 }
2157 
2158 llvm::Constant *
2159 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2160   return ::EmitNullConstant(*this, Record, false);
2161 }
2162