clang  3.8.0
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 "clang/AST/APValue.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/Builtins.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 //===----------------------------------------------------------------------===//
32 // ConstStructBuilder
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 class ConstExprEmitter;
37 class ConstStructBuilder {
38  CodeGenModule &CGM;
39  CodeGenFunction *CGF;
40 
41  bool Packed;
42  CharUnits NextFieldOffsetInChars;
43  CharUnits LLVMStructAlignment;
45 public:
46  static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CFG,
47  ConstExprEmitter *Emitter,
48  llvm::ConstantStruct *Base,
49  InitListExpr *Updater);
50  static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
51  InitListExpr *ILE);
52  static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
53  const APValue &Value, QualType ValTy);
54 
55 private:
56  ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
57  : CGM(CGM), CGF(CGF), Packed(false),
58  NextFieldOffsetInChars(CharUnits::Zero()),
59  LLVMStructAlignment(CharUnits::One()) { }
60 
61  void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
62  llvm::Constant *InitExpr);
63 
64  void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
65 
66  void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
67  llvm::ConstantInt *InitExpr);
68 
69  void AppendPadding(CharUnits PadSize);
70 
71  void AppendTailPadding(CharUnits RecordSize);
72 
73  void ConvertStructToPacked();
74 
75  bool Build(InitListExpr *ILE);
76  bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base,
77  InitListExpr *Updater);
78  void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
79  const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
80  llvm::Constant *Finalize(QualType Ty);
81 
82  CharUnits getAlignment(const llvm::Constant *C) const {
83  if (Packed) return CharUnits::One();
85  CGM.getDataLayout().getABITypeAlignment(C->getType()));
86  }
87 
88  CharUnits getSizeInChars(const llvm::Constant *C) const {
90  CGM.getDataLayout().getTypeAllocSize(C->getType()));
91  }
92 };
93 
94 void ConstStructBuilder::
95 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
96  llvm::Constant *InitCst) {
97  const ASTContext &Context = CGM.getContext();
98 
99  CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
100 
101  AppendBytes(FieldOffsetInChars, InitCst);
102 }
103 
104 void ConstStructBuilder::
105 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
106 
107  assert(NextFieldOffsetInChars <= FieldOffsetInChars
108  && "Field offset mismatch!");
109 
110  CharUnits FieldAlignment = getAlignment(InitCst);
111 
112  // Round up the field offset to the alignment of the field type.
113  CharUnits AlignedNextFieldOffsetInChars =
114  NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
115 
116  if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
117  // We need to append padding.
118  AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
119 
120  assert(NextFieldOffsetInChars == FieldOffsetInChars &&
121  "Did not add enough padding!");
122 
123  AlignedNextFieldOffsetInChars =
124  NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
125  }
126 
127  if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
128  assert(!Packed && "Alignment is wrong even with a packed struct!");
129 
130  // Convert the struct to a packed struct.
131  ConvertStructToPacked();
132 
133  // After we pack the struct, we may need to insert padding.
134  if (NextFieldOffsetInChars < FieldOffsetInChars) {
135  // We need to append padding.
136  AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
137 
138  assert(NextFieldOffsetInChars == FieldOffsetInChars &&
139  "Did not add enough padding!");
140  }
141  AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
142  }
143 
144  // Add the field.
145  Elements.push_back(InitCst);
146  NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
147  getSizeInChars(InitCst);
148 
149  if (Packed)
150  assert(LLVMStructAlignment == CharUnits::One() &&
151  "Packed struct not byte-aligned!");
152  else
153  LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
154 }
155 
156 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
157  uint64_t FieldOffset,
158  llvm::ConstantInt *CI) {
159  const ASTContext &Context = CGM.getContext();
160  const uint64_t CharWidth = Context.getCharWidth();
161  uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
162  if (FieldOffset > NextFieldOffsetInBits) {
163  // We need to add padding.
164  CharUnits PadSize = Context.toCharUnitsFromBits(
165  llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
166  Context.getTargetInfo().getCharAlign()));
167 
168  AppendPadding(PadSize);
169  }
170 
171  uint64_t FieldSize = Field->getBitWidthValue(Context);
172 
173  llvm::APInt FieldValue = CI->getValue();
174 
175  // Promote the size of FieldValue if necessary
176  // FIXME: This should never occur, but currently it can because initializer
177  // constants are cast to bool, and because clang is not enforcing bitfield
178  // width limits.
179  if (FieldSize > FieldValue.getBitWidth())
180  FieldValue = FieldValue.zext(FieldSize);
181 
182  // Truncate the size of FieldValue to the bit field size.
183  if (FieldSize < FieldValue.getBitWidth())
184  FieldValue = FieldValue.trunc(FieldSize);
185 
186  NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
187  if (FieldOffset < NextFieldOffsetInBits) {
188  // Either part of the field or the entire field can go into the previous
189  // byte.
190  assert(!Elements.empty() && "Elements can't be empty!");
191 
192  unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
193 
194  bool FitsCompletelyInPreviousByte =
195  BitsInPreviousByte >= FieldValue.getBitWidth();
196 
197  llvm::APInt Tmp = FieldValue;
198 
199  if (!FitsCompletelyInPreviousByte) {
200  unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
201 
202  if (CGM.getDataLayout().isBigEndian()) {
203  Tmp = Tmp.lshr(NewFieldWidth);
204  Tmp = Tmp.trunc(BitsInPreviousByte);
205 
206  // We want the remaining high bits.
207  FieldValue = FieldValue.trunc(NewFieldWidth);
208  } else {
209  Tmp = Tmp.trunc(BitsInPreviousByte);
210 
211  // We want the remaining low bits.
212  FieldValue = FieldValue.lshr(BitsInPreviousByte);
213  FieldValue = FieldValue.trunc(NewFieldWidth);
214  }
215  }
216 
217  Tmp = Tmp.zext(CharWidth);
218  if (CGM.getDataLayout().isBigEndian()) {
219  if (FitsCompletelyInPreviousByte)
220  Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
221  } else {
222  Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
223  }
224 
225  // 'or' in the bits that go into the previous byte.
226  llvm::Value *LastElt = Elements.back();
227  if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
228  Tmp |= Val->getValue();
229  else {
230  assert(isa<llvm::UndefValue>(LastElt));
231  // If there is an undef field that we're adding to, it can either be a
232  // scalar undef (in which case, we just replace it with our field) or it
233  // is an array. If it is an array, we have to pull one byte off the
234  // array so that the other undef bytes stay around.
235  if (!isa<llvm::IntegerType>(LastElt->getType())) {
236  // The undef padding will be a multibyte array, create a new smaller
237  // padding and then an hole for our i8 to get plopped into.
238  assert(isa<llvm::ArrayType>(LastElt->getType()) &&
239  "Expected array padding of undefs");
240  llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
241  assert(AT->getElementType()->isIntegerTy(CharWidth) &&
242  AT->getNumElements() != 0 &&
243  "Expected non-empty array padding of undefs");
244 
245  // Remove the padding array.
246  NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
247  Elements.pop_back();
248 
249  // Add the padding back in two chunks.
250  AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
251  AppendPadding(CharUnits::One());
252  assert(isa<llvm::UndefValue>(Elements.back()) &&
253  Elements.back()->getType()->isIntegerTy(CharWidth) &&
254  "Padding addition didn't work right");
255  }
256  }
257 
258  Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
259 
260  if (FitsCompletelyInPreviousByte)
261  return;
262  }
263 
264  while (FieldValue.getBitWidth() > CharWidth) {
265  llvm::APInt Tmp;
266 
267  if (CGM.getDataLayout().isBigEndian()) {
268  // We want the high bits.
269  Tmp =
270  FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
271  } else {
272  // We want the low bits.
273  Tmp = FieldValue.trunc(CharWidth);
274 
275  FieldValue = FieldValue.lshr(CharWidth);
276  }
277 
278  Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
279  ++NextFieldOffsetInChars;
280 
281  FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
282  }
283 
284  assert(FieldValue.getBitWidth() > 0 &&
285  "Should have at least one bit left!");
286  assert(FieldValue.getBitWidth() <= CharWidth &&
287  "Should not have more than a byte left!");
288 
289  if (FieldValue.getBitWidth() < CharWidth) {
290  if (CGM.getDataLayout().isBigEndian()) {
291  unsigned BitWidth = FieldValue.getBitWidth();
292 
293  FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
294  } else
295  FieldValue = FieldValue.zext(CharWidth);
296  }
297 
298  // Append the last element.
299  Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
300  FieldValue));
301  ++NextFieldOffsetInChars;
302 }
303 
304 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
305  if (PadSize.isZero())
306  return;
307 
308  llvm::Type *Ty = CGM.Int8Ty;
309  if (PadSize > CharUnits::One())
310  Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
311 
312  llvm::Constant *C = llvm::UndefValue::get(Ty);
313  Elements.push_back(C);
314  assert(getAlignment(C) == CharUnits::One() &&
315  "Padding must have 1 byte alignment!");
316 
317  NextFieldOffsetInChars += getSizeInChars(C);
318 }
319 
320 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
321  assert(NextFieldOffsetInChars <= RecordSize &&
322  "Size mismatch!");
323 
324  AppendPadding(RecordSize - NextFieldOffsetInChars);
325 }
326 
327 void ConstStructBuilder::ConvertStructToPacked() {
328  SmallVector<llvm::Constant *, 16> PackedElements;
329  CharUnits ElementOffsetInChars = CharUnits::Zero();
330 
331  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
332  llvm::Constant *C = Elements[i];
333 
334  CharUnits ElementAlign = CharUnits::fromQuantity(
335  CGM.getDataLayout().getABITypeAlignment(C->getType()));
336  CharUnits AlignedElementOffsetInChars =
337  ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
338 
339  if (AlignedElementOffsetInChars > ElementOffsetInChars) {
340  // We need some padding.
341  CharUnits NumChars =
342  AlignedElementOffsetInChars - ElementOffsetInChars;
343 
344  llvm::Type *Ty = CGM.Int8Ty;
345  if (NumChars > CharUnits::One())
346  Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
347 
348  llvm::Constant *Padding = llvm::UndefValue::get(Ty);
349  PackedElements.push_back(Padding);
350  ElementOffsetInChars += getSizeInChars(Padding);
351  }
352 
353  PackedElements.push_back(C);
354  ElementOffsetInChars += getSizeInChars(C);
355  }
356 
357  assert(ElementOffsetInChars == NextFieldOffsetInChars &&
358  "Packing the struct changed its size!");
359 
360  Elements.swap(PackedElements);
361  LLVMStructAlignment = CharUnits::One();
362  Packed = true;
363 }
364 
365 bool ConstStructBuilder::Build(InitListExpr *ILE) {
366  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
367  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
368 
369  unsigned FieldNo = 0;
370  unsigned ElementNo = 0;
371 
372  for (RecordDecl::field_iterator Field = RD->field_begin(),
373  FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
374  // If this is a union, skip all the fields that aren't being initialized.
375  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
376  continue;
377 
378  // Don't emit anonymous bitfields, they just affect layout.
379  if (Field->isUnnamedBitfield())
380  continue;
381 
382  // Get the initializer. A struct can include fields without initializers,
383  // we just use explicit null values for them.
384  llvm::Constant *EltInit;
385  if (ElementNo < ILE->getNumInits())
386  EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
387  Field->getType(), CGF);
388  else
389  EltInit = CGM.EmitNullConstant(Field->getType());
390 
391  if (!EltInit)
392  return false;
393 
394  if (!Field->isBitField()) {
395  // Handle non-bitfield members.
396  AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
397  } else {
398  // Otherwise we have a bitfield.
399  if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
400  AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
401  } else {
402  // We are trying to initialize a bitfield with a non-trivial constant,
403  // this must require run-time code.
404  return false;
405  }
406  }
407  }
408 
409  return true;
410 }
411 
412 namespace {
413 struct BaseInfo {
414  BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
415  : Decl(Decl), Offset(Offset), Index(Index) {
416  }
417 
418  const CXXRecordDecl *Decl;
420  unsigned Index;
421 
422  bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
423 };
424 }
425 
426 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
427  bool IsPrimaryBase,
428  const CXXRecordDecl *VTableClass,
429  CharUnits Offset) {
430  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
431 
432  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
433  // Add a vtable pointer, if we need one and it hasn't already been added.
434  if (CD->isDynamicClass() && !IsPrimaryBase) {
435  llvm::Constant *VTableAddressPoint =
436  CGM.getCXXABI().getVTableAddressPointForConstExpr(
437  BaseSubobject(CD, Offset), VTableClass);
438  AppendBytes(Offset, VTableAddressPoint);
439  }
440 
441  // Accumulate and sort bases, in order to visit them in address order, which
442  // may not be the same as declaration order.
444  Bases.reserve(CD->getNumBases());
445  unsigned BaseNo = 0;
446  for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
447  BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
448  assert(!Base->isVirtual() && "should not have virtual bases here");
449  const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
450  CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
451  Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
452  }
453  std::stable_sort(Bases.begin(), Bases.end());
454 
455  for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
456  BaseInfo &Base = Bases[I];
457 
458  bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
459  Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
460  VTableClass, Offset + Base.Offset);
461  }
462  }
463 
464  unsigned FieldNo = 0;
465  uint64_t OffsetBits = CGM.getContext().toBits(Offset);
466 
467  for (RecordDecl::field_iterator Field = RD->field_begin(),
468  FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
469  // If this is a union, skip all the fields that aren't being initialized.
470  if (RD->isUnion() && Val.getUnionField() != *Field)
471  continue;
472 
473  // Don't emit anonymous bitfields, they just affect layout.
474  if (Field->isUnnamedBitfield())
475  continue;
476 
477  // Emit the value of the initializer.
478  const APValue &FieldValue =
479  RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
480  llvm::Constant *EltInit =
481  CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
482  assert(EltInit && "EmitConstantValue can't fail");
483 
484  if (!Field->isBitField()) {
485  // Handle non-bitfield members.
486  AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
487  } else {
488  // Otherwise we have a bitfield.
489  AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
490  cast<llvm::ConstantInt>(EltInit));
491  }
492  }
493 }
494 
495 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
496  RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
497  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
498 
499  CharUnits LayoutSizeInChars = Layout.getSize();
500 
501  if (NextFieldOffsetInChars > LayoutSizeInChars) {
502  // If the struct is bigger than the size of the record type,
503  // we must have a flexible array member at the end.
504  assert(RD->hasFlexibleArrayMember() &&
505  "Must have flexible array member if struct is bigger than type!");
506 
507  // No tail padding is necessary.
508  } else {
509  // Append tail padding if necessary.
510  CharUnits LLVMSizeInChars =
511  NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
512 
513  if (LLVMSizeInChars != LayoutSizeInChars)
514  AppendTailPadding(LayoutSizeInChars);
515 
516  LLVMSizeInChars =
517  NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
518 
519  // Check if we need to convert the struct to a packed struct.
520  if (NextFieldOffsetInChars <= LayoutSizeInChars &&
521  LLVMSizeInChars > LayoutSizeInChars) {
522  assert(!Packed && "Size mismatch!");
523 
524  ConvertStructToPacked();
525  assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
526  "Converting to packed did not help!");
527  }
528 
529  LLVMSizeInChars =
530  NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
531 
532  assert(LayoutSizeInChars == LLVMSizeInChars &&
533  "Tail padding mismatch!");
534  }
535 
536  // Pick the type to use. If the type is layout identical to the ConvertType
537  // type then use it, otherwise use whatever the builder produced for us.
538  llvm::StructType *STy =
539  llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
540  Elements, Packed);
541  llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
542  if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
543  if (ValSTy->isLayoutIdentical(STy))
544  STy = ValSTy;
545  }
546 
547  llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
548 
549  assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
550  getSizeInChars(Result) && "Size mismatch!");
551 
552  return Result;
553 }
554 
555 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
556  CodeGenFunction *CGF,
557  ConstExprEmitter *Emitter,
558  llvm::ConstantStruct *Base,
559  InitListExpr *Updater) {
560  ConstStructBuilder Builder(CGM, CGF);
561  if (!Builder.Build(Emitter, Base, Updater))
562  return nullptr;
563  return Builder.Finalize(Updater->getType());
564 }
565 
566 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
567  CodeGenFunction *CGF,
568  InitListExpr *ILE) {
569  ConstStructBuilder Builder(CGM, CGF);
570 
571  if (!Builder.Build(ILE))
572  return nullptr;
573 
574  return Builder.Finalize(ILE->getType());
575 }
576 
577 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
578  CodeGenFunction *CGF,
579  const APValue &Val,
580  QualType ValTy) {
581  ConstStructBuilder Builder(CGM, CGF);
582 
583  const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
584  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
585  Builder.Build(Val, RD, false, CD, CharUnits::Zero());
586 
587  return Builder.Finalize(ValTy);
588 }
589 
590 
591 //===----------------------------------------------------------------------===//
592 // ConstExprEmitter
593 //===----------------------------------------------------------------------===//
594 
595 /// This class only needs to handle two cases:
596 /// 1) Literals (this is used by APValue emission to emit literals).
597 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
598 /// constant fold these types).
599 class ConstExprEmitter :
600  public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
601  CodeGenModule &CGM;
602  CodeGenFunction *CGF;
603  llvm::LLVMContext &VMContext;
604 public:
605  ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
606  : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
607  }
608 
609  //===--------------------------------------------------------------------===//
610  // Visitor Methods
611  //===--------------------------------------------------------------------===//
612 
613  llvm::Constant *VisitStmt(Stmt *S) {
614  return nullptr;
615  }
616 
617  llvm::Constant *VisitParenExpr(ParenExpr *PE) {
618  return Visit(PE->getSubExpr());
619  }
620 
621  llvm::Constant *
622  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
623  return Visit(PE->getReplacement());
624  }
625 
626  llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
627  return Visit(GE->getResultExpr());
628  }
629 
630  llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
631  return Visit(CE->getChosenSubExpr());
632  }
633 
634  llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
635  return Visit(E->getInitializer());
636  }
637 
638  llvm::Constant *VisitCastExpr(CastExpr* E) {
639  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
640  CGM.EmitExplicitCastExprType(ECE, CGF);
641  Expr *subExpr = E->getSubExpr();
642  llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
643  if (!C) return nullptr;
644 
645  llvm::Type *destType = ConvertType(E->getType());
646 
647  switch (E->getCastKind()) {
648  case CK_ToUnion: {
649  // GCC cast to union extension
650  assert(E->getType()->isUnionType() &&
651  "Destination type is not union type!");
652 
653  // Build a struct with the union sub-element as the first member,
654  // and padded to the appropriate size
657  Elts.push_back(C);
658  Types.push_back(C->getType());
659  unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
660  unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
661 
662  assert(CurSize <= TotalSize && "Union size mismatch!");
663  if (unsigned NumPadBytes = TotalSize - CurSize) {
664  llvm::Type *Ty = CGM.Int8Ty;
665  if (NumPadBytes > 1)
666  Ty = llvm::ArrayType::get(Ty, NumPadBytes);
667 
668  Elts.push_back(llvm::UndefValue::get(Ty));
669  Types.push_back(Ty);
670  }
671 
672  llvm::StructType* STy =
673  llvm::StructType::get(C->getType()->getContext(), Types, false);
674  return llvm::ConstantStruct::get(STy, Elts);
675  }
676 
678  return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
679 
680  case CK_LValueToRValue:
683  case CK_NoOp:
685  return C;
686 
687  case CK_Dependent: llvm_unreachable("saw dependent cast!");
688 
689  case CK_BuiltinFnToFnPtr:
690  llvm_unreachable("builtin functions are handled elsewhere");
691 
695  return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
696 
697  // These will never be supported.
699  case CK_ARCProduceObject:
700  case CK_ARCConsumeObject:
704  return nullptr;
705 
706  // These don't need to be handled here because Evaluate knows how to
707  // evaluate them in the cases where they can be folded.
708  case CK_BitCast:
709  case CK_ToVoid:
710  case CK_Dynamic:
711  case CK_LValueBitCast:
719  case CK_BaseToDerived:
720  case CK_DerivedToBase:
723  case CK_VectorSplat:
735  case CK_PointerToBoolean:
736  case CK_NullToPointer:
737  case CK_IntegralCast:
744  case CK_FloatingCast:
745  case CK_ZeroToOCLEvent:
746  return nullptr;
747  }
748  llvm_unreachable("Invalid CastKind");
749  }
750 
751  llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
752  return Visit(DAE->getExpr());
753  }
754 
755  llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
756  // No need for a DefaultInitExprScope: we don't handle 'this' in a
757  // constant expression.
758  return Visit(DIE->getExpr());
759  }
760 
761  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
762  return Visit(E->GetTemporaryExpr());
763  }
764 
765  llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
766  if (ILE->isStringLiteralInit())
767  return Visit(ILE->getInit(0));
768 
769  llvm::ArrayType *AType =
770  cast<llvm::ArrayType>(ConvertType(ILE->getType()));
771  llvm::Type *ElemTy = AType->getElementType();
772  unsigned NumInitElements = ILE->getNumInits();
773  unsigned NumElements = AType->getNumElements();
774 
775  // Initialising an array requires us to automatically
776  // initialise any elements that have not been initialised explicitly
777  unsigned NumInitableElts = std::min(NumInitElements, NumElements);
778 
779  // Initialize remaining array elements.
780  // FIXME: This doesn't handle member pointers correctly!
781  llvm::Constant *fillC;
782  if (Expr *filler = ILE->getArrayFiller())
783  fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
784  else
785  fillC = llvm::Constant::getNullValue(ElemTy);
786  if (!fillC)
787  return nullptr;
788 
789  // Try to use a ConstantAggregateZero if we can.
790  if (fillC->isNullValue() && !NumInitableElts)
791  return llvm::ConstantAggregateZero::get(AType);
792 
793  // Copy initializer elements.
794  std::vector<llvm::Constant*> Elts;
795  Elts.reserve(NumInitableElts + NumElements);
796 
797  bool RewriteType = false;
798  for (unsigned i = 0; i < NumInitableElts; ++i) {
799  Expr *Init = ILE->getInit(i);
800  llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
801  if (!C)
802  return nullptr;
803  RewriteType |= (C->getType() != ElemTy);
804  Elts.push_back(C);
805  }
806 
807  RewriteType |= (fillC->getType() != ElemTy);
808  Elts.resize(NumElements, fillC);
809 
810  if (RewriteType) {
811  // FIXME: Try to avoid packing the array
812  std::vector<llvm::Type*> Types;
813  Types.reserve(NumInitableElts + NumElements);
814  for (unsigned i = 0, e = Elts.size(); i < e; ++i)
815  Types.push_back(Elts[i]->getType());
816  llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
817  Types, true);
818  return llvm::ConstantStruct::get(SType, Elts);
819  }
820 
821  return llvm::ConstantArray::get(AType, Elts);
822  }
823 
824  llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
825  return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
826  }
827 
828  llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
829  return CGM.EmitNullConstant(E->getType());
830  }
831 
832  llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
833  if (ILE->getType()->isArrayType())
834  return EmitArrayInitialization(ILE);
835 
836  if (ILE->getType()->isRecordType())
837  return EmitRecordInitialization(ILE);
838 
839  return nullptr;
840  }
841 
842  llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
843  InitListExpr *Updater) {
844  QualType ExprType = Updater->getType();
845 
846  if (ExprType->isArrayType()) {
847  llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType));
848  llvm::Type *ElemType = AType->getElementType();
849 
850  unsigned NumInitElements = Updater->getNumInits();
851  unsigned NumElements = AType->getNumElements();
852 
853  std::vector<llvm::Constant *> Elts;
854  Elts.reserve(NumElements);
855 
856  if (llvm::ConstantDataArray *DataArray =
857  dyn_cast<llvm::ConstantDataArray>(Base))
858  for (unsigned i = 0; i != NumElements; ++i)
859  Elts.push_back(DataArray->getElementAsConstant(i));
860  else if (llvm::ConstantArray *Array =
861  dyn_cast<llvm::ConstantArray>(Base))
862  for (unsigned i = 0; i != NumElements; ++i)
863  Elts.push_back(Array->getOperand(i));
864  else
865  return nullptr; // FIXME: other array types not implemented
866 
867  llvm::Constant *fillC = nullptr;
868  if (Expr *filler = Updater->getArrayFiller())
869  if (!isa<NoInitExpr>(filler))
870  fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
871  bool RewriteType = (fillC && fillC->getType() != ElemType);
872 
873  for (unsigned i = 0; i != NumElements; ++i) {
874  Expr *Init = nullptr;
875  if (i < NumInitElements)
876  Init = Updater->getInit(i);
877 
878  if (!Init && fillC)
879  Elts[i] = fillC;
880  else if (!Init || isa<NoInitExpr>(Init))
881  ; // Do nothing.
882  else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
883  Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE);
884  else
885  Elts[i] = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
886 
887  if (!Elts[i])
888  return nullptr;
889  RewriteType |= (Elts[i]->getType() != ElemType);
890  }
891 
892  if (RewriteType) {
893  std::vector<llvm::Type *> Types;
894  Types.reserve(NumElements);
895  for (unsigned i = 0; i != NumElements; ++i)
896  Types.push_back(Elts[i]->getType());
897  llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
898  Types, true);
899  return llvm::ConstantStruct::get(SType, Elts);
900  }
901 
902  return llvm::ConstantArray::get(AType, Elts);
903  }
904 
905  if (ExprType->isRecordType())
906  return ConstStructBuilder::BuildStruct(CGM, CGF, this,
907  dyn_cast<llvm::ConstantStruct>(Base), Updater);
908 
909  return nullptr;
910  }
911 
912  llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
913  return EmitDesignatedInitUpdater(
914  CGM.EmitConstantExpr(E->getBase(), E->getType(), CGF),
915  E->getUpdater());
916  }
917 
918  llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
919  if (!E->getConstructor()->isTrivial())
920  return nullptr;
921 
922  QualType Ty = E->getType();
923 
924  // FIXME: We should not have to call getBaseElementType here.
925  const RecordType *RT =
927  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
928 
929  // If the class doesn't have a trivial destructor, we can't emit it as a
930  // constant expr.
931  if (!RD->hasTrivialDestructor())
932  return nullptr;
933 
934  // Only copy and default constructors can be trivial.
935 
936 
937  if (E->getNumArgs()) {
938  assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
939  assert(E->getConstructor()->isCopyOrMoveConstructor() &&
940  "trivial ctor has argument but isn't a copy/move ctor");
941 
942  Expr *Arg = E->getArg(0);
943  assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
944  "argument to copy ctor is of wrong type");
945 
946  return Visit(Arg);
947  }
948 
949  return CGM.EmitNullConstant(Ty);
950  }
951 
952  llvm::Constant *VisitStringLiteral(StringLiteral *E) {
953  return CGM.GetConstantArrayFromStringLiteral(E);
954  }
955 
956  llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
957  // This must be an @encode initializing an array in a static initializer.
958  // Don't emit it as the address of the string, emit the string data itself
959  // as an inline array.
960  std::string Str;
962  QualType T = E->getType();
963  if (T->getTypeClass() == Type::TypeOfExpr)
964  T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
965  const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
966 
967  // Resize the string to the right size, adding zeros at the end, or
968  // truncating as needed.
969  Str.resize(CAT->getSize().getZExtValue(), '\0');
970  return llvm::ConstantDataArray::getString(VMContext, Str, false);
971  }
972 
973  llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
974  return Visit(E->getSubExpr());
975  }
976 
977  // Utility methods
978  llvm::Type *ConvertType(QualType T) {
979  return CGM.getTypes().ConvertType(T);
980  }
981 
982 public:
983  ConstantAddress EmitLValue(APValue::LValueBase LVBase) {
984  if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
985  if (Decl->hasAttr<WeakRefAttr>())
986  return CGM.GetWeakRefReference(Decl);
987  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
989  if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
990  // We can never refer to a variable with local storage.
991  if (!VD->hasLocalStorage()) {
992  CharUnits Align = CGM.getContext().getDeclAlign(VD);
993  if (VD->isFileVarDecl() || VD->hasExternalStorage())
994  return ConstantAddress(CGM.GetAddrOfGlobalVar(VD), Align);
995  else if (VD->isLocalVarDecl()) {
996  auto Ptr = CGM.getOrCreateStaticVarDecl(
997  *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
998  return ConstantAddress(Ptr, Align);
999  }
1000  }
1001  }
1002  return ConstantAddress::invalid();
1003  }
1004 
1005  Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
1006  switch (E->getStmtClass()) {
1007  default: break;
1008  case Expr::CompoundLiteralExprClass: {
1009  // Note that due to the nature of compound literals, this is guaranteed
1010  // to be the only use of the variable, so we just generate it here.
1011  CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1012  llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
1013  CLE->getType(), CGF);
1014  // FIXME: "Leaked" on failure.
1015  if (!C) return ConstantAddress::invalid();
1016 
1017  CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
1018 
1019  auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1020  E->getType().isConstant(CGM.getContext()),
1022  C, ".compoundliteral", nullptr,
1023  llvm::GlobalVariable::NotThreadLocal,
1025  GV->setAlignment(Align.getQuantity());
1026  return ConstantAddress(GV, Align);
1027  }
1028  case Expr::StringLiteralClass:
1029  return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
1030  case Expr::ObjCEncodeExprClass:
1031  return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
1032  case Expr::ObjCStringLiteralClass: {
1033  ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
1034  ConstantAddress C =
1036  return C.getElementBitCast(ConvertType(E->getType()));
1037  }
1038  case Expr::PredefinedExprClass: {
1039  unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
1040  if (CGF) {
1041  LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
1042  return cast<ConstantAddress>(Res.getAddress());
1043  } else if (Type == PredefinedExpr::PrettyFunction) {
1044  return CGM.GetAddrOfConstantCString("top level", ".tmp");
1045  }
1046 
1047  return CGM.GetAddrOfConstantCString("", ".tmp");
1048  }
1049  case Expr::AddrLabelExprClass: {
1050  assert(CGF && "Invalid address of label expression outside function.");
1051  llvm::Constant *Ptr =
1052  CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
1053  Ptr = llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
1054  return ConstantAddress(Ptr, CharUnits::One());
1055  }
1056  case Expr::CallExprClass: {
1057  CallExpr* CE = cast<CallExpr>(E);
1058  unsigned builtin = CE->getBuiltinCallee();
1059  if (builtin !=
1060  Builtin::BI__builtin___CFStringMakeConstantString &&
1061  builtin !=
1062  Builtin::BI__builtin___NSStringMakeConstantString)
1063  break;
1064  const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
1065  const StringLiteral *Literal = cast<StringLiteral>(Arg);
1066  if (builtin ==
1067  Builtin::BI__builtin___NSStringMakeConstantString) {
1068  return CGM.getObjCRuntime().GenerateConstantString(Literal);
1069  }
1070  // FIXME: need to deal with UCN conversion issues.
1071  return CGM.GetAddrOfConstantCFString(Literal);
1072  }
1073  case Expr::BlockExprClass: {
1074  std::string FunctionName;
1075  if (CGF)
1076  FunctionName = CGF->CurFn->getName();
1077  else
1078  FunctionName = "global";
1079 
1080  // This is not really an l-value.
1081  llvm::Constant *Ptr =
1082  CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
1083  return ConstantAddress(Ptr, CGM.getPointerAlign());
1084  }
1085  case Expr::CXXTypeidExprClass: {
1086  CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
1087  QualType T;
1088  if (Typeid->isTypeOperand())
1089  T = Typeid->getTypeOperand(CGM.getContext());
1090  else
1091  T = Typeid->getExprOperand()->getType();
1093  CGM.getPointerAlign());
1094  }
1095  case Expr::CXXUuidofExprClass: {
1096  return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
1097  }
1098  case Expr::MaterializeTemporaryExprClass: {
1099  MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
1100  assert(MTE->getStorageDuration() == SD_Static);
1101  SmallVector<const Expr *, 2> CommaLHSs;
1103  const Expr *Inner = MTE->GetTemporaryExpr()
1104  ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1105  return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
1106  }
1107  }
1108 
1109  return ConstantAddress::invalid();
1110  }
1111 };
1112 
1113 } // end anonymous namespace.
1114 
1115 bool ConstStructBuilder::Build(ConstExprEmitter *Emitter,
1116  llvm::ConstantStruct *Base,
1117  InitListExpr *Updater) {
1118  assert(Base && "base expression should not be empty");
1119 
1120  QualType ExprType = Updater->getType();
1121  RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1122  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1123  const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1124  Base->getType());
1125  unsigned FieldNo = -1;
1126  unsigned ElementNo = 0;
1127 
1128  for (FieldDecl *Field : RD->fields()) {
1129  ++FieldNo;
1130 
1131  if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1132  continue;
1133 
1134  // Skip anonymous bitfields.
1135  if (Field->isUnnamedBitfield())
1136  continue;
1137 
1138  llvm::Constant *EltInit = Base->getOperand(ElementNo);
1139 
1140  // Bail out if the type of the ConstantStruct does not have the same layout
1141  // as the type of the InitListExpr.
1142  if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1143  Layout.getFieldOffset(ElementNo) !=
1144  BaseLayout->getElementOffsetInBits(ElementNo))
1145  return false;
1146 
1147  // Get the initializer. If we encounter an empty field or a NoInitExpr,
1148  // we use values from the base expression.
1149  Expr *Init = nullptr;
1150  if (ElementNo < Updater->getNumInits())
1151  Init = Updater->getInit(ElementNo);
1152 
1153  if (!Init || isa<NoInitExpr>(Init))
1154  ; // Do nothing.
1155  else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1156  EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE);
1157  else
1158  EltInit = CGM.EmitConstantExpr(Init, Field->getType(), CGF);
1159 
1160  ++ElementNo;
1161 
1162  if (!EltInit)
1163  return false;
1164 
1165  if (!Field->isBitField())
1166  AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1167  else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1168  AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1169  else
1170  // Initializing a bitfield with a non-trivial constant?
1171  return false;
1172  }
1173 
1174  return true;
1175 }
1176 
1177 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
1178  CodeGenFunction *CGF) {
1179  // Make a quick check if variable can be default NULL initialized
1180  // and avoid going through rest of code which may do, for c++11,
1181  // initialization of memory to all NULLs.
1182  if (!D.hasLocalStorage()) {
1183  QualType Ty = D.getType();
1184  if (Ty->isArrayType())
1185  Ty = Context.getBaseElementType(Ty);
1186  if (Ty->isRecordType())
1187  if (const CXXConstructExpr *E =
1188  dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1189  const CXXConstructorDecl *CD = E->getConstructor();
1190  if (CD->isTrivial() && CD->isDefaultConstructor())
1191  return EmitNullConstant(D.getType());
1192  }
1193  }
1194 
1195  if (const APValue *Value = D.evaluateValue())
1196  return EmitConstantValueForMemory(*Value, D.getType(), CGF);
1197 
1198  // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1199  // reference is a constant expression, and the reference binds to a temporary,
1200  // then constant initialization is performed. ConstExprEmitter will
1201  // incorrectly emit a prvalue constant in this case, and the calling code
1202  // interprets that as the (pointer) value of the reference, rather than the
1203  // desired value of the referee.
1204  if (D.getType()->isReferenceType())
1205  return nullptr;
1206 
1207  const Expr *E = D.getInit();
1208  assert(E && "No initializer to emit");
1209 
1210  llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1211  if (C && C->getType()->isIntegerTy(1)) {
1212  llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1213  C = llvm::ConstantExpr::getZExt(C, BoolTy);
1214  }
1215  return C;
1216 }
1217 
1218 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
1219  QualType DestType,
1220  CodeGenFunction *CGF) {
1221  Expr::EvalResult Result;
1222 
1223  bool Success = false;
1224 
1225  if (DestType->isReferenceType())
1226  Success = E->EvaluateAsLValue(Result, Context);
1227  else
1228  Success = E->EvaluateAsRValue(Result, Context);
1229 
1230  llvm::Constant *C = nullptr;
1231  if (Success && !Result.HasSideEffects)
1232  C = EmitConstantValue(Result.Val, DestType, CGF);
1233  else
1234  C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1235 
1236  if (C && C->getType()->isIntegerTy(1)) {
1237  llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1238  C = llvm::ConstantExpr::getZExt(C, BoolTy);
1239  }
1240  return C;
1241 }
1242 
1244  QualType DestType,
1245  CodeGenFunction *CGF) {
1246  // For an _Atomic-qualified constant, we may need to add tail padding.
1247  if (auto *AT = DestType->getAs<AtomicType>()) {
1248  QualType InnerType = AT->getValueType();
1249  auto *Inner = EmitConstantValue(Value, InnerType, CGF);
1250 
1251  uint64_t InnerSize = Context.getTypeSize(InnerType);
1252  uint64_t OuterSize = Context.getTypeSize(DestType);
1253  if (InnerSize == OuterSize)
1254  return Inner;
1255 
1256  assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
1257  llvm::Constant *Elts[] = {
1258  Inner,
1259  llvm::ConstantAggregateZero::get(
1260  llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
1261  };
1262  return llvm::ConstantStruct::getAnon(Elts);
1263  }
1264 
1265  switch (Value.getKind()) {
1267  llvm_unreachable("Constant expressions should be initialized.");
1268  case APValue::LValue: {
1269  llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
1270  llvm::Constant *Offset =
1271  llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
1272 
1273  llvm::Constant *C = nullptr;
1274  if (APValue::LValueBase LVBase = Value.getLValueBase()) {
1275  // An array can be represented as an lvalue referring to the base.
1276  if (isa<llvm::ArrayType>(DestTy)) {
1277  assert(Offset->isNullValue() && "offset on array initializer");
1278  return ConstExprEmitter(*this, CGF).Visit(
1279  const_cast<Expr*>(LVBase.get<const Expr*>()));
1280  }
1281 
1282  C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase).getPointer();
1283 
1284  // Apply offset if necessary.
1285  if (!Offset->isNullValue()) {
1286  unsigned AS = C->getType()->getPointerAddressSpace();
1287  llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
1288  llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
1289  Casted = llvm::ConstantExpr::getGetElementPtr(Int8Ty, Casted, Offset);
1290  C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
1291  }
1292 
1293  // Convert to the appropriate type; this could be an lvalue for
1294  // an integer.
1295  if (isa<llvm::PointerType>(DestTy))
1296  return llvm::ConstantExpr::getPointerCast(C, DestTy);
1297 
1298  return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1299  } else {
1300  C = Offset;
1301 
1302  // Convert to the appropriate type; this could be an lvalue for
1303  // an integer.
1304  if (isa<llvm::PointerType>(DestTy))
1305  return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1306 
1307  // If the types don't match this should only be a truncate.
1308  if (C->getType() != DestTy)
1309  return llvm::ConstantExpr::getTrunc(C, DestTy);
1310 
1311  return C;
1312  }
1313  }
1314  case APValue::Int:
1315  return llvm::ConstantInt::get(VMContext, Value.getInt());
1316  case APValue::ComplexInt: {
1317  llvm::Constant *Complex[2];
1318 
1319  Complex[0] = llvm::ConstantInt::get(VMContext,
1320  Value.getComplexIntReal());
1321  Complex[1] = llvm::ConstantInt::get(VMContext,
1322  Value.getComplexIntImag());
1323 
1324  // FIXME: the target may want to specify that this is packed.
1325  llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1326  Complex[1]->getType(),
1327  nullptr);
1328  return llvm::ConstantStruct::get(STy, Complex);
1329  }
1330  case APValue::Float: {
1331  const llvm::APFloat &Init = Value.getFloat();
1332  if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
1333  !Context.getLangOpts().NativeHalfType &&
1334  !Context.getLangOpts().HalfArgsAndReturns)
1335  return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1336  else
1337  return llvm::ConstantFP::get(VMContext, Init);
1338  }
1339  case APValue::ComplexFloat: {
1340  llvm::Constant *Complex[2];
1341 
1342  Complex[0] = llvm::ConstantFP::get(VMContext,
1343  Value.getComplexFloatReal());
1344  Complex[1] = llvm::ConstantFP::get(VMContext,
1345  Value.getComplexFloatImag());
1346 
1347  // FIXME: the target may want to specify that this is packed.
1348  llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1349  Complex[1]->getType(),
1350  nullptr);
1351  return llvm::ConstantStruct::get(STy, Complex);
1352  }
1353  case APValue::Vector: {
1354  unsigned NumElts = Value.getVectorLength();
1356 
1357  for (unsigned I = 0; I != NumElts; ++I) {
1358  const APValue &Elt = Value.getVectorElt(I);
1359  if (Elt.isInt())
1360  Inits[I] = llvm::ConstantInt::get(VMContext, Elt.getInt());
1361  else if (Elt.isFloat())
1362  Inits[I] = llvm::ConstantFP::get(VMContext, Elt.getFloat());
1363  else
1364  llvm_unreachable("unsupported vector element type");
1365  }
1366  return llvm::ConstantVector::get(Inits);
1367  }
1368  case APValue::AddrLabelDiff: {
1369  const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1370  const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1371  llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
1372  llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
1373 
1374  // Compute difference
1375  llvm::Type *ResultType = getTypes().ConvertType(DestType);
1376  LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
1377  RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
1378  llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1379 
1380  // LLVM is a bit sensitive about the exact format of the
1381  // address-of-label difference; make sure to truncate after
1382  // the subtraction.
1383  return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1384  }
1385  case APValue::Struct:
1386  case APValue::Union:
1387  return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
1388  case APValue::Array: {
1389  const ArrayType *CAT = Context.getAsArrayType(DestType);
1390  unsigned NumElements = Value.getArraySize();
1391  unsigned NumInitElts = Value.getArrayInitializedElts();
1392 
1393  // Emit array filler, if there is one.
1394  llvm::Constant *Filler = nullptr;
1395  if (Value.hasArrayFiller())
1396  Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
1397  CAT->getElementType(), CGF);
1398 
1399  // Emit initializer elements.
1400  llvm::Type *CommonElementType =
1402 
1403  // Try to use a ConstantAggregateZero if we can.
1404  if (Filler && Filler->isNullValue() && !NumInitElts) {
1405  llvm::ArrayType *AType =
1406  llvm::ArrayType::get(CommonElementType, NumElements);
1407  return llvm::ConstantAggregateZero::get(AType);
1408  }
1409 
1410  std::vector<llvm::Constant*> Elts;
1411  Elts.reserve(NumElements);
1412  for (unsigned I = 0; I < NumElements; ++I) {
1413  llvm::Constant *C = Filler;
1414  if (I < NumInitElts)
1416  CAT->getElementType(), CGF);
1417  else
1418  assert(Filler && "Missing filler for implicit elements of initializer");
1419  if (I == 0)
1420  CommonElementType = C->getType();
1421  else if (C->getType() != CommonElementType)
1422  CommonElementType = nullptr;
1423  Elts.push_back(C);
1424  }
1425 
1426  if (!CommonElementType) {
1427  // FIXME: Try to avoid packing the array
1428  std::vector<llvm::Type*> Types;
1429  Types.reserve(NumElements);
1430  for (unsigned i = 0, e = Elts.size(); i < e; ++i)
1431  Types.push_back(Elts[i]->getType());
1432  llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
1433  return llvm::ConstantStruct::get(SType, Elts);
1434  }
1435 
1436  llvm::ArrayType *AType =
1437  llvm::ArrayType::get(CommonElementType, NumElements);
1438  return llvm::ConstantArray::get(AType, Elts);
1439  }
1441  return getCXXABI().EmitMemberPointer(Value, DestType);
1442  }
1443  llvm_unreachable("Unknown APValue kind");
1444 }
1445 
1446 llvm::Constant *
1448  QualType DestType,
1449  CodeGenFunction *CGF) {
1450  llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
1451  if (C->getType()->isIntegerTy(1)) {
1452  llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
1453  C = llvm::ConstantExpr::getZExt(C, BoolTy);
1454  }
1455  return C;
1456 }
1457 
1460  assert(E->isFileScope() && "not a file-scope compound literal expr");
1461  return ConstExprEmitter(*this, nullptr).EmitLValue(E);
1462 }
1463 
1464 llvm::Constant *
1466  // Member pointer constants always have a very particular form.
1467  const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1468  const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1469 
1470  // A member function pointer.
1471  if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1472  return getCXXABI().EmitMemberFunctionPointer(method);
1473 
1474  // Otherwise, a member data pointer.
1475  uint64_t fieldOffset = getContext().getFieldOffset(decl);
1476  CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1477  return getCXXABI().EmitMemberDataPointer(type, chars);
1478 }
1479 
1480 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1481  llvm::Type *baseType,
1482  const CXXRecordDecl *base);
1483 
1484 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
1485  const CXXRecordDecl *record,
1486  bool asCompleteObject) {
1487  const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1488  llvm::StructType *structure =
1489  (asCompleteObject ? layout.getLLVMType()
1490  : layout.getBaseSubobjectLLVMType());
1491 
1492  unsigned numElements = structure->getNumElements();
1493  std::vector<llvm::Constant *> elements(numElements);
1494 
1495  // Fill in all the bases.
1496  for (const auto &I : record->bases()) {
1497  if (I.isVirtual()) {
1498  // Ignore virtual bases; if we're laying out for a complete
1499  // object, we'll lay these out later.
1500  continue;
1501  }
1502 
1503  const CXXRecordDecl *base =
1504  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1505 
1506  // Ignore empty bases.
1507  if (base->isEmpty())
1508  continue;
1509 
1510  unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
1511  llvm::Type *baseType = structure->getElementType(fieldIndex);
1512  elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1513  }
1514 
1515  // Fill in all the fields.
1516  for (const auto *Field : record->fields()) {
1517  // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1518  // will fill in later.)
1519  if (!Field->isBitField()) {
1520  unsigned fieldIndex = layout.getLLVMFieldNo(Field);
1521  elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
1522  }
1523 
1524  // For unions, stop after the first named field.
1525  if (record->isUnion()) {
1526  if (Field->getIdentifier())
1527  break;
1528  if (const auto *FieldRD =
1529  dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl()))
1530  if (FieldRD->findFirstNamedDataMember())
1531  break;
1532  }
1533  }
1534 
1535  // Fill in the virtual bases, if we're working with the complete object.
1536  if (asCompleteObject) {
1537  for (const auto &I : record->vbases()) {
1538  const CXXRecordDecl *base =
1539  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1540 
1541  // Ignore empty bases.
1542  if (base->isEmpty())
1543  continue;
1544 
1545  unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1546 
1547  // We might have already laid this field out.
1548  if (elements[fieldIndex]) continue;
1549 
1550  llvm::Type *baseType = structure->getElementType(fieldIndex);
1551  elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1552  }
1553  }
1554 
1555  // Now go through all other fields and zero them out.
1556  for (unsigned i = 0; i != numElements; ++i) {
1557  if (!elements[i])
1558  elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
1559  }
1560 
1561  return llvm::ConstantStruct::get(structure, elements);
1562 }
1563 
1564 /// Emit the null constant for a base subobject.
1565 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1566  llvm::Type *baseType,
1567  const CXXRecordDecl *base) {
1568  const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1569 
1570  // Just zero out bases that don't have any pointer to data members.
1571  if (baseLayout.isZeroInitializableAsBase())
1572  return llvm::Constant::getNullValue(baseType);
1573 
1574  // Otherwise, we can just use its null constant.
1575  return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
1576 }
1577 
1579  if (getTypes().isZeroInitializable(T))
1580  return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
1581 
1582  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
1583  llvm::ArrayType *ATy =
1584  cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1585 
1586  QualType ElementTy = CAT->getElementType();
1587 
1588  llvm::Constant *Element = EmitNullConstant(ElementTy);
1589  unsigned NumElements = CAT->getSize().getZExtValue();
1590  SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
1591  return llvm::ConstantArray::get(ATy, Array);
1592  }
1593 
1594  if (const RecordType *RT = T->getAs<RecordType>()) {
1595  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1596  return ::EmitNullConstant(*this, RD, /*complete object*/ true);
1597  }
1598 
1599  assert(T->isMemberDataPointerType() &&
1600  "Should only see pointers to data members here!");
1601 
1603 }
1604 
1605 llvm::Constant *
1607  return ::EmitNullConstant(*this, Record, false);
1608 }
Defines the clang::ASTContext interface.
unsigned getNumInits() const
Definition: Expr.h:3754
CastKind getCastKind() const
Definition: Expr.h:2658
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
Definition: CGCXXABI.cpp:147
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
CK_LValueToRValue - A conversion which causes the extraction of an r-value from the operand gl-value...
const FieldDecl * getUnionField() const
Definition: APValue.h:322
bool isFileScope() const
Definition: Expr.h:2570
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2140
A (possibly-)qualified type.
Definition: Type.h:575
Static storage duration.
Definition: Specifiers.h:266
base_class_range bases()
Definition: DeclCXX.h:713
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2199
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2277
llvm::Module & getModule() const
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
llvm::Constant * getMemberPointerConstant(const UnaryOperator *e)
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:164
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:3905
#define trunc(__x)
Definition: tgmath.h:1223
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:171
bool isRecordType() const
Definition: Type.h:5362
CK_ToUnion - The GCC cast-to-union extension.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
Address getAddress() const
Definition: CGValue.h:331
bool hasFlexibleArrayMember() const
Definition: Decl.h:3218
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1605
const llvm::DataLayout & getDataLayout() const
The base class of the type hierarchy.
Definition: Type.h:1249
CK_BaseToDerivedMemberPointer - Member pointer in base class to member pointer in derived class...
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2424
const Expr * getResultExpr() const
The generic selection's result expression.
Definition: Expr.h:4494
const Expr * getInit() const
Definition: Decl.h:1070
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1149
CK_FloatingToIntegral - Floating point to integral.
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
[ARC] Consumes a retainable object pointer that has just been produced, e.g.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2134
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:3864
llvm::Constant * EmitConstantValue(const APValue &Value, QualType DestType, CodeGenFunction *CGF=nullptr)
Emit the given constant value as a constant, in the type's scalar representation. ...
const llvm::APInt & getSize() const
Definition: Type.h:2495
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
CK_IntegralToFloating - Integral to floating point.
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
CK_IntegralCast - A cast between integral types (other than to boolean).
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2540
APFloat & getComplexFloatReal()
Definition: APValue.h:232
field_iterator field_begin() const
Definition: Decl.cpp:3746
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr)
Return the llvm::Constant for the address of the given global variable.
CK_Dynamic - A C++ dynamic_cast.
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:1802
CK_Dependent - A conversion which cannot yet be analyzed because either the expression or target type...
bool isMemberDataPointerType() const
Definition: Type.h:5338
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool isUnionType() const
Definition: Type.cpp:391
llvm::Constant * EmitConstantValueForMemory(const APValue &Value, QualType DestType, CodeGenFunction *CGF=nullptr)
Emit the given constant value as a constant, in the type's memory representation. ...
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1144
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:1526
bool hasAttr() const
Definition: DeclBase.h:498
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
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:91
Converts between different integral complex types.
bool isReferenceType() const
Definition: Type.h:5314
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2209
StringLiteral * getString()
Definition: ExprObjC.h:40
Converting between two Objective-C object types, which can occur when performing reference binding to...
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:259
CK_FloatingCast - Casting between floating types of different size.
[ARC] Causes a value of block type to be copied to the heap, if it is not already there...
CK_VectorSplat - A conversion from an arithmetic type to a vector of that element type...
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Expr * getSubExpr()
Definition: Expr.h:2662
CK_NullToPointer - Null pointer constant to pointer, ObjC pointer, or block pointer.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1987
CK_PointerToIntegral - Pointer to integral.
CK_IntegralToPointer - Integral to pointer.
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
Converts a floating point complex to bool by comparing against 0+0i.
unsigned getVirtualBaseIndex(const CXXRecordDecl *base) const
Return the LLVM field index corresponding to the given virtual base.
Describes an C or C++ initializer list.
Definition: Expr.h:3724
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:559
CK_IntegralToBoolean - Integral to boolean.
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition: Expr.h:3566
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:580
const LangOptions & getLangOpts() const
Definition: ASTContext.h:596
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:563
uint32_t Offset
Definition: CacheTokens.cpp:44
bool isZeroInitializableAsBase() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer when considered as a bas...
Expr * getExprOperand() const
Definition: ExprCXX.h:614
field_range fields() const
Definition: Decl.h:3295
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
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:54
RecordDecl * getDecl() const
Definition: Type.h:3553
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2464
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:29
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:181
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2610
TypeClass getTypeClass() const
Definition: Type.h:1501
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1245
detail::InMemoryDirectory::const_iterator I
APSInt & getComplexIntReal()
Definition: APValue.h:216
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:954
QualType getType() const
Definition: Decl.h:530
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2283
field_iterator field_end() const
Definition: Decl.h:3298
APValue & getVectorElt(unsigned I)
Definition: APValue.h:258
CK_AnyPointerToBlockPointerCast - Casting any non-block pointer to a block pointer.
bool isUnion() const
Definition: Decl.h:2856
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
Causes a block literal to by copied to the heap and then autoreleased.
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...
APValue & getArrayFiller()
Definition: APValue.h:282
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.
ASTContext * Context
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1049
CK_FunctionToPointerDecay - Function to pointer decay.
Converts between different floating point complex types.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
unsigned getArrayInitializedElts() const
Definition: APValue.h:290
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
Expr - This represents one expression.
Definition: Expr.h:104
CK_PointerToBoolean - Pointer to boolean conversion.
Converts an integral complex to an integral real of the source's element type by discarding the imagi...
CK_BitCast - A conversion which causes a bit pattern of one type to be reinterpreted as a bit pattern...
CFG - Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
Definition: CFG.h:721
CGCXXABI & getCXXABI() const
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:3908
Inits[]
Definition: OpenMPClause.h:310
ASTContext & getContext() const
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:224
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
Expr * getSubExpr() const
Definition: Expr.h:1681
CK_ConstructorConversion - Conversion by constructor.
APValue & getStructField(unsigned i)
Definition: APValue.h:311
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:137
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
Converts from an integral complex to a floating complex.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1654
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3669
APSInt & getComplexIntImag()
Definition: APValue.h:224
The result type of a method or function.
CK_ArrayToPointerDecay - Array to pointer decay.
InitListExpr * getUpdater() const
Definition: Expr.h:4308
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
The l-value was considered opaque, so the alignment was determined from a type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
APValue & getStructBase(unsigned i)
Definition: APValue.h:307
CK_CPointerToObjCPointerCast - Casting a C pointer kind to an Objective-C pointer.
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:177
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:271
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:102
#define false
Definition: stdbool.h:33
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CK_UserDefinedConversion - Conversion using a user defined type conversion function.
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:174
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3463
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:209
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
const AddrLabelExpr * getAddrLabelDiffLHS() const
Definition: APValue.h:338
APValue & getUnionValue()
Definition: APValue.h:326
bool isConstant(ASTContext &Ctx) const
Definition: Type.h:712
CK_NullToMemberPointer - Null pointer constant to member pointer.
ValueKind getKind() const
Definition: APValue.h:180
APFloat & getFloat()
Definition: APValue.h:208
ConstantAddress getElementBitCast(llvm::Type *ty) const
Definition: Address.h:93
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
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:178
CK_ReinterpretMemberPointer - Reinterpret a member pointer as a different kind of member pointer...
CK_DerivedToBase - A conversion from a C++ class pointer to a base class pointer. ...
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
Return a null constant appropriate for zero-initializing a base class with the given type...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2094
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
Converts from an integral real to an integral complex whose element type matches the source...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
const AddrLabelExpr * getAddrLabelDiffRHS() const
Definition: APValue.h:342
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:133
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:3809
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character...
Represents a C11 generic selection.
Definition: Expr.h:4426
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3317
QualType getType() const
Definition: Expr.h:125
Converts a floating point complex to floating point real of the source's element type.
This class organizes the cross-function state that is used while generating LLVM code.
const Expr * getExpr() const
Definition: ExprCXX.h:985
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:43
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:561
Converts an integral complex to bool by comparing against 0+0i.
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1723
unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const
CK_BaseToDerived - A conversion from a C++ class pointer/reference to a derived class pointer/referen...
static llvm::Constant * EmitNullConstantForBase(CodeGenModule &CGM, llvm::Type *baseType, const CXXRecordDecl *base)
Emit the null constant for a base subobject.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
CK_BlockPointerToObjCPointerCast - Casting a block pointer to an ObjC pointer.
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
A conversion of a floating point real to a floating point complex of the original type...
CK_MemberPointerToBoolean - Member pointer to boolean.
unsigned getNumArgs() const
Definition: ExprCXX.h:1272
bool isFloat() const
Definition: APValue.h:183
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:1459
[ARC] Reclaim a retainable object pointer object that may have been produced and autoreleased as part...
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:779
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:534
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
llvm::PointerUnion< const ValueDecl *, const Expr * > LValueBase
Definition: APValue.h:56
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:355
[ARC] Produces a retainable object pointer so that it may be consumed, e.g.
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:142
CK_LValueBitCast - A conversion which reinterprets the address of an l-value as an l-value of a diffe...
Converts from T to _Atomic(T).
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1275
CXXConstructorDecl * getConstructor() const
Definition: ExprCXX.h:1211
llvm::Constant * GetAddrOfGlobalBlock(const BlockExpr *BE, const char *)
Gets the address of a block which requires no captures.
Definition: CGBlocks.cpp:1033
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1759
Converts from a floating complex to an integral complex.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:1797
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
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:157
const Expr * getInitializer() const
Definition: Expr.h:2566
CK_UncheckedDerivedToBase - A conversion from a C++ class pointer/reference to a base class that can ...
llvm::Constant * EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF=nullptr)
Try to emit the initializer for the given declaration as a constant; returns 0 if the expression cann...
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:1782
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1024
const Expr * getSubExpr() const
Definition: Expr.h:1621
APFloat & getComplexFloatImag()
Definition: APValue.h:240
const LValueBase getLValueBase() const
Definition: APValue.cpp:553
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
QualType getEncodedType() const
Definition: ExprObjC.h:376
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3525
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:75
Converts from _Atomic(T) to T.
bool isArrayType() const
Definition: Type.h:5344
LValue EmitPredefinedLValue(const PredefinedExpr *E)
Definition: CGExpr.cpp:2245
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1452
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2134
static ConstantAddress invalid()
Definition: Address.h:80
bool isInt() const
Definition: APValue.h:182
bool isStringLiteralInit() const
Definition: Expr.cpp:1957
Expr * getBase() const
Definition: Expr.h:4305
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2180
CK_NoOp - A conversion which does not affect the type other than (possibly) adding qualifiers...
CK_DerivedToBaseMemberPointer - Member pointer in derived class to member pointer in base class...
QualType getElementType() const
Definition: Type.h:2458
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3763
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:3827
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
static llvm::Constant * EmitNullConstant(CodeGenModule &CGM, const CXXRecordDecl *record, bool asCompleteObject)
LValue - This represents an lvalue references.
Definition: CGValue.h:152
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
APSInt & getInt()
Definition: APValue.h:200
unsigned getArraySize() const
Definition: APValue.h:294
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 ...
bool isTypeOperand() const
Definition: ExprCXX.h:597
llvm::StructType * getBaseSubobjectLLVMType() const
Return the "base subobject" LLVM type associated with this record.
CK_ToVoid - Cast to void, discarding the computed value.
CharUnits RoundUpToAlignment(const CharUnits &Align) const
RoundUpToAlignment - Returns the next integer (mod 2**64) that is greater than or equal to this quant...
Definition: CharUnits.h:176
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, bool IsForDefinition=false)
Return the address of the given function.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
base_class_range vbases()
Definition: DeclCXX.h:730
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
unsigned getVectorLength() const
Definition: APValue.h:266
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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:4328
bool hasLocalStorage() const
hasLocalStorage - Returns true if a variable with function scope is a non-static local variable...
Definition: Decl.h:891
bool hasArrayFiller() const
Definition: APValue.h:279
CharUnits & getLValueOffset()
Definition: APValue.cpp:563
CK_FloatingToBoolean - Floating point to boolean.