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