clang  6.0.0
CGExpr.cpp
Go to the documentation of this file.
1 //===--- CGExpr.cpp - Emit LLVM Code from 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 Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGCXXABI.h"
15 #include "CGCall.h"
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenModule.h"
23 #include "ConstantEmitter.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/Attr.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/NSAPI.h"
30 #include "llvm/ADT/Hashing.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/MDBuilder.h"
36 #include "llvm/Support/ConvertUTF.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Transforms/Utils/SanitizerStats.h"
40 
41 #include <string>
42 
43 using namespace clang;
44 using namespace CodeGen;
45 
46 //===--------------------------------------------------------------------===//
47 // Miscellaneous Helper Methods
48 //===--------------------------------------------------------------------===//
49 
51  unsigned addressSpace =
52  cast<llvm::PointerType>(value->getType())->getAddressSpace();
53 
54  llvm::PointerType *destType = Int8PtrTy;
55  if (addressSpace)
56  destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57 
58  if (value->getType() == destType) return value;
59  return Builder.CreateBitCast(value, destType);
60 }
61 
62 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
63 /// block.
65  const Twine &Name,
66  llvm::Value *ArraySize,
67  bool CastToDefaultAddrSpace) {
68  auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
69  Alloca->setAlignment(Align.getQuantity());
70  llvm::Value *V = Alloca;
71  // Alloca always returns a pointer in alloca address space, which may
72  // be different from the type defined by the language. For example,
73  // in C++ the auto variables are in the default address space. Therefore
74  // cast alloca to the default address space when necessary.
75  if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76  auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
77  llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
78  // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
79  // otherwise alloca is inserted at the current insertion point of the
80  // builder.
81  if (!ArraySize)
82  Builder.SetInsertPoint(AllocaInsertPt);
85  Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
86  }
87 
88  return Address(V, Align);
89 }
90 
91 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
92 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
93 /// insertion point of the builder.
95  const Twine &Name,
96  llvm::Value *ArraySize) {
97  if (ArraySize)
98  return Builder.CreateAlloca(Ty, ArraySize, Name);
99  return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
100  ArraySize, Name, AllocaInsertPt);
101 }
102 
103 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
104 /// default alignment of the corresponding LLVM type, which is *not*
105 /// guaranteed to be related in any way to the expected alignment of
106 /// an AST type that might have been lowered to Ty.
108  const Twine &Name) {
109  CharUnits Align =
110  CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
111  return CreateTempAlloca(Ty, Align, Name);
112 }
113 
115  assert(isa<llvm::AllocaInst>(Var.getPointer()));
116  auto *Store = new llvm::StoreInst(Init, Var.getPointer());
117  Store->setAlignment(Var.getAlignment().getQuantity());
118  llvm::BasicBlock *Block = AllocaInsertPt->getParent();
119  Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
120 }
121 
124  return CreateTempAlloca(ConvertType(Ty), Align, Name);
125 }
126 
128  bool CastToDefaultAddrSpace) {
129  // FIXME: Should we prefer the preferred type alignment here?
130  return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
131  CastToDefaultAddrSpace);
132 }
133 
135  const Twine &Name,
136  bool CastToDefaultAddrSpace) {
137  return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
138  CastToDefaultAddrSpace);
139 }
140 
141 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
142 /// expression and compare the result against zero, returning an Int1Ty value.
144  PGO.setCurrentStmt(E);
145  if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
146  llvm::Value *MemPtr = EmitScalarExpr(E);
147  return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
148  }
149 
150  QualType BoolTy = getContext().BoolTy;
151  SourceLocation Loc = E->getExprLoc();
152  if (!E->getType()->isAnyComplexType())
153  return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
154 
155  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
156  Loc);
157 }
158 
159 /// EmitIgnoredExpr - Emit code to compute the specified expression,
160 /// ignoring the result.
162  if (E->isRValue())
163  return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
164 
165  // Just emit it as an l-value and drop the result.
166  EmitLValue(E);
167 }
168 
169 /// EmitAnyExpr - Emit code to compute the specified expression which
170 /// can have any type. The result is returned as an RValue struct.
171 /// If this is an aggregate expression, AggSlot indicates where the
172 /// result should be returned.
174  AggValueSlot aggSlot,
175  bool ignoreResult) {
176  switch (getEvaluationKind(E->getType())) {
177  case TEK_Scalar:
178  return RValue::get(EmitScalarExpr(E, ignoreResult));
179  case TEK_Complex:
180  return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
181  case TEK_Aggregate:
182  if (!ignoreResult && aggSlot.isIgnored())
183  aggSlot = CreateAggTemp(E->getType(), "agg-temp");
184  EmitAggExpr(E, aggSlot);
185  return aggSlot.asRValue();
186  }
187  llvm_unreachable("bad evaluation kind");
188 }
189 
190 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
191 /// always be accessible even if no aggregate location is provided.
194 
196  AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
197  return EmitAnyExpr(E, AggSlot);
198 }
199 
200 /// EmitAnyExprToMem - Evaluate an expression into a given memory
201 /// location.
203  Address Location,
204  Qualifiers Quals,
205  bool IsInit) {
206  // FIXME: This function should take an LValue as an argument.
207  switch (getEvaluationKind(E->getType())) {
208  case TEK_Complex:
210  /*isInit*/ false);
211  return;
212 
213  case TEK_Aggregate: {
214  EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
217  AggValueSlot::IsAliased_t(!IsInit)));
218  return;
219  }
220 
221  case TEK_Scalar: {
222  RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
223  LValue LV = MakeAddrLValue(Location, E->getType());
224  EmitStoreThroughLValue(RV, LV);
225  return;
226  }
227  }
228  llvm_unreachable("bad evaluation kind");
229 }
230 
231 static void
233  const Expr *E, Address ReferenceTemporary) {
234  // Objective-C++ ARC:
235  // If we are binding a reference to a temporary that has ownership, we
236  // need to perform retain/release operations on the temporary.
237  //
238  // FIXME: This should be looking at E, not M.
239  if (auto Lifetime = M->getType().getObjCLifetime()) {
240  switch (Lifetime) {
243  // Carry on to normal cleanup handling.
244  break;
245 
247  // Nothing to do; cleaned up by an autorelease pool.
248  return;
249 
252  switch (StorageDuration Duration = M->getStorageDuration()) {
253  case SD_Static:
254  // Note: we intentionally do not register a cleanup to release
255  // the object on program termination.
256  return;
257 
258  case SD_Thread:
259  // FIXME: We should probably register a cleanup in this case.
260  return;
261 
262  case SD_Automatic:
263  case SD_FullExpression:
266  if (Lifetime == Qualifiers::OCL_Strong) {
267  const ValueDecl *VD = M->getExtendingDecl();
268  bool Precise =
269  VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
270  CleanupKind = CGF.getARCCleanupKind();
271  Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
273  } else {
274  // __weak objects always get EH cleanups; otherwise, exceptions
275  // could cause really nasty crashes instead of mere leaks.
276  CleanupKind = NormalAndEHCleanup;
278  }
279  if (Duration == SD_FullExpression)
280  CGF.pushDestroy(CleanupKind, ReferenceTemporary,
281  M->getType(), *Destroy,
282  CleanupKind & EHCleanup);
283  else
284  CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
285  M->getType(),
286  *Destroy, CleanupKind & EHCleanup);
287  return;
288 
289  case SD_Dynamic:
290  llvm_unreachable("temporary cannot have dynamic storage duration");
291  }
292  llvm_unreachable("unknown storage duration");
293  }
294  }
295 
296  CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
297  if (const RecordType *RT =
299  // Get the destructor for the reference temporary.
300  auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
301  if (!ClassDecl->hasTrivialDestructor())
302  ReferenceTemporaryDtor = ClassDecl->getDestructor();
303  }
304 
305  if (!ReferenceTemporaryDtor)
306  return;
307 
308  // Call the destructor for the temporary.
309  switch (M->getStorageDuration()) {
310  case SD_Static:
311  case SD_Thread: {
312  llvm::Constant *CleanupFn;
313  llvm::Constant *CleanupArg;
314  if (E->getType()->isArrayType()) {
315  CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
316  ReferenceTemporary, E->getType(),
318  dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
319  CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
320  } else {
321  CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
323  CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
324  }
326  CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
327  break;
328  }
329 
330  case SD_FullExpression:
331  CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
333  CGF.getLangOpts().Exceptions);
334  break;
335 
336  case SD_Automatic:
338  ReferenceTemporary, E->getType(),
340  CGF.getLangOpts().Exceptions);
341  break;
342 
343  case SD_Dynamic:
344  llvm_unreachable("temporary cannot have dynamic storage duration");
345  }
346 }
347 
349  const MaterializeTemporaryExpr *M,
350  const Expr *Inner) {
351  auto &TCG = CGF.getTargetHooks();
352  switch (M->getStorageDuration()) {
353  case SD_FullExpression:
354  case SD_Automatic: {
355  // If we have a constant temporary array or record try to promote it into a
356  // constant global under the same rules a normal constant would've been
357  // promoted. This is easier on the optimizer and generally emits fewer
358  // instructions.
359  QualType Ty = Inner->getType();
360  if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
361  (Ty->isArrayType() || Ty->isRecordType()) &&
362  CGF.CGM.isTypeConstant(Ty, true))
363  if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
364  if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
365  auto AS = AddrSpace.getValue();
366  auto *GV = new llvm::GlobalVariable(
367  CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
368  llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
369  llvm::GlobalValue::NotThreadLocal,
371  CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
372  GV->setAlignment(alignment.getQuantity());
373  llvm::Constant *C = GV;
374  if (AS != LangAS::Default)
375  C = TCG.performAddrSpaceCast(
376  CGF.CGM, GV, AS, LangAS::Default,
377  GV->getValueType()->getPointerTo(
379  // FIXME: Should we put the new global into a COMDAT?
380  return Address(C, alignment);
381  }
382  }
383  return CGF.CreateMemTemp(Ty, "ref.tmp");
384  }
385  case SD_Thread:
386  case SD_Static:
387  return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
388 
389  case SD_Dynamic:
390  llvm_unreachable("temporary can't have dynamic storage duration");
391  }
392  llvm_unreachable("unknown storage duration");
393 }
394 
397  const Expr *E = M->GetTemporaryExpr();
398 
399  // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
400  // as that will cause the lifetime adjustment to be lost for ARC
401  auto ownership = M->getType().getObjCLifetime();
402  if (ownership != Qualifiers::OCL_None &&
403  ownership != Qualifiers::OCL_ExplicitNone) {
404  Address Object = createReferenceTemporary(*this, M, E);
405  if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
406  Object = Address(llvm::ConstantExpr::getBitCast(Var,
408  ->getPointerTo(Object.getAddressSpace())),
409  Object.getAlignment());
410 
411  // createReferenceTemporary will promote the temporary to a global with a
412  // constant initializer if it can. It can only do this to a value of
413  // ARC-manageable type if the value is global and therefore "immune" to
414  // ref-counting operations. Therefore we have no need to emit either a
415  // dynamic initialization or a cleanup and we can just return the address
416  // of the temporary.
417  if (Var->hasInitializer())
418  return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
419 
420  Var->setInitializer(CGM.EmitNullConstant(E->getType()));
421  }
422  LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
424 
425  switch (getEvaluationKind(E->getType())) {
426  default: llvm_unreachable("expected scalar or aggregate expression");
427  case TEK_Scalar:
428  EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
429  break;
430  case TEK_Aggregate: {
432  E->getType().getQualifiers(),
436  break;
437  }
438  }
439 
440  pushTemporaryCleanup(*this, M, E, Object);
441  return RefTempDst;
442  }
443 
446  E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
447 
448  for (const auto &Ignored : CommaLHSs)
449  EmitIgnoredExpr(Ignored);
450 
451  if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
452  if (opaque->getType()->isRecordType()) {
453  assert(Adjustments.empty());
454  return EmitOpaqueValueLValue(opaque);
455  }
456  }
457 
458  // Create and initialize the reference temporary.
459  Address Object = createReferenceTemporary(*this, M, E);
460  if (auto *Var = dyn_cast<llvm::GlobalVariable>(
461  Object.getPointer()->stripPointerCasts())) {
462  Object = Address(llvm::ConstantExpr::getBitCast(
463  cast<llvm::Constant>(Object.getPointer()),
464  ConvertTypeForMem(E->getType())->getPointerTo()),
465  Object.getAlignment());
466  // If the temporary is a global and has a constant initializer or is a
467  // constant temporary that we promoted to a global, we may have already
468  // initialized it.
469  if (!Var->hasInitializer()) {
470  Var->setInitializer(CGM.EmitNullConstant(E->getType()));
471  EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
472  }
473  } else {
474  switch (M->getStorageDuration()) {
475  case SD_Automatic:
476  case SD_FullExpression:
477  if (auto *Size = EmitLifetimeStart(
478  CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
479  Object.getPointer())) {
480  if (M->getStorageDuration() == SD_Automatic)
481  pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
482  Object, Size);
483  else
484  pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
485  Size);
486  }
487  break;
488  default:
489  break;
490  }
491  EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
492  }
493  pushTemporaryCleanup(*this, M, E, Object);
494 
495  // Perform derived-to-base casts and/or field accesses, to get from the
496  // temporary object we created (and, potentially, for which we extended
497  // the lifetime) to the subobject we're binding the reference to.
498  for (unsigned I = Adjustments.size(); I != 0; --I) {
499  SubobjectAdjustment &Adjustment = Adjustments[I-1];
500  switch (Adjustment.Kind) {
502  Object =
504  Adjustment.DerivedToBase.BasePath->path_begin(),
505  Adjustment.DerivedToBase.BasePath->path_end(),
506  /*NullCheckValue=*/ false, E->getExprLoc());
507  break;
508 
511  LV = EmitLValueForField(LV, Adjustment.Field);
512  assert(LV.isSimple() &&
513  "materialized temporary field is not a simple lvalue");
514  Object = LV.getAddress();
515  break;
516  }
517 
519  llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
520  Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
521  Adjustment.Ptr.MPT);
522  break;
523  }
524  }
525  }
526 
527  return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
528 }
529 
530 RValue
532  // Emit the expression as an lvalue.
533  LValue LV = EmitLValue(E);
534  assert(LV.isSimple());
535  llvm::Value *Value = LV.getPointer();
536 
537  if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
538  // C++11 [dcl.ref]p5 (as amended by core issue 453):
539  // If a glvalue to which a reference is directly bound designates neither
540  // an existing object or function of an appropriate type nor a region of
541  // storage of suitable size and alignment to contain an object of the
542  // reference's type, the behavior is undefined.
543  QualType Ty = E->getType();
545  }
546 
547  return RValue::get(Value);
548 }
549 
550 
551 /// getAccessedFieldNo - Given an encoded value and a result number, return the
552 /// input field number being accessed.
554  const llvm::Constant *Elts) {
555  return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
556  ->getZExtValue();
557 }
558 
559 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
561  llvm::Value *High) {
562  llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
563  llvm::Value *K47 = Builder.getInt64(47);
564  llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565  llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566  llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567  llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568  return Builder.CreateMul(B1, KMul);
569 }
570 
572  return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
574 }
575 
577  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
578  return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
579  (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
580  TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
582 }
583 
585  return SanOpts.has(SanitizerKind::Null) |
586  SanOpts.has(SanitizerKind::Alignment) |
587  SanOpts.has(SanitizerKind::ObjectSize) |
588  SanOpts.has(SanitizerKind::Vptr);
589 }
590 
592  llvm::Value *Ptr, QualType Ty,
593  CharUnits Alignment,
594  SanitizerSet SkippedChecks) {
596  return;
597 
598  // Don't check pointers outside the default address space. The null check
599  // isn't correct, the object-size check isn't supported by LLVM, and we can't
600  // communicate the addresses to the runtime handler for the vptr check.
601  if (Ptr->getType()->getPointerAddressSpace())
602  return;
603 
604  // Don't check pointers to volatile data. The behavior here is implementation-
605  // defined.
606  if (Ty.isVolatileQualified())
607  return;
608 
609  SanitizerScope SanScope(this);
610 
612  llvm::BasicBlock *Done = nullptr;
613 
614  // Quickly determine whether we have a pointer to an alloca. It's possible
615  // to skip null checks, and some alignment checks, for these pointers. This
616  // can reduce compile-time significantly.
617  auto PtrToAlloca =
618  dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
619 
620  llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
621  llvm::Value *IsNonNull = nullptr;
622  bool IsGuaranteedNonNull =
623  SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
624  bool AllowNullPointers = isNullPointerAllowed(TCK);
625  if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
626  !IsGuaranteedNonNull) {
627  // The glvalue must not be an empty glvalue.
628  IsNonNull = Builder.CreateIsNotNull(Ptr);
629 
630  // The IR builder can constant-fold the null check if the pointer points to
631  // a constant.
632  IsGuaranteedNonNull = IsNonNull == True;
633 
634  // Skip the null check if the pointer is known to be non-null.
635  if (!IsGuaranteedNonNull) {
636  if (AllowNullPointers) {
637  // When performing pointer casts, it's OK if the value is null.
638  // Skip the remaining checks in that case.
639  Done = createBasicBlock("null");
640  llvm::BasicBlock *Rest = createBasicBlock("not.null");
641  Builder.CreateCondBr(IsNonNull, Rest, Done);
642  EmitBlock(Rest);
643  } else {
644  Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
645  }
646  }
647  }
648 
649  if (SanOpts.has(SanitizerKind::ObjectSize) &&
650  !SkippedChecks.has(SanitizerKind::ObjectSize) &&
651  !Ty->isIncompleteType()) {
652  uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
653 
654  // The glvalue must refer to a large enough storage region.
655  // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
656  // to check this.
657  // FIXME: Get object address space
658  llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
659  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
660  llvm::Value *Min = Builder.getFalse();
661  llvm::Value *NullIsUnknown = Builder.getFalse();
662  llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
663  llvm::Value *LargeEnough = Builder.CreateICmpUGE(
664  Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
665  llvm::ConstantInt::get(IntPtrTy, Size));
666  Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
667  }
668 
669  uint64_t AlignVal = 0;
670  llvm::Value *PtrAsInt = nullptr;
671 
672  if (SanOpts.has(SanitizerKind::Alignment) &&
673  !SkippedChecks.has(SanitizerKind::Alignment)) {
674  AlignVal = Alignment.getQuantity();
675  if (!Ty->isIncompleteType() && !AlignVal)
676  AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
677 
678  // The glvalue must be suitably aligned.
679  if (AlignVal > 1 &&
680  (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
681  PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
682  llvm::Value *Align = Builder.CreateAnd(
683  PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
684  llvm::Value *Aligned =
685  Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
686  if (Aligned != True)
687  Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
688  }
689  }
690 
691  if (Checks.size() > 0) {
692  // Make sure we're not losing information. Alignment needs to be a power of
693  // 2
694  assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
695  llvm::Constant *StaticData[] = {
697  llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698  llvm::ConstantInt::get(Int8Ty, TCK)};
699  EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700  PtrAsInt ? PtrAsInt : Ptr);
701  }
702 
703  // If possible, check that the vptr indicates that there is a subobject of
704  // type Ty at offset zero within this object.
705  //
706  // C++11 [basic.life]p5,6:
707  // [For storage which does not refer to an object within its lifetime]
708  // The program has undefined behavior if:
709  // -- the [pointer or glvalue] is used to access a non-static data member
710  // or call a non-static member function
711  if (SanOpts.has(SanitizerKind::Vptr) &&
712  !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
713  // Ensure that the pointer is non-null before loading it. If there is no
714  // compile-time guarantee, reuse the run-time null check or emit a new one.
715  if (!IsGuaranteedNonNull) {
716  if (!IsNonNull)
717  IsNonNull = Builder.CreateIsNotNull(Ptr);
718  if (!Done)
719  Done = createBasicBlock("vptr.null");
720  llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721  Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722  EmitBlock(VptrNotNull);
723  }
724 
725  // Compute a hash of the mangled name of the type.
726  //
727  // FIXME: This is not guaranteed to be deterministic! Move to a
728  // fingerprinting mechanism once LLVM provides one. For the time
729  // being the implementation happens to be deterministic.
730  SmallString<64> MangledName;
731  llvm::raw_svector_ostream Out(MangledName);
733  Out);
734 
735  // Blacklist based on the mangled type.
737  SanitizerKind::Vptr, Out.str())) {
738  llvm::hash_code TypeHash = hash_value(Out.str());
739 
740  // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741  llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742  llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
743  Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
744  llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745  llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
746 
747  llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748  Hash = Builder.CreateTrunc(Hash, IntPtrTy);
749 
750  // Look the hash up in our cache.
751  const int CacheSize = 128;
752  llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
754  "__ubsan_vptr_type_cache");
755  llvm::Value *Slot = Builder.CreateAnd(Hash,
756  llvm::ConstantInt::get(IntPtrTy,
757  CacheSize-1));
758  llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759  llvm::Value *CacheVal =
760  Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
761  getPointerAlign());
762 
763  // If the hash isn't in the cache, call a runtime handler to perform the
764  // hard work of checking whether the vptr is for an object of the right
765  // type. This will either fill in the cache and return, or produce a
766  // diagnostic.
767  llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
768  llvm::Constant *StaticData[] = {
772  llvm::ConstantInt::get(Int8Ty, TCK)
773  };
774  llvm::Value *DynamicData[] = { Ptr, Hash };
775  EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
776  SanitizerHandler::DynamicTypeCacheMiss, StaticData,
777  DynamicData);
778  }
779  }
780 
781  if (Done) {
782  Builder.CreateBr(Done);
783  EmitBlock(Done);
784  }
785 }
786 
787 /// Determine whether this expression refers to a flexible array member in a
788 /// struct. We disable array bounds checks for such members.
789 static bool isFlexibleArrayMemberExpr(const Expr *E) {
790  // For compatibility with existing code, we treat arrays of length 0 or
791  // 1 as flexible array members.
792  const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
793  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
794  if (CAT->getSize().ugt(1))
795  return false;
796  } else if (!isa<IncompleteArrayType>(AT))
797  return false;
798 
799  E = E->IgnoreParens();
800 
801  // A flexible array member must be the last member in the class.
802  if (const auto *ME = dyn_cast<MemberExpr>(E)) {
803  // FIXME: If the base type of the member expr is not FD->getParent(),
804  // this should not be treated as a flexible array member access.
805  if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
807  DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808  return ++FI == FD->getParent()->field_end();
809  }
810  } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811  return IRE->getDecl()->getNextIvar() == nullptr;
812  }
813 
814  return false;
815 }
816 
818  QualType EltTy) {
819  ASTContext &C = getContext();
820  uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
821  if (!EltSize)
822  return nullptr;
823 
824  auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
825  if (!ArrayDeclRef)
826  return nullptr;
827 
828  auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
829  if (!ParamDecl)
830  return nullptr;
831 
832  auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
833  if (!POSAttr)
834  return nullptr;
835 
836  // Don't load the size if it's a lower bound.
837  int POSType = POSAttr->getType();
838  if (POSType != 0 && POSType != 1)
839  return nullptr;
840 
841  // Find the implicit size parameter.
842  auto PassedSizeIt = SizeArguments.find(ParamDecl);
843  if (PassedSizeIt == SizeArguments.end())
844  return nullptr;
845 
846  const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
847  assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
848  Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
849  llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
850  C.getSizeType(), E->getExprLoc());
851  llvm::Value *SizeOfElement =
852  llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
853  return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
854 }
855 
856 /// If Base is known to point to the start of an array, return the length of
857 /// that array. Return 0 if the length cannot be determined.
859  CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
860  // For the vector indexing extension, the bound is the number of elements.
861  if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
862  IndexedType = Base->getType();
863  return CGF.Builder.getInt32(VT->getNumElements());
864  }
865 
866  Base = Base->IgnoreParens();
867 
868  if (const auto *CE = dyn_cast<CastExpr>(Base)) {
869  if (CE->getCastKind() == CK_ArrayToPointerDecay &&
870  !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
871  IndexedType = CE->getSubExpr()->getType();
872  const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
873  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
874  return CGF.Builder.getInt(CAT->getSize());
875  else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
876  return CGF.getVLASize(VAT).first;
877  // Ignore pass_object_size here. It's not applicable on decayed pointers.
878  }
879  }
880 
881  QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
882  if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
883  IndexedType = Base->getType();
884  return POS;
885  }
886 
887  return nullptr;
888 }
889 
891  llvm::Value *Index, QualType IndexType,
892  bool Accessed) {
893  assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
894  "should not be called unless adding bounds checks");
895  SanitizerScope SanScope(this);
896 
897  QualType IndexedType;
898  llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
899  if (!Bound)
900  return;
901 
902  bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
903  llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
904  llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
905 
906  llvm::Constant *StaticData[] = {
908  EmitCheckTypeDescriptor(IndexedType),
909  EmitCheckTypeDescriptor(IndexType)
910  };
911  llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
912  : Builder.CreateICmpULE(IndexVal, BoundVal);
913  EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
914  SanitizerHandler::OutOfBounds, StaticData, Index);
915 }
916 
917 
920  bool isInc, bool isPre) {
921  ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
922 
923  llvm::Value *NextVal;
924  if (isa<llvm::IntegerType>(InVal.first->getType())) {
925  uint64_t AmountVal = isInc ? 1 : -1;
926  NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
927 
928  // Add the inc/dec to the real part.
929  NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
930  } else {
931  QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
932  llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
933  if (!isInc)
934  FVal.changeSign();
935  NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
936 
937  // Add the inc/dec to the real part.
938  NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
939  }
940 
941  ComplexPairTy IncVal(NextVal, InVal.second);
942 
943  // Store the updated result through the lvalue.
944  EmitStoreOfComplex(IncVal, LV, /*init*/ false);
945 
946  // If this is a postinc, return the value read from memory, otherwise use the
947  // updated value.
948  return isPre ? IncVal : InVal;
949 }
950 
952  CodeGenFunction *CGF) {
953  // Bind VLAs in the cast type.
954  if (CGF && E->getType()->isVariablyModifiedType())
956 
957  if (CGDebugInfo *DI = getModuleDebugInfo())
958  DI->EmitExplicitCastType(E->getType());
959 }
960 
961 //===----------------------------------------------------------------------===//
962 // LValue Expression Emission
963 //===----------------------------------------------------------------------===//
964 
965 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
966 /// derive a more accurate bound on the alignment of the pointer.
968  LValueBaseInfo *BaseInfo,
969  TBAAAccessInfo *TBAAInfo) {
970  // We allow this with ObjC object pointers because of fragile ABIs.
971  assert(E->getType()->isPointerType() ||
973  E = E->IgnoreParens();
974 
975  // Casts:
976  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
977  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
978  CGM.EmitExplicitCastExprType(ECE, this);
979 
980  switch (CE->getCastKind()) {
981  // Non-converting casts (but not C's implicit conversion from void*).
982  case CK_BitCast:
983  case CK_NoOp:
984  case CK_AddressSpaceConversion:
985  if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
986  if (PtrTy->getPointeeType()->isVoidType())
987  break;
988 
989  LValueBaseInfo InnerBaseInfo;
990  TBAAAccessInfo InnerTBAAInfo;
991  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
992  &InnerBaseInfo,
993  &InnerTBAAInfo);
994  if (BaseInfo) *BaseInfo = InnerBaseInfo;
995  if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
996 
997  if (isa<ExplicitCastExpr>(CE)) {
998  LValueBaseInfo TargetTypeBaseInfo;
999  TBAAAccessInfo TargetTypeTBAAInfo;
1000  CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
1001  &TargetTypeBaseInfo,
1002  &TargetTypeTBAAInfo);
1003  if (TBAAInfo)
1004  *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1005  TargetTypeTBAAInfo);
1006  // If the source l-value is opaque, honor the alignment of the
1007  // casted-to type.
1008  if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1009  if (BaseInfo)
1010  BaseInfo->mergeForCast(TargetTypeBaseInfo);
1011  Addr = Address(Addr.getPointer(), Align);
1012  }
1013  }
1014 
1015  if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1016  CE->getCastKind() == CK_BitCast) {
1017  if (auto PT = E->getType()->getAs<PointerType>())
1018  EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1019  /*MayBeNull=*/true,
1021  CE->getLocStart());
1022  }
1023  return CE->getCastKind() != CK_AddressSpaceConversion
1024  ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1026  ConvertType(E->getType()));
1027  }
1028  break;
1029 
1030  // Array-to-pointer decay.
1031  case CK_ArrayToPointerDecay:
1032  return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1033 
1034  // Derived-to-base conversions.
1035  case CK_UncheckedDerivedToBase:
1036  case CK_DerivedToBase: {
1037  Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
1038  TBAAInfo);
1039  auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1040  return GetAddressOfBaseClass(Addr, Derived,
1041  CE->path_begin(), CE->path_end(),
1043  CE->getExprLoc());
1044  }
1045 
1046  // TODO: Is there any reason to treat base-to-derived conversions
1047  // specially?
1048  default:
1049  break;
1050  }
1051  }
1052 
1053  // Unary &.
1054  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1055  if (UO->getOpcode() == UO_AddrOf) {
1056  LValue LV = EmitLValue(UO->getSubExpr());
1057  if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1058  if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1059  return LV.getAddress();
1060  }
1061  }
1062 
1063  // TODO: conditional operators, comma.
1064 
1065  // Otherwise, use the alignment of the type.
1066  CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1067  TBAAInfo);
1068  return Address(EmitScalarExpr(E), Align);
1069 }
1070 
1072  if (Ty->isVoidType())
1073  return RValue::get(nullptr);
1074 
1075  switch (getEvaluationKind(Ty)) {
1076  case TEK_Complex: {
1077  llvm::Type *EltTy =
1079  llvm::Value *U = llvm::UndefValue::get(EltTy);
1080  return RValue::getComplex(std::make_pair(U, U));
1081  }
1082 
1083  // If this is a use of an undefined aggregate type, the aggregate must have an
1084  // identifiable address. Just because the contents of the value are undefined
1085  // doesn't mean that the address can't be taken and compared.
1086  case TEK_Aggregate: {
1087  Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1088  return RValue::getAggregate(DestPtr);
1089  }
1090 
1091  case TEK_Scalar:
1092  return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1093  }
1094  llvm_unreachable("bad evaluation kind");
1095 }
1096 
1098  const char *Name) {
1099  ErrorUnsupported(E, Name);
1100  return GetUndefRValue(E->getType());
1101 }
1102 
1104  const char *Name) {
1105  ErrorUnsupported(E, Name);
1106  llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1107  return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1108  E->getType());
1109 }
1110 
1112  const Expr *Base = Obj;
1113  while (!isa<CXXThisExpr>(Base)) {
1114  // The result of a dynamic_cast can be null.
1115  if (isa<CXXDynamicCastExpr>(Base))
1116  return false;
1117 
1118  if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1119  Base = CE->getSubExpr();
1120  } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1121  Base = PE->getSubExpr();
1122  } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1123  if (UO->getOpcode() == UO_Extension)
1124  Base = UO->getSubExpr();
1125  else
1126  return false;
1127  } else {
1128  return false;
1129  }
1130  }
1131  return true;
1132 }
1133 
1135  LValue LV;
1136  if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1137  LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1138  else
1139  LV = EmitLValue(E);
1140  if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1141  SanitizerSet SkippedChecks;
1142  if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1143  bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1144  if (IsBaseCXXThis)
1145  SkippedChecks.set(SanitizerKind::Alignment, true);
1146  if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1147  SkippedChecks.set(SanitizerKind::Null, true);
1148  }
1149  EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1150  E->getType(), LV.getAlignment(), SkippedChecks);
1151  }
1152  return LV;
1153 }
1154 
1155 /// EmitLValue - Emit code to compute a designator that specifies the location
1156 /// of the expression.
1157 ///
1158 /// This can return one of two things: a simple address or a bitfield reference.
1159 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1160 /// an LLVM pointer type.
1161 ///
1162 /// If this returns a bitfield reference, nothing about the pointee type of the
1163 /// LLVM value is known: For example, it may not be a pointer to an integer.
1164 ///
1165 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1166 /// this method guarantees that the returned pointer type will point to an LLVM
1167 /// type of the same size of the lvalue's type. If the lvalue has a variable
1168 /// length type, this is not possible.
1169 ///
1171  ApplyDebugLocation DL(*this, E);
1172  switch (E->getStmtClass()) {
1173  default: return EmitUnsupportedLValue(E, "l-value expression");
1174 
1175  case Expr::ObjCPropertyRefExprClass:
1176  llvm_unreachable("cannot emit a property reference directly");
1177 
1178  case Expr::ObjCSelectorExprClass:
1179  return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1180  case Expr::ObjCIsaExprClass:
1181  return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1182  case Expr::BinaryOperatorClass:
1183  return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1184  case Expr::CompoundAssignOperatorClass: {
1185  QualType Ty = E->getType();
1186  if (const AtomicType *AT = Ty->getAs<AtomicType>())
1187  Ty = AT->getValueType();
1188  if (!Ty->isAnyComplexType())
1189  return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1190  return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1191  }
1192  case Expr::CallExprClass:
1193  case Expr::CXXMemberCallExprClass:
1194  case Expr::CXXOperatorCallExprClass:
1195  case Expr::UserDefinedLiteralClass:
1196  return EmitCallExprLValue(cast<CallExpr>(E));
1197  case Expr::VAArgExprClass:
1198  return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1199  case Expr::DeclRefExprClass:
1200  return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1201  case Expr::ParenExprClass:
1202  return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1203  case Expr::GenericSelectionExprClass:
1204  return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1205  case Expr::PredefinedExprClass:
1206  return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1207  case Expr::StringLiteralClass:
1208  return EmitStringLiteralLValue(cast<StringLiteral>(E));
1209  case Expr::ObjCEncodeExprClass:
1210  return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1211  case Expr::PseudoObjectExprClass:
1212  return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1213  case Expr::InitListExprClass:
1214  return EmitInitListLValue(cast<InitListExpr>(E));
1215  case Expr::CXXTemporaryObjectExprClass:
1216  case Expr::CXXConstructExprClass:
1217  return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1218  case Expr::CXXBindTemporaryExprClass:
1219  return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1220  case Expr::CXXUuidofExprClass:
1221  return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1222  case Expr::LambdaExprClass:
1223  return EmitLambdaLValue(cast<LambdaExpr>(E));
1224 
1225  case Expr::ExprWithCleanupsClass: {
1226  const auto *cleanups = cast<ExprWithCleanups>(E);
1227  enterFullExpression(cleanups);
1228  RunCleanupsScope Scope(*this);
1229  LValue LV = EmitLValue(cleanups->getSubExpr());
1230  if (LV.isSimple()) {
1231  // Defend against branches out of gnu statement expressions surrounded by
1232  // cleanups.
1233  llvm::Value *V = LV.getPointer();
1234  Scope.ForceCleanup({&V});
1235  return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1236  getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
1237  }
1238  // FIXME: Is it possible to create an ExprWithCleanups that produces a
1239  // bitfield lvalue or some other non-simple lvalue?
1240  return LV;
1241  }
1242 
1243  case Expr::CXXDefaultArgExprClass:
1244  return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1245  case Expr::CXXDefaultInitExprClass: {
1247  return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1248  }
1249  case Expr::CXXTypeidExprClass:
1250  return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1251 
1252  case Expr::ObjCMessageExprClass:
1253  return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1254  case Expr::ObjCIvarRefExprClass:
1255  return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1256  case Expr::StmtExprClass:
1257  return EmitStmtExprLValue(cast<StmtExpr>(E));
1258  case Expr::UnaryOperatorClass:
1259  return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1260  case Expr::ArraySubscriptExprClass:
1261  return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1262  case Expr::OMPArraySectionExprClass:
1263  return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1264  case Expr::ExtVectorElementExprClass:
1265  return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1266  case Expr::MemberExprClass:
1267  return EmitMemberExpr(cast<MemberExpr>(E));
1268  case Expr::CompoundLiteralExprClass:
1269  return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1270  case Expr::ConditionalOperatorClass:
1271  return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1272  case Expr::BinaryConditionalOperatorClass:
1273  return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1274  case Expr::ChooseExprClass:
1275  return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1276  case Expr::OpaqueValueExprClass:
1277  return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1278  case Expr::SubstNonTypeTemplateParmExprClass:
1279  return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1280  case Expr::ImplicitCastExprClass:
1281  case Expr::CStyleCastExprClass:
1282  case Expr::CXXFunctionalCastExprClass:
1283  case Expr::CXXStaticCastExprClass:
1284  case Expr::CXXDynamicCastExprClass:
1285  case Expr::CXXReinterpretCastExprClass:
1286  case Expr::CXXConstCastExprClass:
1287  case Expr::ObjCBridgedCastExprClass:
1288  return EmitCastLValue(cast<CastExpr>(E));
1289 
1290  case Expr::MaterializeTemporaryExprClass:
1291  return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1292 
1293  case Expr::CoawaitExprClass:
1294  return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1295  case Expr::CoyieldExprClass:
1296  return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1297  }
1298 }
1299 
1300 /// Given an object of the given canonical type, can we safely copy a
1301 /// value out of it based on its initializer?
1303  assert(type.isCanonical());
1304  assert(!type->isReferenceType());
1305 
1306  // Must be const-qualified but non-volatile.
1307  Qualifiers qs = type.getLocalQualifiers();
1308  if (!qs.hasConst() || qs.hasVolatile()) return false;
1309 
1310  // Otherwise, all object types satisfy this except C++ classes with
1311  // mutable subobjects or non-trivial copy/destroy behavior.
1312  if (const auto *RT = dyn_cast<RecordType>(type))
1313  if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1314  if (RD->hasMutableFields() || !RD->isTrivial())
1315  return false;
1316 
1317  return true;
1318 }
1319 
1320 /// Can we constant-emit a load of a reference to a variable of the
1321 /// given type? This is different from predicates like
1322 /// Decl::isUsableInConstantExpressions because we do want it to apply
1323 /// in situations that don't necessarily satisfy the language's rules
1324 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1325 /// to do this with const float variables even if those variables
1326 /// aren't marked 'constexpr'.
1332 };
1334  type = type.getCanonicalType();
1335  if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1336  if (isConstantEmittableObjectType(ref->getPointeeType()))
1337  return CEK_AsValueOrReference;
1338  return CEK_AsReferenceOnly;
1339  }
1341  return CEK_AsValueOnly;
1342  return CEK_None;
1343 }
1344 
1345 /// Try to emit a reference to the given value without producing it as
1346 /// an l-value. This is actually more than an optimization: we can't
1347 /// produce an l-value for variables that we never actually captured
1348 /// in a block or lambda, which means const int variables or constexpr
1349 /// literals or similar.
1352  ValueDecl *value = refExpr->getDecl();
1353 
1354  // The value needs to be an enum constant or a constant variable.
1356  if (isa<ParmVarDecl>(value)) {
1357  CEK = CEK_None;
1358  } else if (auto *var = dyn_cast<VarDecl>(value)) {
1359  CEK = checkVarTypeForConstantEmission(var->getType());
1360  } else if (isa<EnumConstantDecl>(value)) {
1361  CEK = CEK_AsValueOnly;
1362  } else {
1363  CEK = CEK_None;
1364  }
1365  if (CEK == CEK_None) return ConstantEmission();
1366 
1367  Expr::EvalResult result;
1368  bool resultIsReference;
1369  QualType resultType;
1370 
1371  // It's best to evaluate all the way as an r-value if that's permitted.
1372  if (CEK != CEK_AsReferenceOnly &&
1373  refExpr->EvaluateAsRValue(result, getContext())) {
1374  resultIsReference = false;
1375  resultType = refExpr->getType();
1376 
1377  // Otherwise, try to evaluate as an l-value.
1378  } else if (CEK != CEK_AsValueOnly &&
1379  refExpr->EvaluateAsLValue(result, getContext())) {
1380  resultIsReference = true;
1381  resultType = value->getType();
1382 
1383  // Failure.
1384  } else {
1385  return ConstantEmission();
1386  }
1387 
1388  // In any case, if the initializer has side-effects, abandon ship.
1389  if (result.HasSideEffects)
1390  return ConstantEmission();
1391 
1392  // Emit as a constant.
1393  auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1394  result.Val, resultType);
1395 
1396  // Make sure we emit a debug reference to the global variable.
1397  // This should probably fire even for
1398  if (isa<VarDecl>(value)) {
1399  if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1400  EmitDeclRefExprDbgValue(refExpr, result.Val);
1401  } else {
1402  assert(isa<EnumConstantDecl>(value));
1403  EmitDeclRefExprDbgValue(refExpr, result.Val);
1404  }
1405 
1406  // If we emitted a reference constant, we need to dereference that.
1407  if (resultIsReference)
1409 
1410  return ConstantEmission::forValue(C);
1411 }
1412 
1414  const MemberExpr *ME) {
1415  if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1416  // Try to emit static variable member expressions as DREs.
1417  return DeclRefExpr::Create(
1419  /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1420  ME->getType(), ME->getValueKind());
1421  }
1422  return nullptr;
1423 }
1424 
1427  if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1428  return tryEmitAsConstant(DRE);
1429  return ConstantEmission();
1430 }
1431 
1433  SourceLocation Loc) {
1434  return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1435  lvalue.getType(), Loc, lvalue.getBaseInfo(),
1436  lvalue.getTBAAInfo(), lvalue.isNontemporal());
1437 }
1438 
1440  if (Ty->isBooleanType())
1441  return true;
1442 
1443  if (const EnumType *ET = Ty->getAs<EnumType>())
1444  return ET->getDecl()->getIntegerType()->isBooleanType();
1445 
1446  if (const AtomicType *AT = Ty->getAs<AtomicType>())
1447  return hasBooleanRepresentation(AT->getValueType());
1448 
1449  return false;
1450 }
1451 
1453  llvm::APInt &Min, llvm::APInt &End,
1454  bool StrictEnums, bool IsBool) {
1455  const EnumType *ET = Ty->getAs<EnumType>();
1456  bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1457  ET && !ET->getDecl()->isFixed();
1458  if (!IsBool && !IsRegularCPlusPlusEnum)
1459  return false;
1460 
1461  if (IsBool) {
1462  Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1463  End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1464  } else {
1465  const EnumDecl *ED = ET->getDecl();
1466  llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1467  unsigned Bitwidth = LTy->getScalarSizeInBits();
1468  unsigned NumNegativeBits = ED->getNumNegativeBits();
1469  unsigned NumPositiveBits = ED->getNumPositiveBits();
1470 
1471  if (NumNegativeBits) {
1472  unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1473  assert(NumBits <= Bitwidth);
1474  End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1475  Min = -End;
1476  } else {
1477  assert(NumPositiveBits <= Bitwidth);
1478  End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1479  Min = llvm::APInt(Bitwidth, 0);
1480  }
1481  }
1482  return true;
1483 }
1484 
1485 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1486  llvm::APInt Min, End;
1487  if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1489  return nullptr;
1490 
1491  llvm::MDBuilder MDHelper(getLLVMContext());
1492  return MDHelper.createRange(Min, End);
1493 }
1494 
1496  SourceLocation Loc) {
1497  bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1498  bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1499  if (!HasBoolCheck && !HasEnumCheck)
1500  return false;
1501 
1502  bool IsBool = hasBooleanRepresentation(Ty) ||
1503  NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1504  bool NeedsBoolCheck = HasBoolCheck && IsBool;
1505  bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1506  if (!NeedsBoolCheck && !NeedsEnumCheck)
1507  return false;
1508 
1509  // Single-bit booleans don't need to be checked. Special-case this to avoid
1510  // a bit width mismatch when handling bitfield values. This is handled by
1511  // EmitFromMemory for the non-bitfield case.
1512  if (IsBool &&
1513  cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1514  return false;
1515 
1516  llvm::APInt Min, End;
1517  if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1518  return true;
1519 
1520  auto &Ctx = getLLVMContext();
1521  SanitizerScope SanScope(this);
1522  llvm::Value *Check;
1523  --End;
1524  if (!Min) {
1525  Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1526  } else {
1527  llvm::Value *Upper =
1528  Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1529  llvm::Value *Lower =
1530  Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1531  Check = Builder.CreateAnd(Upper, Lower);
1532  }
1533  llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1536  NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1537  EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1538  StaticArgs, EmitCheckValue(Value));
1539  return true;
1540 }
1541 
1543  QualType Ty,
1544  SourceLocation Loc,
1545  LValueBaseInfo BaseInfo,
1546  TBAAAccessInfo TBAAInfo,
1547  bool isNontemporal) {
1548  if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1549  // For better performance, handle vector loads differently.
1550  if (Ty->isVectorType()) {
1551  const llvm::Type *EltTy = Addr.getElementType();
1552 
1553  const auto *VTy = cast<llvm::VectorType>(EltTy);
1554 
1555  // Handle vectors of size 3 like size 4 for better performance.
1556  if (VTy->getNumElements() == 3) {
1557 
1558  // Bitcast to vec4 type.
1559  llvm::VectorType *vec4Ty =
1560  llvm::VectorType::get(VTy->getElementType(), 4);
1561  Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1562  // Now load value.
1563  llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1564 
1565  // Shuffle vector to get vec3.
1566  V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1567  {0, 1, 2}, "extractVec");
1568  return EmitFromMemory(V, Ty);
1569  }
1570  }
1571  }
1572 
1573  // Atomic operations have to be done on integral types.
1574  LValue AtomicLValue =
1575  LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1576  if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1577  return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1578  }
1579 
1580  llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1581  if (isNontemporal) {
1582  llvm::MDNode *Node = llvm::MDNode::get(
1583  Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1584  Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1585  }
1586 
1587  CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1588 
1589  if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1590  // In order to prevent the optimizer from throwing away the check, don't
1591  // attach range metadata to the load.
1592  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1593  if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1594  Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1595 
1596  return EmitFromMemory(Load, Ty);
1597 }
1598 
1600  // Bool has a different representation in memory than in registers.
1601  if (hasBooleanRepresentation(Ty)) {
1602  // This should really always be an i1, but sometimes it's already
1603  // an i8, and it's awkward to track those cases down.
1604  if (Value->getType()->isIntegerTy(1))
1605  return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1606  assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1607  "wrong value rep of bool");
1608  }
1609 
1610  return Value;
1611 }
1612 
1614  // Bool has a different representation in memory than in registers.
1615  if (hasBooleanRepresentation(Ty)) {
1616  assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1617  "wrong value rep of bool");
1618  return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1619  }
1620 
1621  return Value;
1622 }
1623 
1625  bool Volatile, QualType Ty,
1626  LValueBaseInfo BaseInfo,
1627  TBAAAccessInfo TBAAInfo,
1628  bool isInit, bool isNontemporal) {
1629  if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1630  // Handle vectors differently to get better performance.
1631  if (Ty->isVectorType()) {
1632  llvm::Type *SrcTy = Value->getType();
1633  auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1634  // Handle vec3 special.
1635  if (VecTy && VecTy->getNumElements() == 3) {
1636  // Our source is a vec3, do a shuffle vector to make it a vec4.
1637  llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1638  Builder.getInt32(2),
1639  llvm::UndefValue::get(Builder.getInt32Ty())};
1640  llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1641  Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1642  MaskV, "extractVec");
1643  SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1644  }
1645  if (Addr.getElementType() != SrcTy) {
1646  Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1647  }
1648  }
1649  }
1650 
1651  Value = EmitToMemory(Value, Ty);
1652 
1653  LValue AtomicLValue =
1654  LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1655  if (Ty->isAtomicType() ||
1656  (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1657  EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1658  return;
1659  }
1660 
1661  llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1662  if (isNontemporal) {
1663  llvm::MDNode *Node =
1664  llvm::MDNode::get(Store->getContext(),
1665  llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1666  Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1667  }
1668 
1669  CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1670 }
1671 
1673  bool isInit) {
1674  EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1675  lvalue.getType(), lvalue.getBaseInfo(),
1676  lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1677 }
1678 
1679 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1680 /// method emits the address of the lvalue, then loads the result as an rvalue,
1681 /// returning the rvalue.
1683  if (LV.isObjCWeak()) {
1684  // load of a __weak object.
1685  Address AddrWeakObj = LV.getAddress();
1687  AddrWeakObj));
1688  }
1690  // In MRC mode, we do a load+autorelease.
1691  if (!getLangOpts().ObjCAutoRefCount) {
1692  return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1693  }
1694 
1695  // In ARC mode, we load retained and then consume the value.
1697  Object = EmitObjCConsumeObject(LV.getType(), Object);
1698  return RValue::get(Object);
1699  }
1700 
1701  if (LV.isSimple()) {
1702  assert(!LV.getType()->isFunctionType());
1703 
1704  // Everything needs a load.
1705  return RValue::get(EmitLoadOfScalar(LV, Loc));
1706  }
1707 
1708  if (LV.isVectorElt()) {
1709  llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1710  LV.isVolatileQualified());
1711  return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1712  "vecext"));
1713  }
1714 
1715  // If this is a reference to a subset of the elements of a vector, either
1716  // shuffle the input or extract/insert them as appropriate.
1717  if (LV.isExtVectorElt())
1719 
1720  // Global Register variables always invoke intrinsics
1721  if (LV.isGlobalReg())
1722  return EmitLoadOfGlobalRegLValue(LV);
1723 
1724  assert(LV.isBitField() && "Unknown LValue type!");
1725  return EmitLoadOfBitfieldLValue(LV, Loc);
1726 }
1727 
1729  SourceLocation Loc) {
1730  const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1731 
1732  // Get the output type.
1733  llvm::Type *ResLTy = ConvertType(LV.getType());
1734 
1735  Address Ptr = LV.getBitFieldAddress();
1736  llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1737 
1738  if (Info.IsSigned) {
1739  assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1740  unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1741  if (HighBits)
1742  Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1743  if (Info.Offset + HighBits)
1744  Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1745  } else {
1746  if (Info.Offset)
1747  Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1748  if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1749  Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1750  Info.Size),
1751  "bf.clear");
1752  }
1753  Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1754  EmitScalarRangeCheck(Val, LV.getType(), Loc);
1755  return RValue::get(Val);
1756 }
1757 
1758 // If this is a reference to a subset of the elements of a vector, create an
1759 // appropriate shufflevector.
1762  LV.isVolatileQualified());
1763 
1764  const llvm::Constant *Elts = LV.getExtVectorElts();
1765 
1766  // If the result of the expression is a non-vector type, we must be extracting
1767  // a single element. Just codegen as an extractelement.
1768  const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1769  if (!ExprVT) {
1770  unsigned InIdx = getAccessedFieldNo(0, Elts);
1771  llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1772  return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1773  }
1774 
1775  // Always use shuffle vector to try to retain the original program structure
1776  unsigned NumResultElts = ExprVT->getNumElements();
1777 
1779  for (unsigned i = 0; i != NumResultElts; ++i)
1780  Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1781 
1782  llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1783  Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1784  MaskV);
1785  return RValue::get(Vec);
1786 }
1787 
1788 /// @brief Generates lvalue for partial ext_vector access.
1790  Address VectorAddress = LV.getExtVectorAddress();
1791  const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1792  QualType EQT = ExprVT->getElementType();
1793  llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1794 
1795  Address CastToPointerElement =
1796  Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1797  "conv.ptr.element");
1798 
1799  const llvm::Constant *Elts = LV.getExtVectorElts();
1800  unsigned ix = getAccessedFieldNo(0, Elts);
1801 
1802  Address VectorBasePtrPlusIx =
1803  Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1804  getContext().getTypeSizeInChars(EQT),
1805  "vector.elt");
1806 
1807  return VectorBasePtrPlusIx;
1808 }
1809 
1810 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1812  assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1813  "Bad type for register variable");
1814  llvm::MDNode *RegName = cast<llvm::MDNode>(
1815  cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1816 
1817  // We accept integer and pointer types only
1818  llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1819  llvm::Type *Ty = OrigTy;
1820  if (OrigTy->isPointerTy())
1821  Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1822  llvm::Type *Types[] = { Ty };
1823 
1824  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1825  llvm::Value *Call = Builder.CreateCall(
1826  F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1827  if (OrigTy->isPointerTy())
1828  Call = Builder.CreateIntToPtr(Call, OrigTy);
1829  return RValue::get(Call);
1830 }
1831 
1832 
1833 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1834 /// lvalue, where both are guaranteed to the have the same type, and that type
1835 /// is 'Ty'.
1837  bool isInit) {
1838  if (!Dst.isSimple()) {
1839  if (Dst.isVectorElt()) {
1840  // Read/modify/write the vector, inserting the new element.
1842  Dst.isVolatileQualified());
1843  Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1844  Dst.getVectorIdx(), "vecins");
1846  Dst.isVolatileQualified());
1847  return;
1848  }
1849 
1850  // If this is an update of extended vector elements, insert them as
1851  // appropriate.
1852  if (Dst.isExtVectorElt())
1854 
1855  if (Dst.isGlobalReg())
1856  return EmitStoreThroughGlobalRegLValue(Src, Dst);
1857 
1858  assert(Dst.isBitField() && "Unknown LValue type");
1859  return EmitStoreThroughBitfieldLValue(Src, Dst);
1860  }
1861 
1862  // There's special magic for assigning into an ARC-qualified l-value.
1863  if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1864  switch (Lifetime) {
1865  case Qualifiers::OCL_None:
1866  llvm_unreachable("present but none");
1867 
1869  // nothing special
1870  break;
1871 
1873  if (isInit) {
1874  Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1875  break;
1876  }
1877  EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1878  return;
1879 
1880  case Qualifiers::OCL_Weak:
1881  if (isInit)
1882  // Initialize and then skip the primitive store.
1883  EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1884  else
1885  EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1886  return;
1887 
1890  Src.getScalarVal()));
1891  // fall into the normal path
1892  break;
1893  }
1894  }
1895 
1896  if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1897  // load of a __weak object.
1898  Address LvalueDst = Dst.getAddress();
1899  llvm::Value *src = Src.getScalarVal();
1900  CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1901  return;
1902  }
1903 
1904  if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1905  // load of a __strong object.
1906  Address LvalueDst = Dst.getAddress();
1907  llvm::Value *src = Src.getScalarVal();
1908  if (Dst.isObjCIvar()) {
1909  assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1910  llvm::Type *ResultType = IntPtrTy;
1912  llvm::Value *RHS = dst.getPointer();
1913  RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1914  llvm::Value *LHS =
1915  Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1916  "sub.ptr.lhs.cast");
1917  llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1918  CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1919  BytesBetween);
1920  } else if (Dst.isGlobalObjCRef()) {
1921  CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1922  Dst.isThreadLocalRef());
1923  }
1924  else
1925  CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1926  return;
1927  }
1928 
1929  assert(Src.isScalar() && "Can't emit an agg store with this method");
1930  EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1931 }
1932 
1934  llvm::Value **Result) {
1935  const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1936  llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1937  Address Ptr = Dst.getBitFieldAddress();
1938 
1939  // Get the source value, truncated to the width of the bit-field.
1940  llvm::Value *SrcVal = Src.getScalarVal();
1941 
1942  // Cast the source to the storage type and shift it into place.
1943  SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1944  /*IsSigned=*/false);
1945  llvm::Value *MaskedVal = SrcVal;
1946 
1947  // See if there are other bits in the bitfield's storage we'll need to load
1948  // and mask together with source before storing.
1949  if (Info.StorageSize != Info.Size) {
1950  assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1951  llvm::Value *Val =
1952  Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1953 
1954  // Mask the source value as needed.
1955  if (!hasBooleanRepresentation(Dst.getType()))
1956  SrcVal = Builder.CreateAnd(SrcVal,
1957  llvm::APInt::getLowBitsSet(Info.StorageSize,
1958  Info.Size),
1959  "bf.value");
1960  MaskedVal = SrcVal;
1961  if (Info.Offset)
1962  SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1963 
1964  // Mask out the original value.
1965  Val = Builder.CreateAnd(Val,
1966  ~llvm::APInt::getBitsSet(Info.StorageSize,
1967  Info.Offset,
1968  Info.Offset + Info.Size),
1969  "bf.clear");
1970 
1971  // Or together the unchanged values and the source value.
1972  SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1973  } else {
1974  assert(Info.Offset == 0);
1975  }
1976 
1977  // Write the new value back out.
1978  Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1979 
1980  // Return the new value of the bit-field, if requested.
1981  if (Result) {
1982  llvm::Value *ResultVal = MaskedVal;
1983 
1984  // Sign extend the value if needed.
1985  if (Info.IsSigned) {
1986  assert(Info.Size <= Info.StorageSize);
1987  unsigned HighBits = Info.StorageSize - Info.Size;
1988  if (HighBits) {
1989  ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1990  ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1991  }
1992  }
1993 
1994  ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1995  "bf.result.cast");
1996  *Result = EmitFromMemory(ResultVal, Dst.getType());
1997  }
1998 }
1999 
2001  LValue Dst) {
2002  // This access turns into a read/modify/write of the vector. Load the input
2003  // value now.
2005  Dst.isVolatileQualified());
2006  const llvm::Constant *Elts = Dst.getExtVectorElts();
2007 
2008  llvm::Value *SrcVal = Src.getScalarVal();
2009 
2010  if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2011  unsigned NumSrcElts = VTy->getNumElements();
2012  unsigned NumDstElts = Vec->getType()->getVectorNumElements();
2013  if (NumDstElts == NumSrcElts) {
2014  // Use shuffle vector is the src and destination are the same number of
2015  // elements and restore the vector mask since it is on the side it will be
2016  // stored.
2017  SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
2018  for (unsigned i = 0; i != NumSrcElts; ++i)
2019  Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
2020 
2021  llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2022  Vec = Builder.CreateShuffleVector(SrcVal,
2023  llvm::UndefValue::get(Vec->getType()),
2024  MaskV);
2025  } else if (NumDstElts > NumSrcElts) {
2026  // Extended the source vector to the same length and then shuffle it
2027  // into the destination.
2028  // FIXME: since we're shuffling with undef, can we just use the indices
2029  // into that? This could be simpler.
2031  for (unsigned i = 0; i != NumSrcElts; ++i)
2032  ExtMask.push_back(Builder.getInt32(i));
2033  ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
2034  llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
2035  llvm::Value *ExtSrcVal =
2036  Builder.CreateShuffleVector(SrcVal,
2037  llvm::UndefValue::get(SrcVal->getType()),
2038  ExtMaskV);
2039  // build identity
2041  for (unsigned i = 0; i != NumDstElts; ++i)
2042  Mask.push_back(Builder.getInt32(i));
2043 
2044  // When the vector size is odd and .odd or .hi is used, the last element
2045  // of the Elts constant array will be one past the size of the vector.
2046  // Ignore the last element here, if it is greater than the mask size.
2047  if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2048  NumSrcElts--;
2049 
2050  // modify when what gets shuffled in
2051  for (unsigned i = 0; i != NumSrcElts; ++i)
2052  Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
2053  llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2054  Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
2055  } else {
2056  // We should never shorten the vector
2057  llvm_unreachable("unexpected shorten vector length");
2058  }
2059  } else {
2060  // If the Src is a scalar (not a vector) it must be updating one element.
2061  unsigned InIdx = getAccessedFieldNo(0, Elts);
2062  llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2063  Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2064  }
2065 
2067  Dst.isVolatileQualified());
2068 }
2069 
2070 /// @brief Store of global named registers are always calls to intrinsics.
2072  assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2073  "Bad type for register variable");
2074  llvm::MDNode *RegName = cast<llvm::MDNode>(
2075  cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2076  assert(RegName && "Register LValue is not metadata");
2077 
2078  // We accept integer and pointer types only
2079  llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2080  llvm::Type *Ty = OrigTy;
2081  if (OrigTy->isPointerTy())
2082  Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2083  llvm::Type *Types[] = { Ty };
2084 
2085  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2086  llvm::Value *Value = Src.getScalarVal();
2087  if (OrigTy->isPointerTy())
2088  Value = Builder.CreatePtrToInt(Value, Ty);
2089  Builder.CreateCall(
2090  F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2091 }
2092 
2093 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2094 // generating write-barries API. It is currently a global, ivar,
2095 // or neither.
2096 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2097  LValue &LV,
2098  bool IsMemberAccess=false) {
2099  if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2100  return;
2101 
2102  if (isa<ObjCIvarRefExpr>(E)) {
2103  QualType ExpTy = E->getType();
2104  if (IsMemberAccess && ExpTy->isPointerType()) {
2105  // If ivar is a structure pointer, assigning to field of
2106  // this struct follows gcc's behavior and makes it a non-ivar
2107  // writer-barrier conservatively.
2108  ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2109  if (ExpTy->isRecordType()) {
2110  LV.setObjCIvar(false);
2111  return;
2112  }
2113  }
2114  LV.setObjCIvar(true);
2115  auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2116  LV.setBaseIvarExp(Exp->getBase());
2117  LV.setObjCArray(E->getType()->isArrayType());
2118  return;
2119  }
2120 
2121  if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2122  if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2123  if (VD->hasGlobalStorage()) {
2124  LV.setGlobalObjCRef(true);
2125  LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2126  }
2127  }
2128  LV.setObjCArray(E->getType()->isArrayType());
2129  return;
2130  }
2131 
2132  if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2133  setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2134  return;
2135  }
2136 
2137  if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2138  setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2139  if (LV.isObjCIvar()) {
2140  // If cast is to a structure pointer, follow gcc's behavior and make it
2141  // a non-ivar write-barrier.
2142  QualType ExpTy = E->getType();
2143  if (ExpTy->isPointerType())
2144  ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2145  if (ExpTy->isRecordType())
2146  LV.setObjCIvar(false);
2147  }
2148  return;
2149  }
2150 
2151  if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2152  setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2153  return;
2154  }
2155 
2156  if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2157  setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2158  return;
2159  }
2160 
2161  if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2162  setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2163  return;
2164  }
2165 
2166  if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2167  setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2168  return;
2169  }
2170 
2171  if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2172  setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2173  if (LV.isObjCIvar() && !LV.isObjCArray())
2174  // Using array syntax to assigning to what an ivar points to is not
2175  // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2176  LV.setObjCIvar(false);
2177  else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2178  // Using array syntax to assigning to what global points to is not
2179  // same as assigning to the global itself. {id *G;} G[i] = 0;
2180  LV.setGlobalObjCRef(false);
2181  return;
2182  }
2183 
2184  if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2185  setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2186  // We don't know if member is an 'ivar', but this flag is looked at
2187  // only in the context of LV.isObjCIvar().
2188  LV.setObjCArray(E->getType()->isArrayType());
2189  return;
2190  }
2191 }
2192 
2193 static llvm::Value *
2195  llvm::Value *V, llvm::Type *IRType,
2196  StringRef Name = StringRef()) {
2197  unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2198  return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2199 }
2200 
2202  CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2203  llvm::Type *RealVarTy, SourceLocation Loc) {
2204  Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2205  Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2206  return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2207 }
2208 
2209 Address
2211  LValueBaseInfo *PointeeBaseInfo,
2212  TBAAAccessInfo *PointeeTBAAInfo) {
2213  llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2214  RefLVal.isVolatile());
2215  CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2216 
2218  PointeeBaseInfo, PointeeTBAAInfo,
2219  /* forPointeeType= */ true);
2220  return Address(Load, Align);
2221 }
2222 
2224  LValueBaseInfo PointeeBaseInfo;
2225  TBAAAccessInfo PointeeTBAAInfo;
2226  Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2227  &PointeeTBAAInfo);
2228  return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2229  PointeeBaseInfo, PointeeTBAAInfo);
2230 }
2231 
2233  const PointerType *PtrTy,
2234  LValueBaseInfo *BaseInfo,
2235  TBAAAccessInfo *TBAAInfo) {
2236  llvm::Value *Addr = Builder.CreateLoad(Ptr);
2237  return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2238  BaseInfo, TBAAInfo,
2239  /*forPointeeType=*/true));
2240 }
2241 
2243  const PointerType *PtrTy) {
2244  LValueBaseInfo BaseInfo;
2245  TBAAAccessInfo TBAAInfo;
2246  Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2247  return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2248 }
2249 
2251  const Expr *E, const VarDecl *VD) {
2252  QualType T = E->getType();
2253 
2254  // If it's thread_local, emit a call to its wrapper function instead.
2255  if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2257  return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2258 
2259  llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2260  llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2261  V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2262  CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2263  Address Addr(V, Alignment);
2264  // Emit reference to the private copy of the variable if it is an OpenMP
2265  // threadprivate variable.
2266  if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2267  VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2268  return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2269  E->getExprLoc());
2270  }
2271  LValue LV = VD->getType()->isReferenceType() ?
2272  CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2274  CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2275  setObjCGCLValueClass(CGF.getContext(), E, LV);
2276  return LV;
2277 }
2278 
2280  const FunctionDecl *FD) {
2281  if (FD->hasAttr<WeakRefAttr>()) {
2282  ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2283  return aliasee.getPointer();
2284  }
2285 
2286  llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2287  if (!FD->hasPrototype()) {
2288  if (const FunctionProtoType *Proto =
2289  FD->getType()->getAs<FunctionProtoType>()) {
2290  // Ugly case: for a K&R-style definition, the type of the definition
2291  // isn't the same as the type of a use. Correct for this with a
2292  // bitcast.
2293  QualType NoProtoType =
2294  CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2295  NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2296  V = llvm::ConstantExpr::getBitCast(V,
2297  CGM.getTypes().ConvertType(NoProtoType));
2298  }
2299  }
2300  return V;
2301 }
2302 
2304  const Expr *E, const FunctionDecl *FD) {
2305  llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2306  CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2307  return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2309 }
2310 
2312  llvm::Value *ThisValue) {
2314  LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2315  return CGF.EmitLValueForField(LV, FD);
2316 }
2317 
2318 /// Named Registers are named metadata pointing to the register name
2319 /// which will be read from/written to as an argument to the intrinsic
2320 /// @llvm.read/write_register.
2321 /// So far, only the name is being passed down, but other options such as
2322 /// register type, allocation type or even optimization options could be
2323 /// passed down via the metadata node.
2325  SmallString<64> Name("llvm.named.register.");
2326  AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2327  assert(Asm->getLabel().size() < 64-Name.size() &&
2328  "Register name too big");
2329  Name.append(Asm->getLabel());
2330  llvm::NamedMDNode *M =
2331  CGM.getModule().getOrInsertNamedMetadata(Name);
2332  if (M->getNumOperands() == 0) {
2333  llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2334  Asm->getLabel());
2335  llvm::Metadata *Ops[] = {Str};
2336  M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2337  }
2338 
2339  CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2340 
2341  llvm::Value *Ptr =
2342  llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2343  return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2344 }
2345 
2347  const NamedDecl *ND = E->getDecl();
2348  QualType T = E->getType();
2349 
2350  if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2351  // Global Named registers access via intrinsics only
2352  if (VD->getStorageClass() == SC_Register &&
2353  VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2354  return EmitGlobalNamedRegister(VD, CGM);
2355 
2356  // A DeclRefExpr for a reference initialized by a constant expression can
2357  // appear without being odr-used. Directly emit the constant initializer.
2358  const Expr *Init = VD->getAnyInitializer(VD);
2359  if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2360  VD->isUsableInConstantExpressions(getContext()) &&
2361  VD->checkInitIsICE() &&
2362  // Do not emit if it is private OpenMP variable.
2364  ((CapturedStmtInfo &&
2365  (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2366  CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2367  LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2368  isa<BlockDecl>(CurCodeDecl)))) {
2369  llvm::Constant *Val =
2371  *VD->evaluateValue(),
2372  VD->getType());
2373  assert(Val && "failed to emit reference constant expression");
2374  // FIXME: Eventually we will want to emit vector element references.
2375 
2376  // Should we be using the alignment of the constant pointer we emitted?
2377  CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2378  /* BaseInfo= */ nullptr,
2379  /* TBAAInfo= */ nullptr,
2380  /* forPointeeType= */ true);
2381  return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2382  }
2383 
2384  // Check for captured variables.
2386  VD = VD->getCanonicalDecl();
2387  if (auto *FD = LambdaCaptureFields.lookup(VD))
2388  return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2389  else if (CapturedStmtInfo) {
2390  auto I = LocalDeclMap.find(VD);
2391  if (I != LocalDeclMap.end()) {
2392  if (VD->getType()->isReferenceType())
2393  return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2395  return MakeAddrLValue(I->second, T);
2396  }
2397  LValue CapLVal =
2400  return MakeAddrLValue(
2401  Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2403  CapLVal.getTBAAInfo());
2404  }
2405 
2406  assert(isa<BlockDecl>(CurCodeDecl));
2407  Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2408  return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2409  }
2410  }
2411 
2412  // FIXME: We should be able to assert this for FunctionDecls as well!
2413  // FIXME: We should be able to assert this for all DeclRefExprs, not just
2414  // those with a valid source location.
2415  assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2416  !E->getLocation().isValid()) &&
2417  "Should not use decl without marking it used!");
2418 
2419  if (ND->hasAttr<WeakRefAttr>()) {
2420  const auto *VD = cast<ValueDecl>(ND);
2421  ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2422  return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2423  }
2424 
2425  if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2426  // Check if this is a global variable.
2427  if (VD->hasLinkage() || VD->isStaticDataMember())
2428  return EmitGlobalVarDeclLValue(*this, E, VD);
2429 
2430  Address addr = Address::invalid();
2431 
2432  // The variable should generally be present in the local decl map.
2433  auto iter = LocalDeclMap.find(VD);
2434  if (iter != LocalDeclMap.end()) {
2435  addr = iter->second;
2436 
2437  // Otherwise, it might be static local we haven't emitted yet for
2438  // some reason; most likely, because it's in an outer function.
2439  } else if (VD->isStaticLocal()) {
2441  *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2442  getContext().getDeclAlign(VD));
2443 
2444  // No other cases for now.
2445  } else {
2446  llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2447  }
2448 
2449 
2450  // Check for OpenMP threadprivate variables.
2451  if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2452  VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2454  *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2455  E->getExprLoc());
2456  }
2457 
2458  // Drill into block byref variables.
2459  bool isBlockByref = VD->hasAttr<BlocksAttr>();
2460  if (isBlockByref) {
2461  addr = emitBlockByrefAddress(addr, VD);
2462  }
2463 
2464  // Drill into reference types.
2465  LValue LV = VD->getType()->isReferenceType() ?
2468 
2469  bool isLocalStorage = VD->hasLocalStorage();
2470 
2471  bool NonGCable = isLocalStorage &&
2472  !VD->getType()->isReferenceType() &&
2473  !isBlockByref;
2474  if (NonGCable) {
2475  LV.getQuals().removeObjCGCAttr();
2476  LV.setNonGC(true);
2477  }
2478 
2479  bool isImpreciseLifetime =
2480  (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2481  if (isImpreciseLifetime)
2483  setObjCGCLValueClass(getContext(), E, LV);
2484  return LV;
2485  }
2486 
2487  if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2488  return EmitFunctionDeclLValue(*this, E, FD);
2489 
2490  // FIXME: While we're emitting a binding from an enclosing scope, all other
2491  // DeclRefExprs we see should be implicitly treated as if they also refer to
2492  // an enclosing scope.
2493  if (const auto *BD = dyn_cast<BindingDecl>(ND))
2494  return EmitLValue(BD->getBinding());
2495 
2496  llvm_unreachable("Unhandled DeclRefExpr");
2497 }
2498 
2500  // __extension__ doesn't affect lvalue-ness.
2501  if (E->getOpcode() == UO_Extension)
2502  return EmitLValue(E->getSubExpr());
2503 
2505  switch (E->getOpcode()) {
2506  default: llvm_unreachable("Unknown unary operator lvalue!");
2507  case UO_Deref: {
2509  assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2510 
2511  LValueBaseInfo BaseInfo;
2512  TBAAAccessInfo TBAAInfo;
2513  Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2514  &TBAAInfo);
2515  LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2516  LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2517 
2518  // We should not generate __weak write barrier on indirect reference
2519  // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2520  // But, we continue to generate __strong write barrier on indirect write
2521  // into a pointer to object.
2522  if (getLangOpts().ObjC1 &&
2523  getLangOpts().getGC() != LangOptions::NonGC &&
2524  LV.isObjCWeak())
2525  LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2526  return LV;
2527  }
2528  case UO_Real:
2529  case UO_Imag: {
2530  LValue LV = EmitLValue(E->getSubExpr());
2531  assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2532 
2533  // __real is valid on scalars. This is a faster way of testing that.
2534  // __imag can only produce an rvalue on scalars.
2535  if (E->getOpcode() == UO_Real &&
2536  !LV.getAddress().getElementType()->isStructTy()) {
2537  assert(E->getSubExpr()->getType()->isArithmeticType());
2538  return LV;
2539  }
2540 
2541  QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2542 
2543  Address Component =
2544  (E->getOpcode() == UO_Real
2547  LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2548  CGM.getTBAAInfoForSubobject(LV, T));
2549  ElemLV.getQuals().addQualifiers(LV.getQuals());
2550  return ElemLV;
2551  }
2552  case UO_PreInc:
2553  case UO_PreDec: {
2554  LValue LV = EmitLValue(E->getSubExpr());
2555  bool isInc = E->getOpcode() == UO_PreInc;
2556 
2557  if (E->getType()->isAnyComplexType())
2558  EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2559  else
2560  EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2561  return LV;
2562  }
2563  }
2564 }
2565 
2569 }
2570 
2574 }
2575 
2577  auto SL = E->getFunctionName();
2578  assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2579  StringRef FnName = CurFn->getName();
2580  if (FnName.startswith("\01"))
2581  FnName = FnName.substr(1);
2582  StringRef NameItems[] = {
2584  std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2585  if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2586  std::string Name = SL->getString();
2587  if (!Name.empty()) {
2588  unsigned Discriminator =
2589  CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2590  if (Discriminator)
2591  Name += "_" + Twine(Discriminator + 1).str();
2592  auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2593  return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2594  } else {
2595  auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2596  return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2597  }
2598  }
2599  auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2600  return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2601 }
2602 
2603 /// Emit a type description suitable for use by a runtime sanitizer library. The
2604 /// format of a type descriptor is
2605 ///
2606 /// \code
2607 /// { i16 TypeKind, i16 TypeInfo }
2608 /// \endcode
2609 ///
2610 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2611 /// integer, 1 for a floating point value, and -1 for anything else.
2613  // Only emit each type's descriptor once.
2614  if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2615  return C;
2616 
2617  uint16_t TypeKind = -1;
2618  uint16_t TypeInfo = 0;
2619 
2620  if (T->isIntegerType()) {
2621  TypeKind = 0;
2622  TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2623  (T->isSignedIntegerType() ? 1 : 0);
2624  } else if (T->isFloatingType()) {
2625  TypeKind = 1;
2626  TypeInfo = getContext().getTypeSize(T);
2627  }
2628 
2629  // Format the type name as if for a diagnostic, including quotes and
2630  // optionally an 'aka'.
2631  SmallString<32> Buffer;
2633  (intptr_t)T.getAsOpaquePtr(),
2634  StringRef(), StringRef(), None, Buffer,
2635  None);
2636 
2637  llvm::Constant *Components[] = {
2638  Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2639  llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2640  };
2641  llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2642 
2643  auto *GV = new llvm::GlobalVariable(
2644  CGM.getModule(), Descriptor->getType(),
2645  /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2646  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2648 
2649  // Remember the descriptor for this type.
2650  CGM.setTypeDescriptorInMap(T, GV);
2651 
2652  return GV;
2653 }
2654 
2656  llvm::Type *TargetTy = IntPtrTy;
2657 
2658  if (V->getType() == TargetTy)
2659  return V;
2660 
2661  // Floating-point types which fit into intptr_t are bitcast to integers
2662  // and then passed directly (after zero-extension, if necessary).
2663  if (V->getType()->isFloatingPointTy()) {
2664  unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2665  if (Bits <= TargetTy->getIntegerBitWidth())
2666  V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2667  Bits));
2668  }
2669 
2670  // Integers which fit in intptr_t are zero-extended and passed directly.
2671  if (V->getType()->isIntegerTy() &&
2672  V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2673  return Builder.CreateZExt(V, TargetTy);
2674 
2675  // Pointers are passed directly, everything else is passed by address.
2676  if (!V->getType()->isPointerTy()) {
2677  Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2678  Builder.CreateStore(V, Ptr);
2679  V = Ptr.getPointer();
2680  }
2681  return Builder.CreatePtrToInt(V, TargetTy);
2682 }
2683 
2684 /// \brief Emit a representation of a SourceLocation for passing to a handler
2685 /// in a sanitizer runtime library. The format for this data is:
2686 /// \code
2687 /// struct SourceLocation {
2688 /// const char *Filename;
2689 /// int32_t Line, Column;
2690 /// };
2691 /// \endcode
2692 /// For an invalid SourceLocation, the Filename pointer is null.
2694  llvm::Constant *Filename;
2695  int Line, Column;
2696 
2698  if (PLoc.isValid()) {
2699  StringRef FilenameString = PLoc.getFilename();
2700 
2701  int PathComponentsToStrip =
2702  CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2703  if (PathComponentsToStrip < 0) {
2704  assert(PathComponentsToStrip != INT_MIN);
2705  int PathComponentsToKeep = -PathComponentsToStrip;
2706  auto I = llvm::sys::path::rbegin(FilenameString);
2707  auto E = llvm::sys::path::rend(FilenameString);
2708  while (I != E && --PathComponentsToKeep)
2709  ++I;
2710 
2711  FilenameString = FilenameString.substr(I - E);
2712  } else if (PathComponentsToStrip > 0) {
2713  auto I = llvm::sys::path::begin(FilenameString);
2714  auto E = llvm::sys::path::end(FilenameString);
2715  while (I != E && PathComponentsToStrip--)
2716  ++I;
2717 
2718  if (I != E)
2719  FilenameString =
2720  FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2721  else
2722  FilenameString = llvm::sys::path::filename(FilenameString);
2723  }
2724 
2725  auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2727  cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2728  Filename = FilenameGV.getPointer();
2729  Line = PLoc.getLine();
2730  Column = PLoc.getColumn();
2731  } else {
2732  Filename = llvm::Constant::getNullValue(Int8PtrTy);
2733  Line = Column = 0;
2734  }
2735 
2736  llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2737  Builder.getInt32(Column)};
2738 
2739  return llvm::ConstantStruct::getAnon(Data);
2740 }
2741 
2742 namespace {
2743 /// \brief Specify under what conditions this check can be recovered
2745  /// Always terminate program execution if this check fails.
2746  Unrecoverable,
2747  /// Check supports recovering, runtime has both fatal (noreturn) and
2748  /// non-fatal handlers for this check.
2749  Recoverable,
2750  /// Runtime conditionally aborts, always need to support recovery.
2751  AlwaysRecoverable
2752 };
2753 }
2754 
2756  assert(llvm::countPopulation(Kind) == 1);
2757  switch (Kind) {
2758  case SanitizerKind::Vptr:
2759  return CheckRecoverableKind::AlwaysRecoverable;
2760  case SanitizerKind::Return:
2761  case SanitizerKind::Unreachable:
2763  default:
2764  return CheckRecoverableKind::Recoverable;
2765  }
2766 }
2767 
2768 namespace {
2769 struct SanitizerHandlerInfo {
2770  char const *const Name;
2771  unsigned Version;
2772 };
2773 }
2774 
2775 const SanitizerHandlerInfo SanitizerHandlers[] = {
2776 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2778 #undef SANITIZER_CHECK
2779 };
2780 
2782  llvm::FunctionType *FnType,
2783  ArrayRef<llvm::Value *> FnArgs,
2784  SanitizerHandler CheckHandler,
2785  CheckRecoverableKind RecoverKind, bool IsFatal,
2786  llvm::BasicBlock *ContBB) {
2787  assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2788  bool NeedsAbortSuffix =
2789  IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2790  bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
2791  const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2792  const StringRef CheckName = CheckInfo.Name;
2793  std::string FnName = "__ubsan_handle_" + CheckName.str();
2794  if (CheckInfo.Version && !MinimalRuntime)
2795  FnName += "_v" + llvm::utostr(CheckInfo.Version);
2796  if (MinimalRuntime)
2797  FnName += "_minimal";
2798  if (NeedsAbortSuffix)
2799  FnName += "_abort";
2800  bool MayReturn =
2801  !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2802 
2803  llvm::AttrBuilder B;
2804  if (!MayReturn) {
2805  B.addAttribute(llvm::Attribute::NoReturn)
2806  .addAttribute(llvm::Attribute::NoUnwind);
2807  }
2808  B.addAttribute(llvm::Attribute::UWTable);
2809 
2811  FnType, FnName,
2812  llvm::AttributeList::get(CGF.getLLVMContext(),
2813  llvm::AttributeList::FunctionIndex, B),
2814  /*Local=*/true);
2815  llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2816  if (!MayReturn) {
2817  HandlerCall->setDoesNotReturn();
2818  CGF.Builder.CreateUnreachable();
2819  } else {
2820  CGF.Builder.CreateBr(ContBB);
2821  }
2822 }
2823 
2825  ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2826  SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2827  ArrayRef<llvm::Value *> DynamicArgs) {
2828  assert(IsSanitizerScope);
2829  assert(Checked.size() > 0);
2830  assert(CheckHandler >= 0 &&
2831  size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
2832  const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2833 
2834  llvm::Value *FatalCond = nullptr;
2835  llvm::Value *RecoverableCond = nullptr;
2836  llvm::Value *TrapCond = nullptr;
2837  for (int i = 0, n = Checked.size(); i < n; ++i) {
2838  llvm::Value *Check = Checked[i].first;
2839  // -fsanitize-trap= overrides -fsanitize-recover=.
2840  llvm::Value *&Cond =
2841  CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2842  ? TrapCond
2843  : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2844  ? RecoverableCond
2845  : FatalCond;
2846  Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2847  }
2848 
2849  if (TrapCond)
2850  EmitTrapCheck(TrapCond);
2851  if (!FatalCond && !RecoverableCond)
2852  return;
2853 
2854  llvm::Value *JointCond;
2855  if (FatalCond && RecoverableCond)
2856  JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2857  else
2858  JointCond = FatalCond ? FatalCond : RecoverableCond;
2859  assert(JointCond);
2860 
2861  CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2862  assert(SanOpts.has(Checked[0].second));
2863 #ifndef NDEBUG
2864  for (int i = 1, n = Checked.size(); i < n; ++i) {
2865  assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2866  "All recoverable kinds in a single check must be same!");
2867  assert(SanOpts.has(Checked[i].second));
2868  }
2869 #endif
2870 
2871  llvm::BasicBlock *Cont = createBasicBlock("cont");
2872  llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2873  llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2874  // Give hint that we very much don't expect to execute the handler
2875  // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2876  llvm::MDBuilder MDHelper(getLLVMContext());
2877  llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2878  Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2879  EmitBlock(Handlers);
2880 
2881  // Handler functions take an i8* pointing to the (handler-specific) static
2882  // information block, followed by a sequence of intptr_t arguments
2883  // representing operand values.
2886  if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2887  Args.reserve(DynamicArgs.size() + 1);
2888  ArgTypes.reserve(DynamicArgs.size() + 1);
2889 
2890  // Emit handler arguments and create handler function type.
2891  if (!StaticArgs.empty()) {
2892  llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2893  auto *InfoPtr =
2894  new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2895  llvm::GlobalVariable::PrivateLinkage, Info);
2896  InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2898  Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2899  ArgTypes.push_back(Int8PtrTy);
2900  }
2901 
2902  for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2903  Args.push_back(EmitCheckValue(DynamicArgs[i]));
2904  ArgTypes.push_back(IntPtrTy);
2905  }
2906  }
2907 
2908  llvm::FunctionType *FnType =
2909  llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2910 
2911  if (!FatalCond || !RecoverableCond) {
2912  // Simple case: we need to generate a single handler call, either
2913  // fatal, or non-fatal.
2914  emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2915  (FatalCond != nullptr), Cont);
2916  } else {
2917  // Emit two handler calls: first one for set of unrecoverable checks,
2918  // another one for recoverable.
2919  llvm::BasicBlock *NonFatalHandlerBB =
2920  createBasicBlock("non_fatal." + CheckName);
2921  llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2922  Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2923  EmitBlock(FatalHandlerBB);
2924  emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2925  NonFatalHandlerBB);
2926  EmitBlock(NonFatalHandlerBB);
2927  emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2928  Cont);
2929  }
2930 
2931  EmitBlock(Cont);
2932 }
2933 
2935  SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2936  llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2937  llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2938 
2939  llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2940  llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2941 
2942  llvm::MDBuilder MDHelper(getLLVMContext());
2943  llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2944  BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2945 
2946  EmitBlock(CheckBB);
2947 
2948  bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2949 
2950  llvm::CallInst *CheckCall;
2951  if (WithDiag) {
2952  llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2953  auto *InfoPtr =
2954  new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2955  llvm::GlobalVariable::PrivateLinkage, Info);
2956  InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2958 
2959  llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2960  "__cfi_slowpath_diag",
2961  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2962  false));
2963  CheckCall = Builder.CreateCall(
2964  SlowPathDiagFn,
2965  {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2966  } else {
2967  llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2968  "__cfi_slowpath",
2969  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2970  CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2971  }
2972 
2973  CheckCall->setDoesNotThrow();
2974 
2975  EmitBlock(Cont);
2976 }
2977 
2978 // Emit a stub for __cfi_check function so that the linker knows about this
2979 // symbol in LTO mode.
2981  llvm::Module *M = &CGM.getModule();
2982  auto &Ctx = M->getContext();
2983  llvm::Function *F = llvm::Function::Create(
2984  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2985  llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2986  llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2987  // FIXME: consider emitting an intrinsic call like
2988  // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2989  // which can be lowered in CrossDSOCFI pass to the actual contents of
2990  // __cfi_check. This would allow inlining of __cfi_check calls.
2992  llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2993  llvm::ReturnInst::Create(Ctx, nullptr, BB);
2994 }
2995 
2996 // This function is basically a switch over the CFI failure kind, which is
2997 // extracted from CFICheckFailData (1st function argument). Each case is either
2998 // llvm.trap or a call to one of the two runtime handlers, based on
2999 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3000 // failure kind) traps, but this should really never happen. CFICheckFailData
3001 // can be nullptr if the calling module has -fsanitize-trap behavior for this
3002 // check kind; in this case __cfi_check_fail traps as well.
3004  SanitizerScope SanScope(this);
3005  FunctionArgList Args;
3010  Args.push_back(&ArgData);
3011  Args.push_back(&ArgAddr);
3012 
3013  const CGFunctionInfo &FI =
3015 
3016  llvm::Function *F = llvm::Function::Create(
3017  llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3018  llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3019  F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3020 
3021  StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3022  SourceLocation());
3023 
3024  llvm::Value *Data =
3025  EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3026  CGM.getContext().VoidPtrTy, ArgData.getLocation());
3027  llvm::Value *Addr =
3028  EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3029  CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3030 
3031  // Data == nullptr means the calling module has trap behaviour for this check.
3032  llvm::Value *DataIsNotNullPtr =
3033  Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3034  EmitTrapCheck(DataIsNotNullPtr);
3035 
3036  llvm::StructType *SourceLocationTy =
3037  llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3038  llvm::StructType *CfiCheckFailDataTy =
3039  llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3040 
3041  llvm::Value *V = Builder.CreateConstGEP2_32(
3042  CfiCheckFailDataTy,
3043  Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3044  0);
3045  Address CheckKindAddr(V, getIntAlign());
3046  llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3047 
3048  llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3049  CGM.getLLVMContext(),
3050  llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3051  llvm::Value *ValidVtable = Builder.CreateZExt(
3052  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3053  {Addr, AllVtables}),
3054  IntPtrTy);
3055 
3056  const std::pair<int, SanitizerMask> CheckKinds[] = {
3057  {CFITCK_VCall, SanitizerKind::CFIVCall},
3058  {CFITCK_NVCall, SanitizerKind::CFINVCall},
3059  {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3060  {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3061  {CFITCK_ICall, SanitizerKind::CFIICall}};
3062 
3064  for (auto CheckKindMaskPair : CheckKinds) {
3065  int Kind = CheckKindMaskPair.first;
3066  SanitizerMask Mask = CheckKindMaskPair.second;
3067  llvm::Value *Cond =
3068  Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3069  if (CGM.getLangOpts().Sanitize.has(Mask))
3070  EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3071  {Data, Addr, ValidVtable});
3072  else
3073  EmitTrapCheck(Cond);
3074  }
3075 
3076  FinishFunction();
3077  // The only reference to this function will be created during LTO link.
3078  // Make sure it survives until then.
3079  CGM.addUsedGlobal(F);
3080 }
3081 
3083  if (SanOpts.has(SanitizerKind::Unreachable)) {
3084  SanitizerScope SanScope(this);
3085  EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3086  SanitizerKind::Unreachable),
3087  SanitizerHandler::BuiltinUnreachable,
3088  EmitCheckSourceLocation(Loc), None);
3089  }
3090  Builder.CreateUnreachable();
3091 }
3092 
3094  llvm::BasicBlock *Cont = createBasicBlock("cont");
3095 
3096  // If we're optimizing, collapse all calls to trap down to just one per
3097  // function to save on code size.
3098  if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3099  TrapBB = createBasicBlock("trap");
3100  Builder.CreateCondBr(Checked, Cont, TrapBB);
3101  EmitBlock(TrapBB);
3102  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3103  TrapCall->setDoesNotReturn();
3104  TrapCall->setDoesNotThrow();
3105  Builder.CreateUnreachable();
3106  } else {
3107  Builder.CreateCondBr(Checked, Cont, TrapBB);
3108  }
3109 
3110  EmitBlock(Cont);
3111 }
3112 
3114  llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3115 
3116  if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3117  auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3119  TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3120  }
3121 
3122  return TrapCall;
3123 }
3124 
3126  LValueBaseInfo *BaseInfo,
3127  TBAAAccessInfo *TBAAInfo) {
3128  assert(E->getType()->isArrayType() &&
3129  "Array to pointer decay must have array source type!");
3130 
3131  // Expressions of array type can't be bitfields or vector elements.
3132  LValue LV = EmitLValue(E);
3133  Address Addr = LV.getAddress();
3134 
3135  // If the array type was an incomplete type, we need to make sure
3136  // the decay ends up being the right type.
3137  llvm::Type *NewTy = ConvertType(E->getType());
3138  Addr = Builder.CreateElementBitCast(Addr, NewTy);
3139 
3140  // Note that VLA pointers are always decayed, so we don't need to do
3141  // anything here.
3142  if (!E->getType()->isVariableArrayType()) {
3143  assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3144  "Expected pointer to array");
3145  Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3146  }
3147 
3148  // The result of this decay conversion points to an array element within the
3149  // base lvalue. However, since TBAA currently does not support representing
3150  // accesses to elements of member arrays, we conservatively represent accesses
3151  // to the pointee object as if it had no any base lvalue specified.
3152  // TODO: Support TBAA for member arrays.
3154  if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3155  if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3156 
3157  return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3158 }
3159 
3160 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3161 /// array to pointer, return the array subexpression.
3162 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3163  // If this isn't just an array->pointer decay, bail out.
3164  const auto *CE = dyn_cast<CastExpr>(E);
3165  if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3166  return nullptr;
3167 
3168  // If this is a decay from variable width array, bail out.
3169  const Expr *SubExpr = CE->getSubExpr();
3170  if (SubExpr->getType()->isVariableArrayType())
3171  return nullptr;
3172 
3173  return SubExpr;
3174 }
3175 
3177  llvm::Value *ptr,
3178  ArrayRef<llvm::Value*> indices,
3179  bool inbounds,
3180  bool signedIndices,
3181  SourceLocation loc,
3182  const llvm::Twine &name = "arrayidx") {
3183  if (inbounds) {
3184  return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3186  name);
3187  } else {
3188  return CGF.Builder.CreateGEP(ptr, indices, name);
3189  }
3190 }
3191 
3193  llvm::Value *idx,
3194  CharUnits eltSize) {
3195  // If we have a constant index, we can use the exact offset of the
3196  // element we're accessing.
3197  if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3198  CharUnits offset = constantIdx->getZExtValue() * eltSize;
3199  return arrayAlign.alignmentAtOffset(offset);
3200 
3201  // Otherwise, use the worst-case alignment for any element.
3202  } else {
3203  return arrayAlign.alignmentOfArrayElement(eltSize);
3204  }
3205 }
3206 
3208  const VariableArrayType *vla) {
3209  QualType eltType;
3210  do {
3211  eltType = vla->getElementType();
3212  } while ((vla = ctx.getAsVariableArrayType(eltType)));
3213  return eltType;
3214 }
3215 
3217  ArrayRef<llvm::Value *> indices,
3218  QualType eltType, bool inbounds,
3219  bool signedIndices, SourceLocation loc,
3220  const llvm::Twine &name = "arrayidx") {
3221  // All the indices except that last must be zero.
3222 #ifndef NDEBUG
3223  for (auto idx : indices.drop_back())
3224  assert(isa<llvm::ConstantInt>(idx) &&
3225  cast<llvm::ConstantInt>(idx)->isZero());
3226 #endif
3227 
3228  // Determine the element size of the statically-sized base. This is
3229  // the thing that the indices are expressed in terms of.
3230  if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3231  eltType = getFixedSizeElementType(CGF.getContext(), vla);
3232  }
3233 
3234  // We can use that to compute the best alignment of the element.
3235  CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3236  CharUnits eltAlign =
3237  getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3238 
3240  CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
3241  return Address(eltPtr, eltAlign);
3242 }
3243 
3245  bool Accessed) {
3246  // The index must always be an integer, which is not an aggregate. Emit it
3247  // in lexical order (this complexity is, sadly, required by C++17).
3248  llvm::Value *IdxPre =
3249  (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3250  bool SignedIndices = false;
3251  auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3252  auto *Idx = IdxPre;
3253  if (E->getLHS() != E->getIdx()) {
3254  assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3255  Idx = EmitScalarExpr(E->getIdx());
3256  }
3257 
3258  QualType IdxTy = E->getIdx()->getType();
3259  bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3260  SignedIndices |= IdxSigned;
3261 
3262  if (SanOpts.has(SanitizerKind::ArrayBounds))
3263  EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3264 
3265  // Extend or truncate the index type to 32 or 64-bits.
3266  if (Promote && Idx->getType() != IntPtrTy)
3267  Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3268 
3269  return Idx;
3270  };
3271  IdxPre = nullptr;
3272 
3273  // If the base is a vector type, then we are forming a vector element lvalue
3274  // with this subscript.
3275  if (E->getBase()->getType()->isVectorType() &&
3276  !isa<ExtVectorElementExpr>(E->getBase())) {
3277  // Emit the vector as an lvalue to get its address.
3278  LValue LHS = EmitLValue(E->getBase());
3279  auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3280  assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3281  return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3282  LHS.getBaseInfo(), TBAAAccessInfo());
3283  }
3284 
3285  // All the other cases basically behave like simple offsetting.
3286 
3287  // Handle the extvector case we ignored above.
3288  if (isa<ExtVectorElementExpr>(E->getBase())) {
3289  LValue LV = EmitLValue(E->getBase());
3290  auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3292 
3293  QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3294  Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3295  SignedIndices, E->getExprLoc());
3296  return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3297  CGM.getTBAAInfoForSubobject(LV, EltType));
3298  }
3299 
3300  LValueBaseInfo EltBaseInfo;
3301  TBAAAccessInfo EltTBAAInfo;
3302  Address Addr = Address::invalid();
3303  if (const VariableArrayType *vla =
3304  getContext().getAsVariableArrayType(E->getType())) {
3305  // The base must be a pointer, which is not an aggregate. Emit
3306  // it. It needs to be emitted first in case it's what captures
3307  // the VLA bounds.
3308  Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3309  auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3310 
3311  // The element count here is the total number of non-VLA elements.
3312  llvm::Value *numElements = getVLASize(vla).first;
3313 
3314  // Effectively, the multiply by the VLA size is part of the GEP.
3315  // GEP indexes are signed, and scaling an index isn't permitted to
3316  // signed-overflow, so we use the same semantics for our explicit
3317  // multiply. We suppress this if overflow is not undefined behavior.
3318  if (getLangOpts().isSignedOverflowDefined()) {
3319  Idx = Builder.CreateMul(Idx, numElements);
3320  } else {
3321  Idx = Builder.CreateNSWMul(Idx, numElements);
3322  }
3323 
3324  Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3326  SignedIndices, E->getExprLoc());
3327 
3328  } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3329  // Indexing over an interface, as in "NSString *P; P[4];"
3330 
3331  // Emit the base pointer.
3332  Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3333  auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3334 
3335  CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3336  llvm::Value *InterfaceSizeVal =
3337  llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3338 
3339  llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3340 
3341  // We don't necessarily build correct LLVM struct types for ObjC
3342  // interfaces, so we can't rely on GEP to do this scaling
3343  // correctly, so we need to cast to i8*. FIXME: is this actually
3344  // true? A lot of other things in the fragile ABI would break...
3345  llvm::Type *OrigBaseTy = Addr.getType();
3346  Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3347 
3348  // Do the GEP.
3349  CharUnits EltAlign =
3350  getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3351  llvm::Value *EltPtr =
3352  emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3353  SignedIndices, E->getExprLoc());
3354  Addr = Address(EltPtr, EltAlign);
3355 
3356  // Cast back.
3357  Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3358  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3359  // If this is A[i] where A is an array, the frontend will have decayed the
3360  // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3361  // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3362  // "gep x, i" here. Emit one "gep A, 0, i".
3363  assert(Array->getType()->isArrayType() &&
3364  "Array to pointer decay must have array source type!");
3365  LValue ArrayLV;
3366  // For simple multidimensional array indexing, set the 'accessed' flag for
3367  // better bounds-checking of the base expression.
3368  if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3369  ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3370  else
3371  ArrayLV = EmitLValue(Array);
3372  auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3373 
3374  // Propagate the alignment from the array itself to the result.
3375  Addr = emitArraySubscriptGEP(
3376  *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3377  E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3378  E->getExprLoc());
3379  EltBaseInfo = ArrayLV.getBaseInfo();
3380  EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3381  } else {
3382  // The base must be a pointer; emit it with an estimate of its alignment.
3383  Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3384  auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3385  Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3387  SignedIndices, E->getExprLoc());
3388  }
3389 
3390  LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3391 
3392  if (getLangOpts().ObjC1 &&
3393  getLangOpts().getGC() != LangOptions::NonGC) {
3395  setObjCGCLValueClass(getContext(), E, LV);
3396  }
3397  return LV;
3398 }
3399 
3401  LValueBaseInfo &BaseInfo,
3402  TBAAAccessInfo &TBAAInfo,
3403  QualType BaseTy, QualType ElTy,
3404  bool IsLowerBound) {
3405  LValue BaseLVal;
3406  if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3407  BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3408  if (BaseTy->isArrayType()) {
3409  Address Addr = BaseLVal.getAddress();
3410  BaseInfo = BaseLVal.getBaseInfo();
3411 
3412  // If the array type was an incomplete type, we need to make sure
3413  // the decay ends up being the right type.
3414  llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3415  Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3416 
3417  // Note that VLA pointers are always decayed, so we don't need to do
3418  // anything here.
3419  if (!BaseTy->isVariableArrayType()) {
3420  assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3421  "Expected pointer to array");
3422  Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3423  "arraydecay");
3424  }
3425 
3426  return CGF.Builder.CreateElementBitCast(Addr,
3427  CGF.ConvertTypeForMem(ElTy));
3428  }
3429  LValueBaseInfo TypeBaseInfo;
3430  TBAAAccessInfo TypeTBAAInfo;
3431  CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3432  &TypeTBAAInfo);
3433  BaseInfo.mergeForCast(TypeBaseInfo);
3434  TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3435  return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3436  }
3437  return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3438 }
3439 
3441  bool IsLowerBound) {
3443  QualType ResultExprTy;
3444  if (auto *AT = getContext().getAsArrayType(BaseTy))
3445  ResultExprTy = AT->getElementType();
3446  else
3447  ResultExprTy = BaseTy->getPointeeType();
3448  llvm::Value *Idx = nullptr;
3449  if (IsLowerBound || E->getColonLoc().isInvalid()) {
3450  // Requesting lower bound or upper bound, but without provided length and
3451  // without ':' symbol for the default length -> length = 1.
3452  // Idx = LowerBound ?: 0;
3453  if (auto *LowerBound = E->getLowerBound()) {
3454  Idx = Builder.CreateIntCast(
3455  EmitScalarExpr(LowerBound), IntPtrTy,
3456  LowerBound->getType()->hasSignedIntegerRepresentation());
3457  } else
3458  Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3459  } else {
3460  // Try to emit length or lower bound as constant. If this is possible, 1
3461  // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3462  // IR (LB + Len) - 1.
3463  auto &C = CGM.getContext();
3464  auto *Length = E->getLength();
3465  llvm::APSInt ConstLength;
3466  if (Length) {
3467  // Idx = LowerBound + Length - 1;
3468  if (Length->isIntegerConstantExpr(ConstLength, C)) {
3469  ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3470  Length = nullptr;
3471  }
3472  auto *LowerBound = E->getLowerBound();
3473  llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3474  if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3475  ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3476  LowerBound = nullptr;
3477  }
3478  if (!Length)
3479  --ConstLength;
3480  else if (!LowerBound)
3481  --ConstLowerBound;
3482 
3483  if (Length || LowerBound) {
3484  auto *LowerBoundVal =
3485  LowerBound
3486  ? Builder.CreateIntCast(
3487  EmitScalarExpr(LowerBound), IntPtrTy,
3488  LowerBound->getType()->hasSignedIntegerRepresentation())
3489  : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3490  auto *LengthVal =
3491  Length
3492  ? Builder.CreateIntCast(
3493  EmitScalarExpr(Length), IntPtrTy,
3494  Length->getType()->hasSignedIntegerRepresentation())
3495  : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3496  Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3497  /*HasNUW=*/false,
3498  !getLangOpts().isSignedOverflowDefined());
3499  if (Length && LowerBound) {
3500  Idx = Builder.CreateSub(
3501  Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3502  /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3503  }
3504  } else
3505  Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3506  } else {
3507  // Idx = ArraySize - 1;
3508  QualType ArrayTy = BaseTy->isPointerType()
3509  ? E->getBase()->IgnoreParenImpCasts()->getType()
3510  : BaseTy;
3511  if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3512  Length = VAT->getSizeExpr();
3513  if (Length->isIntegerConstantExpr(ConstLength, C))
3514  Length = nullptr;
3515  } else {
3516  auto *CAT = C.getAsConstantArrayType(ArrayTy);
3517  ConstLength = CAT->getSize();
3518  }
3519  if (Length) {
3520  auto *LengthVal = Builder.CreateIntCast(
3521  EmitScalarExpr(Length), IntPtrTy,
3522  Length->getType()->hasSignedIntegerRepresentation());
3523  Idx = Builder.CreateSub(
3524  LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3525  /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3526  } else {
3527  ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3528  --ConstLength;
3529  Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3530  }
3531  }
3532  }
3533  assert(Idx);
3534 
3535  Address EltPtr = Address::invalid();
3536  LValueBaseInfo BaseInfo;
3537  TBAAAccessInfo TBAAInfo;
3538  if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3539  // The base must be a pointer, which is not an aggregate. Emit
3540  // it. It needs to be emitted first in case it's what captures
3541  // the VLA bounds.
3542  Address Base =
3543  emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3544  BaseTy, VLA->getElementType(), IsLowerBound);
3545  // The element count here is the total number of non-VLA elements.
3546  llvm::Value *NumElements = getVLASize(VLA).first;
3547 
3548  // Effectively, the multiply by the VLA size is part of the GEP.
3549  // GEP indexes are signed, and scaling an index isn't permitted to
3550  // signed-overflow, so we use the same semantics for our explicit
3551  // multiply. We suppress this if overflow is not undefined behavior.
3552  if (getLangOpts().isSignedOverflowDefined())
3553  Idx = Builder.CreateMul(Idx, NumElements);
3554  else
3555  Idx = Builder.CreateNSWMul(Idx, NumElements);
3556  EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3558  /*SignedIndices=*/false, E->getExprLoc());
3559  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3560  // If this is A[i] where A is an array, the frontend will have decayed the
3561  // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3562  // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3563  // "gep x, i" here. Emit one "gep A, 0, i".
3564  assert(Array->getType()->isArrayType() &&
3565  "Array to pointer decay must have array source type!");
3566  LValue ArrayLV;
3567  // For simple multidimensional array indexing, set the 'accessed' flag for
3568  // better bounds-checking of the base expression.
3569  if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3570  ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3571  else
3572  ArrayLV = EmitLValue(Array);
3573 
3574  // Propagate the alignment from the array itself to the result.
3575  EltPtr = emitArraySubscriptGEP(
3576  *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3577  ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3578  /*SignedIndices=*/false, E->getExprLoc());
3579  BaseInfo = ArrayLV.getBaseInfo();
3580  TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
3581  } else {
3582  Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3583  TBAAInfo, BaseTy, ResultExprTy,
3584  IsLowerBound);
3585  EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3586  !getLangOpts().isSignedOverflowDefined(),
3587  /*SignedIndices=*/false, E->getExprLoc());
3588  }
3589 
3590  return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
3591 }
3592 
3595  // Emit the base vector as an l-value.
3596  LValue Base;
3597 
3598  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3599  if (E->isArrow()) {
3600  // If it is a pointer to a vector, emit the address and form an lvalue with
3601  // it.
3602  LValueBaseInfo BaseInfo;
3603  TBAAAccessInfo TBAAInfo;
3604  Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
3605  const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3606  Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
3607  Base.getQuals().removeObjCGCAttr();
3608  } else if (E->getBase()->isGLValue()) {
3609  // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3610  // emit the base as an lvalue.
3611  assert(E->getBase()->getType()->isVectorType());
3612  Base = EmitLValue(E->getBase());
3613  } else {
3614  // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3615  assert(E->getBase()->getType()->isVectorType() &&
3616  "Result must be a vector");
3617  llvm::Value *Vec = EmitScalarExpr(E->getBase());
3618 
3619  // Store the vector to memory (because LValue wants an address).
3620  Address VecMem = CreateMemTemp(E->getBase()->getType());
3621  Builder.CreateStore(Vec, VecMem);
3622  Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3624  }
3625 
3626  QualType type =
3628 
3629  // Encode the element access list into a vector of unsigned indices.
3630  SmallVector<uint32_t, 4> Indices;
3631  E->getEncodedElementAccess(Indices);
3632 
3633  if (Base.isSimple()) {
3634  llvm::Constant *CV =
3635  llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3636  return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3637  Base.getBaseInfo(), TBAAAccessInfo());
3638  }
3639  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3640 
3641  llvm::Constant *BaseElts = Base.getExtVectorElts();
3643 
3644  for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3645  CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3646  llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3648  Base.getBaseInfo(), TBAAAccessInfo());
3649 }
3650 
3652  if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3653  EmitIgnoredExpr(E->getBase());
3654  return EmitDeclRefLValue(DRE);
3655  }
3656 
3657  Expr *BaseExpr = E->getBase();
3658  // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3659  LValue BaseLV;
3660  if (E->isArrow()) {
3661  LValueBaseInfo BaseInfo;
3662  TBAAAccessInfo TBAAInfo;
3663  Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
3664  QualType PtrTy = BaseExpr->getType()->getPointeeType();
3665  SanitizerSet SkippedChecks;
3666  bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3667  if (IsBaseCXXThis)
3668  SkippedChecks.set(SanitizerKind::Alignment, true);
3669  if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3670  SkippedChecks.set(SanitizerKind::Null, true);
3671  EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3672  /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3673  BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
3674  } else
3675  BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3676 
3677  NamedDecl *ND = E->getMemberDecl();
3678  if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3679  LValue LV = EmitLValueForField(BaseLV, Field);
3680  setObjCGCLValueClass(getContext(), E, LV);
3681  return LV;
3682  }
3683 
3684  if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3685  return EmitFunctionDeclLValue(*this, E, FD);
3686 
3687  llvm_unreachable("Unhandled member declaration!");
3688 }
3689 
3690 /// Given that we are currently emitting a lambda, emit an l-value for
3691 /// one of its members.
3693  assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3694  assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3695  QualType LambdaTagType =
3696  getContext().getTagDeclType(Field->getParent());
3697  LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3698  return EmitLValueForField(LambdaLV, Field);
3699 }
3700 
3701 /// Drill down to the storage of a field without walking into
3702 /// reference types.
3703 ///
3704 /// The resulting address doesn't necessarily have the right type.
3706  const FieldDecl *field) {
3707  const RecordDecl *rec = field->getParent();
3708 
3709  unsigned idx =
3710  CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3711 
3712  CharUnits offset;
3713  // Adjust the alignment down to the given offset.
3714  // As a special case, if the LLVM field index is 0, we know that this
3715  // is zero.
3716  assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3717  .getFieldOffset(field->getFieldIndex()) == 0) &&
3718  "LLVM field at index zero had non-zero offset?");
3719  if (idx != 0) {
3720  auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3721  auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3722  offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3723  }
3724 
3725  return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3726 }
3727 
3728 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3729  const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3730  if (!RD)
3731  return false;
3732 
3733  if (RD->isDynamicClass())
3734  return true;
3735 
3736  for (const auto &Base : RD->bases())
3737  if (hasAnyVptr(Base.getType(), Context))
3738  return true;
3739 
3740  for (const FieldDecl *Field : RD->fields())
3741  if (hasAnyVptr(Field->getType(), Context))
3742  return true;
3743 
3744  return false;
3745 }
3746 
3748  const FieldDecl *field) {
3749  LValueBaseInfo BaseInfo = base.getBaseInfo();
3750 
3751  if (field->isBitField()) {
3752  const CGRecordLayout &RL =
3754  const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3755  Address Addr = base.getAddress();
3756  unsigned Idx = RL.getLLVMFieldNo(field);
3757  if (Idx != 0)
3758  // For structs, we GEP to the field that the record layout suggests.
3759  Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3760  field->getName());
3761  // Get the access type.
3762  llvm::Type *FieldIntTy =
3763  llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3764  if (Addr.getElementType() != FieldIntTy)
3765  Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3766 
3767  QualType fieldType =
3768  field->getType().withCVRQualifiers(base.getVRQualifiers());
3769  // TODO: Support TBAA for bit fields.
3770  LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
3771  return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3772  TBAAAccessInfo());
3773  }
3774 
3775  // Fields of may-alias structures are may-alias themselves.
3776  // FIXME: this should get propagated down through anonymous structs
3777  // and unions.
3778  QualType FieldType = field->getType();
3779  const RecordDecl *rec = field->getParent();
3780  AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
3781  LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
3782  TBAAAccessInfo FieldTBAAInfo;
3783  if (base.getTBAAInfo().isMayAlias() ||
3784  rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
3785  FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3786  } else if (rec->isUnion()) {
3787  // TODO: Support TBAA for unions.
3788  FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3789  } else {
3790  // If no base type been assigned for the base access, then try to generate
3791  // one for this base lvalue.
3792  FieldTBAAInfo = base.getTBAAInfo();
3793  if (!FieldTBAAInfo.BaseType) {
3794  FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3795  assert(!FieldTBAAInfo.Offset &&
3796  "Nonzero offset for an access with no base type!");
3797  }
3798 
3799  // Adjust offset to be relative to the base type.
3800  const ASTRecordLayout &Layout =
3802  unsigned CharWidth = getContext().getCharWidth();
3803  if (FieldTBAAInfo.BaseType)
3804  FieldTBAAInfo.Offset +=
3805  Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3806 
3807  // Update the final access type and size.
3808  FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3809  FieldTBAAInfo.Size =
3810  getContext().getTypeSizeInChars(FieldType).getQuantity();
3811  }
3812 
3813  Address addr = base.getAddress();
3814  unsigned RecordCVR = base.getVRQualifiers();
3815  if (rec->isUnion()) {
3816  // For unions, there is no pointer adjustment.
3817  assert(!FieldType->isReferenceType() && "union has reference member");
3818  if (CGM.getCodeGenOpts().StrictVTablePointers &&
3819  hasAnyVptr(FieldType, getContext()))
3820  // Because unions can easily skip invariant.barriers, we need to add
3821  // a barrier every time CXXRecord field with vptr is referenced.
3822  addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3823  addr.getAlignment());
3824  } else {
3825  // For structs, we GEP to the field that the record layout suggests.
3826  addr = emitAddrOfFieldStorage(*this, addr, field);
3827 
3828  // If this is a reference field, load the reference right now.
3829  if (FieldType->isReferenceType()) {
3830  LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3831  FieldTBAAInfo);
3832  if (RecordCVR & Qualifiers::Volatile)
3833  RefLVal.getQuals().setVolatile(true);
3834  addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
3835 
3836  // Qualifiers on the struct don't apply to the referencee.
3837  RecordCVR = 0;
3838  FieldType = FieldType->getPointeeType();
3839  }
3840  }
3841 
3842  // Make sure that the address is pointing to the right type. This is critical
3843  // for both unions and structs. A union needs a bitcast, a struct element
3844  // will need a bitcast if the LLVM type laid out doesn't match the desired
3845  // type.
3847  addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
3848 
3849  if (field->hasAttr<AnnotateAttr>())
3850  addr = EmitFieldAnnotations(field, addr);
3851 
3852  LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
3853  LV.getQuals().addCVRQualifiers(RecordCVR);
3854 
3855  // __weak attribute on a field is ignored.
3856  if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3857  LV.getQuals().removeObjCGCAttr();
3858 
3859  return LV;
3860 }
3861 
3862 LValue
3864  const FieldDecl *Field) {
3865  QualType FieldType = Field->getType();
3866 
3867  if (!FieldType->isReferenceType())
3868  return EmitLValueForField(Base, Field);
3869 
3870  Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3871 
3872  // Make sure that the address is pointing to the right type.
3873  llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3874  V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3875 
3876  // TODO: Generate TBAA information that describes this access as a structure
3877  // member access and not just an access to an object of the field's type. This
3878  // should be similar to what we do in EmitLValueForField().
3879  LValueBaseInfo BaseInfo = Base.getBaseInfo();
3880  AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
3881  LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
3882  return MakeAddrLValue(V, FieldType, FieldBaseInfo,
3883  CGM.getTBAAInfoForSubobject(Base, FieldType));
3884 }
3885 
3887  if (E->isFileScope()) {
3889  return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3890  }
3891  if (E->getType()->isVariablyModifiedType())
3892  // make sure to emit the VLA size.
3894 
3895  Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3896  const Expr *InitExpr = E->getInitializer();
3897  LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3898 
3899  EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3900  /*Init*/ true);
3901 
3902  return Result;
3903 }
3904 
3906  if (!E->isGLValue())
3907  // Initializing an aggregate temporary in C++11: T{...}.
3908  return EmitAggExprToLValue(E);
3909 
3910  // An lvalue initializer list must be initializing a reference.
3911  assert(E->isTransparent() && "non-transparent glvalue init list");
3912  return EmitLValue(E->getInit(0));
3913 }
3914 
3915 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3916 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3917 /// LValue is returned and the current block has been terminated.
3919  const Expr *Operand) {
3920  if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3921  CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3922  return None;
3923  }
3924 
3925  return CGF.EmitLValue(Operand);
3926 }
3927 
3930  if (!expr->isGLValue()) {
3931  // ?: here should be an aggregate.
3932  assert(hasAggregateEvaluationKind(expr->getType()) &&
3933  "Unexpected conditional operator!");
3934  return EmitAggExprToLValue(expr);
3935  }
3936 
3937  OpaqueValueMapping binding(*this, expr);
3938 
3939  const Expr *condExpr = expr->getCond();
3940  bool CondExprBool;
3941  if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3942  const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3943  if (!CondExprBool) std::swap(live, dead);
3944 
3945  if (!ContainsLabel(dead)) {
3946  // If the true case is live, we need to track its region.
3947  if (CondExprBool)
3949  return EmitLValue(live);
3950  }
3951  }
3952 
3953  llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3954  llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3955  llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3956 
3957  ConditionalEvaluation eval(*this);
3958  EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3959 
3960  // Any temporaries created here are conditional.
3961  EmitBlock(lhsBlock);
3963  eval.begin(*this);
3964  Optional<LValue> lhs =
3965  EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3966  eval.end(*this);
3967 
3968  if (lhs && !lhs->isSimple())
3969  return EmitUnsupportedLValue(expr, "conditional operator");
3970 
3971  lhsBlock = Builder.GetInsertBlock();
3972  if (lhs)
3973  Builder.CreateBr(contBlock);
3974 
3975  // Any temporaries created here are conditional.
3976  EmitBlock(rhsBlock);
3977  eval.begin(*this);
3978  Optional<LValue> rhs =
3979  EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3980  eval.end(*this);
3981  if (rhs && !rhs->isSimple())
3982  return EmitUnsupportedLValue(expr, "conditional operator");
3983  rhsBlock = Builder.GetInsertBlock();
3984 
3985  EmitBlock(contBlock);
3986 
3987  if (lhs && rhs) {
3988  llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3989  2, "cond-lvalue");
3990  phi->addIncoming(lhs->getPointer(), lhsBlock);
3991  phi->addIncoming(rhs->getPointer(), rhsBlock);
3992  Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3993  AlignmentSource alignSource =
3994  std::max(lhs->getBaseInfo().getAlignmentSource(),
3995  rhs->getBaseInfo().getAlignmentSource());
3997  lhs->getTBAAInfo(), rhs->getTBAAInfo());
3998  return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
3999  TBAAInfo);
4000  } else {
4001  assert((lhs || rhs) &&
4002  "both operands of glvalue conditional are throw-expressions?");
4003  return lhs ? *lhs : *rhs;
4004  }
4005 }
4006 
4007 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4008 /// type. If the cast is to a reference, we can have the usual lvalue result,
4009 /// otherwise if a cast is needed by the code generator in an lvalue context,
4010 /// then it must mean that we need the address of an aggregate in order to
4011 /// access one of its members. This can happen for all the reasons that casts
4012 /// are permitted with aggregate result, including noop aggregate casts, and
4013 /// cast from scalar to union.
4015  switch (E->getCastKind()) {
4016  case CK_ToVoid:
4017  case CK_BitCast:
4018  case CK_ArrayToPointerDecay:
4019  case CK_FunctionToPointerDecay:
4020  case CK_NullToMemberPointer:
4021  case CK_NullToPointer:
4022  case CK_IntegralToPointer:
4023  case CK_PointerToIntegral:
4024  case CK_PointerToBoolean:
4025  case CK_VectorSplat:
4026  case CK_IntegralCast:
4027  case CK_BooleanToSignedIntegral:
4028  case CK_IntegralToBoolean:
4029  case CK_IntegralToFloating:
4030  case CK_FloatingToIntegral:
4031  case CK_FloatingToBoolean:
4032  case CK_FloatingCast:
4033  case CK_FloatingRealToComplex:
4034  case CK_FloatingComplexToReal:
4035  case CK_FloatingComplexToBoolean:
4036  case CK_FloatingComplexCast:
4037  case CK_FloatingComplexToIntegralComplex:
4038  case CK_IntegralRealToComplex:
4039  case CK_IntegralComplexToReal:
4040  case CK_IntegralComplexToBoolean:
4041  case CK_IntegralComplexCast:
4042  case CK_IntegralComplexToFloatingComplex:
4043  case CK_DerivedToBaseMemberPointer:
4044  case CK_BaseToDerivedMemberPointer:
4045  case CK_MemberPointerToBoolean:
4046  case CK_ReinterpretMemberPointer:
4047  case CK_AnyPointerToBlockPointerCast:
4048  case CK_ARCProduceObject:
4049  case CK_ARCConsumeObject:
4050  case CK_ARCReclaimReturnedObject:
4051  case CK_ARCExtendBlockObject:
4052  case CK_CopyAndAutoreleaseBlockObject:
4053  case CK_AddressSpaceConversion:
4054  case CK_IntToOCLSampler:
4055  return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4056 
4057  case CK_Dependent:
4058  llvm_unreachable("dependent cast kind in IR gen!");
4059 
4060  case CK_BuiltinFnToFnPtr:
4061  llvm_unreachable("builtin functions are handled elsewhere");
4062 
4063  // These are never l-values; just use the aggregate emission code.
4064  case CK_NonAtomicToAtomic:
4065  case CK_AtomicToNonAtomic:
4066  return EmitAggExprToLValue(E);
4067 
4068  case CK_Dynamic: {
4069  LValue LV = EmitLValue(E->getSubExpr());
4070  Address V = LV.getAddress();
4071  const auto *DCE = cast<CXXDynamicCastExpr>(E);
4072  return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4073  }
4074 
4075  case CK_ConstructorConversion:
4076  case CK_UserDefinedConversion:
4077  case CK_CPointerToObjCPointerCast:
4078  case CK_BlockPointerToObjCPointerCast:
4079  case CK_NoOp:
4080  case CK_LValueToRValue:
4081  return EmitLValue(E->getSubExpr());
4082 
4083  case CK_UncheckedDerivedToBase:
4084  case CK_DerivedToBase: {
4085  const RecordType *DerivedClassTy =
4086  E->getSubExpr()->getType()->getAs<RecordType>();
4087  auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4088 
4089  LValue LV = EmitLValue(E->getSubExpr());
4090  Address This = LV.getAddress();
4091 
4092  // Perform the derived-to-base conversion
4094  This, DerivedClassDecl, E->path_begin(), E->path_end(),
4095  /*NullCheckValue=*/false, E->getExprLoc());
4096 
4097  // TODO: Support accesses to members of base classes in TBAA. For now, we
4098  // conservatively pretend that the complete object is of the base class
4099  // type.
4100  return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4101  CGM.getTBAAInfoForSubobject(LV, E->getType()));
4102  }
4103  case CK_ToUnion:
4104  return EmitAggExprToLValue(E);
4105  case CK_BaseToDerived: {
4106  const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
4107  auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4108 
4109  LValue LV = EmitLValue(E->getSubExpr());
4110 
4111  // Perform the base-to-derived conversion
4112  Address Derived =
4113  GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
4114  E->path_begin(), E->path_end(),
4115  /*NullCheckValue=*/false);
4116 
4117  // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4118  // performed and the object is not of the derived type.
4121  Derived.getPointer(), E->getType());
4122 
4123  if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4124  EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4125  /*MayBeNull=*/false,
4127 
4128  return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4129  CGM.getTBAAInfoForSubobject(LV, E->getType()));
4130  }
4131  case CK_LValueBitCast: {
4132  // This must be a reinterpret_cast (or c-style equivalent).
4133  const auto *CE = cast<ExplicitCastExpr>(E);
4134 
4135  CGM.EmitExplicitCastExprType(CE, this);
4136  LValue LV = EmitLValue(E->getSubExpr());
4138  ConvertType(CE->getTypeAsWritten()));
4139 
4140  if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4141  EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4142  /*MayBeNull=*/false,
4144 
4145  return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4146  CGM.getTBAAInfoForSubobject(LV, E->getType()));
4147  }
4148  case CK_ObjCObjectLValueCast: {
4149  LValue LV = EmitLValue(E->getSubExpr());
4151  ConvertType(E->getType()));
4152  return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4153  CGM.getTBAAInfoForSubobject(LV, E->getType()));
4154  }
4155  case CK_ZeroToOCLQueue:
4156  llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4157  case CK_ZeroToOCLEvent:
4158  llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4159  }
4160 
4161  llvm_unreachable("Unhandled lvalue cast kind?");
4162 }
4163 
4166  return getOpaqueLValueMapping(e);
4167 }
4168 
4170  const FieldDecl *FD,
4171  SourceLocation Loc) {
4172  QualType FT = FD->getType();
4173  LValue FieldLV = EmitLValueForField(LV, FD);
4174  switch (getEvaluationKind(FT)) {
4175  case TEK_Complex:
4176  return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4177  case TEK_Aggregate:
4178  return FieldLV.asAggregateRValue();
4179  case TEK_Scalar:
4180  // This routine is used to load fields one-by-one to perform a copy, so
4181  // don't load reference fields.
4182  if (FD->getType()->isReferenceType())
4183  return RValue::get(FieldLV.getPointer());
4184  return EmitLoadOfLValue(FieldLV, Loc);
4185  }
4186  llvm_unreachable("bad evaluation kind");
4187 }
4188 
4189 //===--------------------------------------------------------------------===//
4190 // Expression Emission
4191 //===--------------------------------------------------------------------===//
4192 
4195  // Builtins never have block type.
4196  if (E->getCallee()->getType()->isBlockPointerType())
4197  return EmitBlockCallExpr(E, ReturnValue);
4198 
4199  if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4200  return EmitCXXMemberCallExpr(CE, ReturnValue);
4201 
4202  if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4203  return EmitCUDAKernelCallExpr(CE, ReturnValue);
4204 
4205  if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4206  if (const CXXMethodDecl *MD =
4207  dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4208  return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4209 
4210  CGCallee callee = EmitCallee(E->getCallee());
4211 
4212  if (callee.isBuiltin()) {
4213  return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4214  E, ReturnValue);
4215  }
4216 
4217  if (callee.isPseudoDestructor()) {
4219  }
4220 
4221  return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4222 }
4223 
4224 /// Emit a CallExpr without considering whether it might be a subclass.
4227  CGCallee Callee = EmitCallee(E->getCallee());
4228  return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4229 }
4230 
4232  if (auto builtinID = FD->getBuiltinID()) {
4233  return CGCallee::forBuiltin(builtinID, FD);
4234  }
4235 
4236  llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4237  return CGCallee::forDirect(calleePtr, FD);
4238 }
4239 
4241  E = E->IgnoreParens();
4242 
4243  // Look through function-to-pointer decay.
4244  if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4245  if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4246  ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4247  return EmitCallee(ICE->getSubExpr());
4248  }
4249 
4250  // Resolve direct calls.
4251  } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4252  if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4253  return EmitDirectCallee(*this, FD);
4254  }
4255  } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4256  if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4257  EmitIgnoredExpr(ME->getBase());
4258  return EmitDirectCallee(*this, FD);
4259  }
4260 
4261  // Look through template substitutions.
4262  } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4263  return EmitCallee(NTTP->getReplacement());
4264 
4265  // Treat pseudo-destructor calls differently.
4266  } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4267  return CGCallee::forPseudoDestructor(PDE);
4268  }
4269 
4270  // Otherwise, we have an indirect reference.
4271  llvm::Value *calleePtr;
4273  if (auto ptrType = E->getType()->getAs<PointerType>()) {
4274  calleePtr = EmitScalarExpr(E);
4275  functionType = ptrType->getPointeeType();
4276  } else {
4277  functionType = E->getType();
4278  calleePtr = EmitLValue(E).getPointer();
4279  }
4280  assert(functionType->isFunctionType());
4281  CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4283  CGCallee callee(calleeInfo, calleePtr);
4284  return callee;
4285 }
4286 
4288  // Comma expressions just emit their LHS then their RHS as an l-value.
4289  if (E->getOpcode() == BO_Comma) {
4290  EmitIgnoredExpr(E->getLHS());
4292  return EmitLValue(E->getRHS());
4293  }
4294 
4295  if (E->getOpcode() == BO_PtrMemD ||
4296  E->getOpcode() == BO_PtrMemI)
4298 
4299  assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4300 
4301  // Note that in all of these cases, __block variables need the RHS
4302  // evaluated first just in case the variable gets moved by the RHS.
4303 
4304  switch (getEvaluationKind(E->getType())) {
4305  case TEK_Scalar: {
4306  switch (E->getLHS()->getType().getObjCLifetime()) {
4308  return EmitARCStoreStrong(E, /*ignored*/ false).first;
4309 
4311  return EmitARCStoreAutoreleasing(E).first;
4312 
4313  // No reason to do any of these differently.
4314  case Qualifiers::OCL_None:
4316  case Qualifiers::OCL_Weak:
4317  break;
4318  }
4319 
4320  RValue RV = EmitAnyExpr(E->getRHS());
4322  if (RV.isScalar())
4324  EmitStoreThroughLValue(RV, LV);
4325  return LV;
4326  }
4327 
4328  case TEK_Complex:
4329  return EmitComplexAssignmentLValue(E);
4330 
4331  case TEK_Aggregate:
4332  return EmitAggExprToLValue(E);
4333  }
4334  llvm_unreachable("bad evaluation kind");
4335 }
4336 
4338  RValue RV = EmitCallExpr(E);
4339 
4340  if (!RV.isScalar())
4341  return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4343 
4344  assert(E->getCallReturnType(getContext())->isReferenceType() &&
4345  "Can't have a scalar return unless the return type is a "
4346  "reference type!");
4347 
4349 }
4350 
4352  // FIXME: This shouldn't require another copy.
4353  return EmitAggExprToLValue(E);
4354 }
4355 
4358  && "binding l-value to type which needs a temporary");
4359  AggValueSlot Slot = CreateAggTemp(E->getType());
4360  EmitCXXConstructExpr(E, Slot);
4361  return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4362 }
4363 
4364 LValue
4367 }
4368 
4371  ConvertType(E->getType()));
4372 }
4373 
4375  return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4377 }
4378 
4379 LValue
4381  AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4382  Slot.setExternallyDestructed();
4383  EmitAggExpr(E->getSubExpr(), Slot);
4384  EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4386 }
4387 
4388 LValue
4390  AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4391  EmitLambdaExpr(E, Slot);
4393 }
4394 
4396  RValue RV = EmitObjCMessageExpr(E);
4397 
4398  if (!RV.isScalar())
4399  return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4401 
4402  assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4403  "Can't have a scalar return unless the return type is a "
4404  "reference type!");
4405 
4407 }
4408 
4410  Address V =
4412  return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4413 }
4414 
4416  const ObjCIvarDecl *Ivar) {
4417  return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4418 }
4419 
4421  llvm::Value *BaseValue,
4422  const ObjCIvarDecl *Ivar,
4423  unsigned CVRQualifiers) {
4424  return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4425  Ivar, CVRQualifiers);
4426 }
4427 
4429  // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4430  llvm::Value *BaseValue = nullptr;
4431  const Expr *BaseExpr = E->getBase();
4432  Qualifiers BaseQuals;
4433  QualType ObjectTy;
4434  if (E->isArrow()) {
4435  BaseValue = EmitScalarExpr(BaseExpr);
4436  ObjectTy = BaseExpr->getType()->getPointeeType();
4437  BaseQuals = ObjectTy.getQualifiers();
4438  } else {
4439  LValue BaseLV = EmitLValue(BaseExpr);
4440  BaseValue = BaseLV.getPointer();
4441  ObjectTy = BaseExpr->getType();
4442  BaseQuals = ObjectTy.getQualifiers();
4443  }
4444 
4445  LValue LV =
4446  EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4447  BaseQuals.getCVRQualifiers());
4448  setObjCGCLValueClass(getContext(), E, LV);
4449  return LV;
4450 }
4451 
4453  // Can only get l-value for message expression returning aggregate type
4454  RValue RV = EmitAnyExprToTemp(E);
4455  return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4457 }
4458 
4459 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4461  llvm::Value *Chain) {
4462  // Get the actual function type. The callee type will always be a pointer to
4463  // function type or a block pointer type.
4464  assert(CalleeType->isFunctionPointerType() &&
4465  "Call must have function pointer type!");
4466 
4467  const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4468 
4469  if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4470  // We can only guarantee that a function is called from the correct
4471  // context/function based on the appropriate target attributes,
4472  // so only check in the case where we have both always_inline and target
4473  // since otherwise we could be making a conditional call after a check for
4474  // the proper cpu features (and it won't cause code generation issues due to
4475  // function based code generation).
4476  if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4477  TargetDecl->hasAttr<TargetAttr>())
4478  checkTargetFeatures(E, FD);
4479 
4480  CalleeType = getContext().getCanonicalType(CalleeType);
4481 
4482  const auto *FnType =
4483  cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4484 
4485  CGCallee Callee = OrigCallee;
4486 
4487  if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4488  (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4489  if (llvm::Constant *PrefixSig =
4491  SanitizerScope SanScope(this);
4492  llvm::Constant *FTRTTIConst =
4493  CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4494  llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
4495  llvm::StructType *PrefixStructTy = llvm::StructType::get(
4496  CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4497 
4498  llvm::Value *CalleePtr = Callee.getFunctionPointer();
4499 
4500  llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4501  CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4502  llvm::Value *CalleeSigPtr =
4503  Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4504  llvm::Value *CalleeSig =
4505  Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4506  llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4507 
4508  llvm::BasicBlock *Cont = createBasicBlock("cont");
4509  llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4510  Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4511 
4512  EmitBlock(TypeCheck);
4513  llvm::Value *CalleeRTTIPtr =
4514  Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4515  llvm::Value *CalleeRTTIEncoded =
4516  Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4517  llvm::Value *CalleeRTTI =
4518  DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
4519  llvm::Value *CalleeRTTIMatch =
4520  Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4521  llvm::Constant *StaticData[] = {
4523  EmitCheckTypeDescriptor(CalleeType)
4524  };
4525  EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4526  SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4527 
4528  Builder.CreateBr(Cont);
4529  EmitBlock(Cont);
4530  }
4531  }
4532 
4533  // If we are checking indirect calls and this call is indirect, check that the
4534  // function pointer is a member of the bit set for the function type.
4535  if (SanOpts.has(SanitizerKind::CFIICall) &&
4536  (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4537  SanitizerScope SanScope(this);
4538  EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4539 
4540  llvm::Metadata *MD;
4541  if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4543  else
4544  MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4545 
4546  llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4547 
4548  llvm::Value *CalleePtr = Callee.getFunctionPointer();
4549  llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4550  llvm::Value *TypeTest = Builder.CreateCall(
4551  CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4552 
4553  auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4554  llvm::Constant *StaticData[] = {
4555  llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4557  EmitCheckTypeDescriptor(QualType(FnType, 0)),
4558  };
4559  if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4560  EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4561  CastedCallee, StaticData);
4562  } else {
4563  EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4564  SanitizerHandler::CFICheckFail, StaticData,
4565  {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4566  }
4567  }
4568 
4569  CallArgList Args;
4570  if (Chain)
4573 
4574  // C++17 requires that we evaluate arguments to a call using assignment syntax
4575  // right-to-left, and that we evaluate arguments to certain other operators
4576  // left-to-right. Note that we allow this to override the order dictated by
4577  // the calling convention on the MS ABI, which means that parameter
4578  // destruction order is not necessarily reverse construction order.
4579  // FIXME: Revisit this based on C++ committee response to unimplementability.
4581  if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4582  if (OCE->isAssignmentOp())
4584  else {
4585  switch (OCE->getOperator()) {
4586  case OO_LessLess:
4587  case OO_GreaterGreater:
4588  case OO_AmpAmp:
4589  case OO_PipePipe:
4590  case OO_Comma:
4591  case OO_ArrowStar:
4593  break;
4594  default:
4595  break;
4596  }
4597  }
4598  }
4599 
4600  EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4601  E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4602 
4604  Args, FnType, /*isChainCall=*/Chain);
4605 
4606  // C99 6.5.2.2p6:
4607  // If the expression that denotes the called function has a type
4608  // that does not include a prototype, [the default argument
4609  // promotions are performed]. If the number of arguments does not
4610  // equal the number of parameters, the behavior is undefined. If
4611  // the function is defined with a type that includes a prototype,
4612  // and either the prototype ends with an ellipsis (, ...) or the
4613  // types of the arguments after promotion are not compatible with
4614  // the types of the parameters, the behavior is undefined. If the
4615  // function is defined with a type that does not include a
4616  // prototype, and the types of the arguments after promotion are
4617  // not compatible with those of the parameters after promotion,
4618  // the behavior is undefined [except in some trivial cases].
4619  // That is, in the general case, we should assume that a call
4620  // through an unprototyped function type works like a *non-variadic*
4621  // call. The way we make this work is to cast to the exact type
4622  // of the promoted arguments.
4623  //
4624  // Chain calls use this same code path to add the invisible chain parameter
4625  // to the function type.
4626  if (isa<FunctionNoProtoType>(FnType) || Chain) {
4627  llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4628  CalleeTy = CalleeTy->getPointerTo();
4629 
4630  llvm::Value *CalleePtr = Callee.getFunctionPointer();
4631  CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4632  Callee.setFunctionPointer(CalleePtr);
4633  }
4634 
4635  return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, E->getExprLoc());
4636 }
4637 
4640  Address BaseAddr = Address::invalid();
4641  if (E->getOpcode() == BO_PtrMemI) {
4642  BaseAddr = EmitPointerWithAlignment(E->getLHS());
4643  } else {
4644  BaseAddr = EmitLValue(E->getLHS()).getAddress();
4645  }
4646 
4647  llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4648 
4649  const MemberPointerType *MPT
4650  = E->getRHS()->getType()->getAs<MemberPointerType>();
4651 
4652  LValueBaseInfo BaseInfo;
4653  TBAAAccessInfo TBAAInfo;
4654  Address MemberAddr =
4655  EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4656  &TBAAInfo);
4657 
4658  return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
4659 }
4660 
4661 /// Given the address of a temporary variable, produce an r-value of
4662 /// its type.
4664  QualType type,
4665  SourceLocation loc) {
4666  LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4667  switch (getEvaluationKind(type)) {
4668  case TEK_Complex:
4669  return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4670  case TEK_Aggregate:
4671  return lvalue.asAggregateRValue();
4672  case TEK_Scalar:
4673  return RValue::get(EmitLoadOfScalar(lvalue, loc));
4674  }
4675  llvm_unreachable("bad evaluation kind");
4676 }
4677 
4678 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4679  assert(Val->getType()->isFPOrFPVectorTy());
4680  if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4681  return;
4682 
4683  llvm::MDBuilder MDHelper(getLLVMContext());
4684  llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4685 
4686  cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4687 }
4688 
4689 namespace {
4690  struct LValueOrRValue {
4691  LValue LV;
4692  RValue RV;
4693  };
4694 }
4695 
4696 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4697  const PseudoObjectExpr *E,
4698  bool forLValue,
4699  AggValueSlot slot) {
4701 
4702  // Find the result expression, if any.
4703  const Expr *resultExpr = E->getResultExpr();
4704  LValueOrRValue result;
4705 
4707  i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4708  const Expr *semantic = *i;
4709 
4710  // If this semantic expression is an opaque value, bind it
4711  // to the result of its source expression.
4712  if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4713 
4714  // If this is the result expression, we may need to evaluate
4715  // directly into the slot.
4717  OVMA opaqueData;
4718  if (ov == resultExpr && ov->isRValue() && !forLValue &&
4720  CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4721  LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4723  opaqueData = OVMA::bind(CGF, ov, LV);
4724  result.RV = slot.asRValue();
4725 
4726  // Otherwise, emit as normal.
4727  } else {
4728  opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4729 
4730  // If this is the result, also evaluate the result now.
4731  if (ov == resultExpr) {
4732  if (forLValue)
4733  result.LV = CGF.EmitLValue(ov);
4734  else
4735  result.RV = CGF.EmitAnyExpr(ov, slot);
4736  }
4737  }
4738 
4739  opaques.push_back(opaqueData);
4740 
4741  // Otherwise, if the expression is the result, evaluate it
4742  // and remember the result.
4743  } else if (semantic == resultExpr) {
4744  if (forLValue)
4745  result.LV = CGF.EmitLValue(semantic);
4746  else
4747  result.RV = CGF.EmitAnyExpr(semantic, slot);
4748 
4749  // Otherwise, evaluate the expression in an ignored context.
4750  } else {
4751  CGF.EmitIgnoredExpr(semantic);
4752  }
4753  }
4754 
4755  // Unbind all the opaques now.
4756  for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4757  opaques[i].unbind(CGF);
4758 
4759  return result;
4760 }
4761 
4763  AggValueSlot slot) {
4764  return emitPseudoObjectExpr(*this, E, false, slot).RV;
4765 }
4766 
4768  return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4769 }
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:640
const llvm::DataLayout & getDataLayout() const
TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType)
getTBAAInfoForSubobject - Get TBAA information for an access with a given base lvalue.
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:281
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprOpenMP.h:115
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
Definition: CGExpr.cpp:1495
Defines the clang::ASTContext interface.
An instance of this class is created to represent a function declaration or definition.
Definition: Decl.h:1697
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition: CGObjC.cpp:2160
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
Address getAddress() const
Definition: CGValue.h:555
Other implicit parameter.
Definition: Decl.h:1473
bool isSignedOverflowDefined() const
Definition: LangOptions.h:176
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...
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2283
CanQualType VoidPtrTy
Definition: ASTContext.h:1012
QualType getPointeeType() const
Definition: Type.h:2296
void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C)
A (possibly-)qualified type.
Definition: Type.h:653
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
bool isBlockPointerType() const
Definition: Type.h:5950
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
Definition: CGClass.cpp:129
Static storage duration.
Definition: Specifiers.h:277
bool isArrayType() const
Definition: Type.h:5991
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2483
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:149
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition: CGExpr.cpp:584
llvm::Type * ConvertTypeForMem(QualType T)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
const CodeGenOptions & getCodeGenOpts() const
LValue EmitStmtExprLValue(const StmtExpr *E)
Definition: CGExpr.cpp:4452
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
llvm::Value * getGlobalReg() const
Definition: CGValue.h:362
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
Definition: CGExpr.cpp:2612
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
Definition: CGValue.h:126
bool isBlacklistedType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category=StringRef()) const
llvm::LLVMContext & getLLVMContext()
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3920
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
Definition: CGExpr.cpp:396
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
bool isArithmeticType() const
Definition: Type.cpp:1908
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:101
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
Definition: CGExpr.cpp:2071
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:456
const Decl * getCalleeDecl() const
Definition: CGCall.h:62
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition: CGClass.cpp:374
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition: CGExpr.cpp:967
bool isRecordType() const
Definition: Type.h:6015
Expr * getBase() const
Definition: Expr.h:2477
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition: CGExpr.cpp:4762
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static void pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *E, Address ReferenceTemporary)
Definition: CGExpr.cpp:232
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, QualType Type, CharUnits Alignment=CharUnits::Zero(), SanitizerSet SkippedChecks=SanitizerSet())
Emit a check that V is the address of storage of the appropriate size and alignment for an object of ...
Definition: CGExpr.cpp:591
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition: Expr.cpp:3551
llvm::MDNode * AccessType
AccessType - The final access type.
Definition: CodeGenTBAA.h:106
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
const llvm::DataLayout & getDataLayout() const
Definition: CodeGenTypes.h:171
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:1933
Opcode getOpcode() const
Definition: Expr.h:3026
const CastExpr * BasePath
Definition: Expr.h:68
unsigned getFieldIndex() const
getFieldIndex - Returns the index of this field within its record, as appropriate for passing to ASTR...
Definition: Decl.cpp:3661
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, SanitizerHandler Check, ArrayRef< llvm::Constant *> StaticArgs, ArrayRef< llvm::Value *> DynamicArgs)
Create a basic block that will call a handler function in a sanitizer runtime with the provided argum...
Definition: CGExpr.cpp:2824
const AstTypeMatcher< FunctionType > functionType
Matches FunctionType nodes.
bool isVolatile() const
Definition: CGValue.h:298
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:26
static Destroyer destroyARCStrongPrecise
Expr * getLowerBound()
Get lower bound of array section.
Definition: ExprOpenMP.h:91
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Definition: Decl.h:2648
The base class of the type hierarchy.
Definition: Type.h:1351
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition: CGDecl.cpp:1506
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
Definition: CGExpr.cpp:4287
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
Definition: CGExpr.cpp:2096
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition: CGExpr.cpp:1836
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
Definition: CGExpr.cpp:4164
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2558
static llvm::Value * EmitBitCastOfLValueToProperType(CodeGenFunction &CGF, llvm::Value *V, llvm::Type *IRType, StringRef Name=StringRef())
Definition: CGExpr.cpp:2194
virtual const FieldDecl * lookup(const VarDecl *VD) const
Lookup the captured field decl for a variable.
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1239
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:168
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition: CGExpr.cpp:2201
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition: CGExpr.cpp:3003
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition: Specifiers.h:273
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition: CGExpr.cpp:2232
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier, emit the object size divided by the size of EltTy.
Definition: CGExpr.cpp:817
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference...
Definition: CGExpr.cpp:3863
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4035
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
Definition: CGAtomic.cpp:1871
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant, or if it does but contains a label, return false.
QualType getElementType() const
Definition: Type.h:2593
! Language semantics require left-to-right evaluation.
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
Definition: CGExpr.cpp:4374
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3723
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:806
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Definition: CGExpr.cpp:2571
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:35
static bool hasBooleanRepresentation(QualType Ty)
Definition: CGExpr.cpp:1439
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2637
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3426
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6305
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
Definition: CGExpr.cpp:4409
uint64_t getProfileCount(const Stmt *S)
Get the profiler&#39;s count for the given statement.
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type...
Definition: Type.h:6377
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:53
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:377
DiagnosticsEngine & getDiags() const
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified...
Definition: CGExpr.cpp:3113
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
llvm::Value * getPointer() const
Definition: Address.h:38
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information...
Definition: TargetInfo.h:164
static ConstantEmission forValue(llvm::Constant *C)
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
Not a TLS variable.
Definition: Decl.h:823
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF, const MemberExpr *ME)
Definition: CGExpr.cpp:1413
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:464
bool hasDefinition() const
Definition: DeclCXX.h:738
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1513
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition: CGExpr.cpp:1933
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition: Address.h:57
Address emitAddrOfImagComponent(Address complex, QualType complexType)
The collection of all-type qualifiers we support.
Definition: Type.h:152
bool isVariableArrayType() const
Definition: Type.h:6003
void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
Definition: CGExpr.cpp:890
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3488
llvm::DenseMap< const VarDecl *, FieldDecl * > LambdaCaptureFields
const TargetInfo & getTarget() const
An object to manage conditionally-evaluated expressions.
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4076
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
bool isObjCIvar() const
Definition: CGValue.h:267
Address getAddress() const
Definition: CGValue.h:324
Represents a class type in Objective C.
Definition: Type.h:5184
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.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Definition: CGExpr.cpp:4428
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Given that we are currently emitting a lambda, emit an l-value for one of its members.
Definition: CGExpr.cpp:3692
A C++ nested-name-specifier augmented with source location information.
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition: CGObjC.cpp:3156
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
Definition: CGExprCXX.cpp:2133
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2186
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition: CGObjC.cpp:1796
bool isFileScope() const
Definition: Expr.h:2667
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition: CGExpr.cpp:531
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
Definition: CGExpr.cpp:4380
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
Definition: CGCXX.cpp:238
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
Definition: CGExpr.cpp:2210
bool isVolatileQualified() const
Definition: CGValue.h:255
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2467
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Value *ptr, ArrayRef< llvm::Value *> indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
Definition: CGExpr.cpp:3176
CharUnits getAlignment() const
Definition: CGValue.h:313
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
LValue EmitCoyieldLValue(const CoyieldExpr *E)
virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, llvm::Value *ivarOffset)=0
LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, bool IsLowerBound=true)
Definition: CGExpr.cpp:3440
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2593
bool isReferenceType() const
Definition: Type.h:5954
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool IsBool)
Definition: CGExpr.cpp:1452
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:391
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:4790
Expr * getSubExpr()
Definition: Expr.h:2761
void setBaseIvarExp(Expr *V)
Definition: CGValue.h:303
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition: Expr.cpp:3519
void InitTempAlloca(Address Alloca, llvm::Value *Value)
InitTempAlloca - Provide an initial value for the given alloca which will be observable at all locati...
Definition: CGExpr.cpp:114
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition: CGExpr.cpp:1760
LValue EmitLambdaLValue(const LambdaExpr *E)
Definition: CGExpr.cpp:4389
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field)
Drill down to the storage of a field without walking into reference types.
Definition: CGExpr.cpp:3705
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:5737
static bool isFlexibleArrayMemberExpr(const Expr *E)
Determine whether this expression refers to a flexible array member in a struct.
Definition: CGExpr.cpp:789
Selector getSelector() const
Definition: ExprObjC.h:442
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition: CGExpr.cpp:192
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
const Expr *const * const_semantics_iterator
Definition: Expr.h:5036
void setNonGC(bool Value)
Definition: CGValue.h:274
Address CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition: CGExpr.cpp:122
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition: CGExpr.cpp:173
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition: CGCall.h:145
bool isGLValue() const
Definition: Expr.h:252
Describes an C or C++ initializer list.
Definition: Expr.h:3872
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:638
bool isArrow() const
Definition: ExprObjC.h:551
Address emitAddrOfRealComponent(Address complex, QualType complexType)
virtual llvm::Value * EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)=0
unsigned Size
The total size of the bit-field, in bits.
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2545
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
Definition: CGExpr.cpp:4696
Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef)
Definition: CGBlocks.cpp:1168
Address CreateElementBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Cast the element type of the given address to a different type, preserving information like the align...
Definition: CGBuilder.h:157
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
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, const FunctionDecl *FD)
Definition: CGExpr.cpp:2303
const FunctionDecl * getBuiltinDecl() const
Definition: CGCall.h:133
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2030
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
bool isGlobalObjCRef() const
Definition: CGValue.h:276
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type...
path_iterator path_begin()
Definition: Expr.h:2777
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:67
static LValue MakeExtVectorElt(Address vecAddress, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:389
void addCVRQualifiers(unsigned mask)
Definition: Type.h:303
semantics_iterator semantics_end()
Definition: Expr.h:5043
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2985
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5788
Checking the operand of a dynamic_cast or a typeid expression.
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Definition: Decl.h:3390
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what&#39;s our confidence in the alignment of...
Definition: CGValue.h:144
virtual llvm::Value * EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT)
Determine if a member pointer is non-null. Returns an i1.
Definition: CGCXXABI.cpp:97
bool isObjCWeak() const
Definition: CGValue.h:291
bool isArrow() const
Definition: Expr.h:2582
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition: CGObjC.cpp:2251
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
Definition: CGExpr.cpp:4356
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue)
Emit a CallExpr without considering whether it might be a subclass.
Definition: CGExpr.cpp:4225
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5718
LValue EmitUnaryOpLValue(const UnaryOperator *E)
Definition: CGExpr.cpp:2499
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition: Type.h:432
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition: CGExpr.cpp:161
An adjustment to be made to the temporary created when emitting a reference binding, which accesses a particular subobject of that temporary.
Definition: Expr.h:60
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2710
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
Definition: CGExpr.cpp:4395
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
void ForceCleanup(std::initializer_list< llvm::Value **> ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1196
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
bool isSimple() const
Definition: CGValue.h:249
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1215
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1580
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type...
Definition: opencl-c.h:75
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1404
RValue EmitBuiltinExpr(const FunctionDecl *FD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGBuiltin.cpp:933
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void * getAsOpaquePtr() const
Definition: Type.h:699
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler&#39;s counter for the given statement by StepV.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:94
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
Definition: CGValue.h:285
Represents an ObjC class declaration.
Definition: DeclObjC.h:1191
QualType getReturnType() const
Definition: DeclObjC.h:361
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition: CGExpr.cpp:4663
Checking the operand of a cast to a virtual base object.
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:71
static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx, CharUnits eltSize)
Definition: CGExpr.cpp:3192
virtual void mangleCXXRTTI(QualType T, raw_ostream &)=0
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Definition: CGExpr.cpp:2655
void setThreadLocalRef(bool Value)
Definition: CGValue.h:280
This object can be modified without requiring retains or releases.
Definition: Type.h:173
LValue EmitLValueForField(LValue Base, const FieldDecl *Field)
Definition: CGExpr.cpp:3747
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
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:434
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
Checking the &#39;this&#39; pointer for a call to a non-static member function.
virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, bool threadlocal=false)=0
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
Definition: CGExpr.cpp:3594
OpenMP 4.0 [2.4, Array Sections].
Definition: ExprOpenMP.h:45
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition: CGObjC.cpp:355
bool isVectorElt() const
Definition: CGValue.h:250
bool hasAttr() const
Definition: DeclBase.h:535
const ValueDecl * getExtendingDecl() const
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition: ExprCXX.h:4098
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
Definition: CGExprCXX.cpp:557
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1590
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3268
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 ...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
bool isDynamicClass() const
Definition: DeclCXX.h:751
const TargetCodeGenInfo & getTargetCodeGenInfo()
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition: CGExpr.cpp:202
LValueBaseInfo getBaseInfo() const
Definition: CGValue.h:316
static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind)
Definition: CGExpr.cpp:2755
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
Address getExtVectorAddress() const
Definition: CGValue.h:339
StringRef Filename
Definition: Format.cpp:1345
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:6270
bool isPseudoDestructor() const
Definition: CGCall.h:142
SourceLocation getLocation() const
Definition: Expr.h:1049
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
llvm::Value * DecodeAddrUsedInPrologue(llvm::Value *F, llvm::Value *EncodedAddr)
Decode an address used in a function prologue, encoded by EncodeAddrForUseInPrologue.
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:3778
Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition: CGExpr.cpp:107
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:39
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2266
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
LValue EmitInitListLValue(const InitListExpr *E)
Definition: CGExpr.cpp:3905
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
Definition: CGExpr.cpp:2000
bool isValid() const
QualType getElementType() const
Definition: Type.h:2236
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:627
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object...
Definition: CGDeclCXX.cpp:651
Expr - This represents one expression.
Definition: Expr.h:106
SourceLocation End
static Address invalid()
Definition: Address.h:35
const AnnotatedLine * Line
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
const FunctionProtoType * T
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
Definition: CGExpr.cpp:4365
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type, where the destination type is an LLVM scalar type.
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
Definition: CGExprCXX.cpp:107
void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
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:6368
void setObjCArray(bool Value)
Definition: CGValue.h:271
unsigned getLine() const
Return the presumed line number of this location.
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2620
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
const Expr * getCallee() const
Definition: Expr.h:2249
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
Definition: CGExpr.cpp:2311
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation, expressed as the maximum relative error in ulp.
Definition: CGExpr.cpp:4678
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp")
CreateAggTemp - Create a temporary memory object for the given aggregate type.
struct DTB DerivedToBase
Definition: Expr.h:78
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
Definition: CGExpr.cpp:576
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
ObjCLifetime getObjCLifetime() const
Definition: Type.h:341
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation...
Definition: CGExpr.cpp:1599
bool isAnyComplexType() const
Definition: Type.h:6023
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:429
TLSKind getTLSKind() const
Definition: Decl.cpp:1887
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1165
static Optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition: CGExpr.cpp:3918
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
Definition: CGValue.h:407
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::Constant *Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
llvm::LLVMContext & getLLVMContext()
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1800
QualType getType() const
Definition: Expr.h:128
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull...
Definition: CGDecl.cpp:692
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest)
Definition: CGExprCXX.cpp:2224
TBAAAccessInfo getTBAAInfo() const
Definition: CGValue.h:305
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:197
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4079
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
#define INT_MIN
Definition: limits.h:67
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:903
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
Definition: CGExpr.cpp:919
Represents an unpacked "presumed" location which can be presented to the user.
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:1717
Represents a GCC generic vector type.
Definition: Type.h:2914
llvm::Value * EmitCastToVoidPtr(llvm::Value *value)
Emit a cast to void* in the appropriate address space.
Definition: CGExpr.cpp:50
ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition: CGExpr.cpp:1351
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6263
ValueDecl * getDecl()
Definition: Expr.h:1041
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global gamed gegisters are always calls to intrinsics.
Definition: CGExpr.cpp:1811
const Qualifiers & getQuals() const
Definition: CGValue.h:308
const LangOptions & getLangOpts() const
bool isObjCStrong() const
Definition: CGValue.h:294
const Expr * getSubExpr() const
Definition: ExprCXX.h:1219
ASTContext & getContext() const
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition: CGExpr.cpp:1728
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type? This is different from pr...
Definition: CGExpr.cpp:1327
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:495
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition: Expr.h:2154
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
Definition: CGAtomic.cpp:1449
const SanitizerBlacklist & getSanitizerBlacklist() const
Definition: ASTContext.h:690
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:35
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
bool isThreadLocalRef() const
Definition: CGValue.h:279
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
Definition: CGExpr.cpp:2242
Dynamic storage duration.
Definition: Specifiers.h:278
The l-value was considered opaque, so the alignment was determined from a type.
RecordDecl * getDecl() const
Definition: Type.h:3986
const char * getFilename() const
Return the presumed filename of this location.
Thread storage duration.
Definition: Specifiers.h:276
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:181
CGCallee EmitCallee(const Expr *E)
Definition: CGExpr.cpp:4240
bool isBuiltin() const
Definition: CGCall.h:130
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:209
There is no lifetime qualification on this type.
Definition: Type.h:169
const SanitizerHandlerInfo SanitizerHandlers[]
Definition: CGExpr.cpp:2775
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:868
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:59
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:180
Kind
QualType getCanonicalType() const
Definition: Type.h:5757
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
Definition: CGExpr.cpp:2324
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4969
LValue EmitVAArgExprLValue(const VAArgExpr *E)
Definition: CGExpr.cpp:4351
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
Definition: CGExprCXX.cpp:2094
void setVolatile(bool flag)
Definition: Type.h:277
unsigned getColumn() const
Return the presumed column number of this location.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup...
Definition: CGDecl.cpp:1486
static llvm::Constant * EmitFunctionDeclPointer(CodeGenModule &CGM, const FunctionDecl *FD)
Definition: CGExpr.cpp:2279
Encodes a location in the source.
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
Definition: CGAtomic.cpp:1436
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go...
virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)=0
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4002
llvm::Constant * getTypeDescriptorFromMap(QualType Ty)
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition: CGExpr.cpp:2346
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5834
llvm::MDNode * BaseType
BaseType - The base/leading access type.
Definition: CodeGenTBAA.h:102
Expr * getSubExpr() const
Definition: Expr.h:1744
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition: CGExpr.cpp:143
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:1806
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior...
Definition: CGExpr.cpp:1134
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1874
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation...
Definition: CGExpr.cpp:1613
unsigned getBlockId(const BlockDecl *BD, bool Local)
Definition: Mangle.h:76
CastKind getCastKind() const
Definition: Expr.h:2757
Expr * getBaseIvarExp() const
Definition: CGValue.h:302
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
const CGBitFieldInfo & getBitFieldInfo() const
Definition: CGValue.h:356
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
Definition: CGExprAgg.cpp:1534
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
QualType getElementType() const
Definition: Type.h:2949
Checking the operand of a cast to a base object.
An aggregate value slot.
Definition: CGValue.h:434
void ConvertArgToString(ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, ArrayRef< intptr_t > QualTypeVals) const
Converts a diagnostic argument (as an intptr_t) into the string that represents it.
Definition: Diagnostic.h:698
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:620
llvm::Value * EmitLifetimeStart(uint64_t Size, llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition: CGDecl.cpp:938
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
Definition: CGExpr.cpp:1103
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition: CGExpr.cpp:3728
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition: CGExpr.cpp:2250
SourceLocation getColonLoc() const
Definition: ExprOpenMP.h:109
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
virtual Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel)=0
Get the address of a selector for the specified name and type values.
SanitizerSet SanOpts
Sanitizers enabled for this function.
static QualType getFixedSizeElementType(const ASTContext &ctx, const VariableArrayType *vla)
Definition: CGExpr.cpp:3207
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
bool isNontemporal() const
Definition: CGValue.h:288
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1816
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
Definition: CGCleanup.cpp:1260
CanQualType VoidTy
Definition: ASTContext.h:996
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
arg_range arguments()
Definition: Expr.h:2303
bool isObjCObjectPointerType() const
Definition: Type.h:6039
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
StringLiteral * getFunctionName()
Definition: Expr.cpp:469
An aligned address.
Definition: Address.h:25
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
void setObjCIvar(bool Value)
Definition: CGValue.h:268
uint64_t Size
Size - The size of access, in bytes.
Definition: CodeGenTBAA.h:113
All available information about a concrete callee.
Definition: CGCall.h:66
Address getVectorAddress() const
Definition: CGValue.h:332
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:97
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:399
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition: CGExpr.cpp:3125
IdentType getIdentType() const
Definition: Expr.h:1215
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition: CGExpr.cpp:4639
EnumDecl * getDecl() const
Definition: Type.h:4009
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1302
bool isVectorType() const
Definition: Type.h:6027
Checking the object expression in a non-static data member access.
bool isNonGC() const
Definition: CGValue.h:273
Assigning into this object requires a lifetime extension.
Definition: Type.h:186
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3488
void removeObjCGCAttr()
Definition: Type.h:324
QualType getType() const
Definition: CGValue.h:261
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot())
Definition: CGExpr.cpp:4193
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition: CGObjC.cpp:1972
bool isCanonical() const
Definition: Type.h:5762
static ConstantEmission forReference(llvm::Constant *C)
void enterFullExpression(const ExprWithCleanups *E)
const TargetCodeGenInfo & getTargetHooks() const
static Destroyer destroyARCStrongImprecise
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
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:2663
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...
Expr * getLHS() const
Definition: Expr.h:3029
void setExternallyDestructed(bool destructed=true)
Definition: CGValue.h:529
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
const Expr * getBase() const
Definition: Expr.h:4808
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:1537
! Language semantics require right-to-left evaluation.
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:276
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:59
ast_type_traits::DynTypedNode Node
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:5024
TLS with a dynamic initializer.
Definition: Decl.h:829
CGFunctionInfo - Class to encapsulate the information about a function definition.
This class organizes the cross-function state that is used while generating LLVM code.
const CGCalleeInfo & getAbstractInfo() const
Definition: CGCall.h:153
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset...
Definition: CharUnits.h:190
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
GC getObjCGCAttr() const
Definition: Type.h:320
Dataflow Directional Tag Classes.
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition: CGExpr.cpp:2223
uint64_t SanitizerMask
Definition: Sanitizers.h:24
bool isValid() const
Return true if this is a valid SourceLocation object.
void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
Definition: CGClass.cpp:2596
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1188
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
Definition: CGExpr.cpp:1097
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:93
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
Decl * getReferencedDeclOfCallee()
Definition: Expr.cpp:1224
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1216
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored...
Definition: CGValue.h:480
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
Definition: CGObjC.cpp:2258
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:172
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
Definition: CGCall.h:111
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
Checking the bound value in a reference binding.
LValue EmitCallExprLValue(const CallExpr *E)
Definition: CGExpr.cpp:4337
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition: CGExpr.cpp:4767
unsigned IsSigned
Whether the bit-field is signed.
llvm::Constant * getPointer() const
Definition: Address.h:84
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
StmtClass getStmtClass() const
Definition: Stmt.h:378
bool isBooleanType() const
Definition: Type.h:6232
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
enum clang::SubobjectAdjustment::@36 Kind
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
EnumDecl - Represents an enum.
Definition: Decl.h:3239
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, CharUnits EltSize, const llvm::Twine &Name="")
Given addr = T* ...
Definition: CGBuilder.h:211
Checking the destination of a store. Must be suitably sized and aligned.
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2502
bool isBitField() const
Definition: CGValue.h:251
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
semantics_iterator semantics_begin()
Definition: Expr.h:5037
llvm::Module & getModule() const
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1307
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:2888
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
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:1600
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Definition: CGExprAgg.cpp:1522
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2552
unsigned getBuiltinID() const
Definition: CGCall.h:137
static Address createReferenceTemporary(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *Inner)
Definition: CGExpr.cpp:348
Checking the operand of a static_cast to a derived reference type.
path_iterator path_end()
Definition: Expr.h:2778
static bool hasAggregateEvaluationKind(QualType T)
virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest)=0
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:951
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
virtual llvm::Optional< LangAS > getConstantAddressSpace() const
Return an AST address space which can be used opportunistically for constant global memory...
Definition: TargetInfo.h:989
AlignmentSource getAlignmentSource() const
Definition: CGValue.h:156
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3976
Complex values, per C99 6.2.5p11.
Definition: Type.h:2223
const LValue & getOpaqueLValueMapping(const OpaqueValueExpr *e)
getOpaqueLValueMapping - Given an opaque value expression (which must be mapped to an l-value)...
Checking the operand of a static_cast to a derived pointer type.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2121
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:3227
CodeGenTypes & getTypes() const
static StringRef getIdentTypeName(IdentType IT)
Definition: Expr.cpp:473
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6191
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate &#39;undef&#39; rvalue for the given type.
Definition: CGExpr.cpp:1071
Address getBitFieldAddress() const
Definition: CGValue.h:352
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:386
virtual bool usesThreadWrapperFunction() const =0
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Definition: CGExpr.cpp:3244
T * getAttr() const
Definition: DeclBase.h:531
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2011
bool isAtomicType() const
Definition: Type.h:6052
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition: CGExpr.cpp:3400
bool isFunctionType() const
Definition: Type.h:5938
llvm::Value * EmitCheckedInBoundsGEP(llvm::Value *Ptr, ArrayRef< llvm::Value *> IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition: CGExpr.cpp:4169
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1326
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
Definition: CGCall.h:119
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition: CGExpr.cpp:4420
static llvm::Value * emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low, llvm::Value *High)
Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
Definition: CGExpr.cpp:560
Opcode getOpcode() const
Definition: Expr.h:1741
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition: CGDecl.cpp:713
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.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition: CGExpr.cpp:4415
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value *> FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB)
Definition: CGExpr.cpp:2781
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type. ...
Definition: CGExpr.cpp:4014
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:445
void setGlobalObjCRef(bool Value)
Definition: CGValue.h:277
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition: CGObjC.cpp:2278
void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant *> StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false. ...
Definition: CGExpr.cpp:2934
const Expr * getBase() const
Definition: ExprObjC.h:547
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3022
ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E)
Returns a pointer to a constant global variable for the given file-scope compound literal expression...
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition: CGExpr.cpp:3082
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type, returning the result.
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
RValue asAggregateRValue() const
Definition: CGValue.h:428
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2007
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
SourceManager & getSourceManager()
Definition: ASTContext.h:643
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
Definition: CGExpr.cpp:3929
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1986
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
The type-property cache.
Definition: Type.cpp:3350
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:838
virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest)=0
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
Definition: Type.h:183
void setCurrentStmt(const Stmt *S)
If the execution count for the current statement is known, record that as the current count...
Definition: CodeGenPGO.h:75
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2387
static bool isConstantEmittableObjectType(QualType type)
Given an object of the given canonical type, can we safely copy a value out of it based on its initia...
Definition: CGExpr.cpp:1302
A non-RAII class containing all the information about a bound opaque value.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5798
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn&#39;t support the specified stmt yet...
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
LValue EmitCoawaitLValue(const CoawaitExpr *E)
bool isVoidType() const
Definition: Type.h:6169
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2856
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
Definition: CGExpr.cpp:571
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:4071
llvm::Type * ConvertType(QualType T)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5745
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:75
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:3407
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1964
! No language constraints on evaluation order.
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD)
Definition: CGExpr.cpp:4231
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1170
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitTrapCheck(llvm::Value *Checked)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it...
Definition: CGExpr.cpp:3093
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType)
If Base is known to point to the start of an array, return the length of that array.
Definition: CGExpr.cpp:858
bool isRValue() const
Definition: Expr.h:250
unsigned getVRQualifiers() const
Definition: CGValue.h:257
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
Definition: CGExpr.cpp:3886
FieldDecl * Field
Definition: Expr.h:79
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition: CGExpr.cpp:1682
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:50
LValue EmitPredefinedLValue(const PredefinedExpr *E)
Definition: CGExpr.cpp:2576
std::pair< llvm::Value *, QualType > getVLASize(const VariableArrayType *vla)
getVLASize - Returns an LLVM value that corresponds to the size, in non-variably-sized elements...
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1509
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:274
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
Definition: CGExpr.cpp:1111
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
Definition: CGExpr.cpp:4369
const MemberPointerType * MPT
Definition: Expr.h:73
bool isObjCArray() const
Definition: CGValue.h:270
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
Definition: CGExpr.cpp:1789
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3364
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
unsigned getCVRQualifiers() const
Definition: Type.h:291
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
CGCapturedStmtInfo * CapturedStmtInfo
bool isGlobalReg() const
Definition: CGValue.h:253
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
CGCXXABI & getCXXABI() const
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2324
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
static LValue MakeGlobalReg(Address Reg, QualType type)
Definition: CGValue.h:419
unsigned getNumElements() const
Definition: Type.h:2950
LValue EmitMemberExpr(const MemberExpr *E)
Definition: CGExpr.cpp:3651
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
bool isUnion() const
Definition: Decl.h:3165
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGBlocks.cpp:1100
Expr * getRHS() const
Definition: Expr.h:3031
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
Definition: CGExpr.cpp:1333
bool isPointerType() const
Definition: Type.h:5942
bool isExtVectorElt() const
Definition: CGValue.h:252
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments...
Definition: CGCall.cpp:597
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:2693
uint64_t Offset
Offset - The byte offset of the final access within the base one.
Definition: CodeGenTBAA.h:110
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition: Expr.cpp:2365
QualType getType() const
Definition: Decl.h:638
bool isFloatingType() const
Definition: Type.cpp:1877
static RValue getAggregate(Address addr, bool isVolatile=false)
Definition: CGValue.h:107
LValue - This represents an lvalue references.
Definition: CGValue.h:167
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
RValue asRValue() const
Definition: CGValue.h:571
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition: CGObjC.cpp:1788
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2717
CanQualType BoolTy
Definition: ASTContext.h:997
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:856
Automatic storage duration (most local variables).
Definition: Specifiers.h:275
SanitizerMetadata * getSanitizerMetadata()
const LangOptions & getLangOpts() const
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2407
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Definition: CGExpr.cpp:2980
const CXXRecordDecl * DerivedClass
Definition: Expr.h:69
bool isFunctionPointerType() const
Definition: Type.h:5966
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:454
static LValue MakeAddr(Address address, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:364
llvm::Value * getVectorIdx() const
Definition: CGValue.h:336
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of &#39;this&#39; and returns ...
Definition: CGClass.cpp:267
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
Address CreateMemTemp(QualType T, const Twine &Name="tmp", bool CastToDefaultAddrSpace=true)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignment...
Definition: CGExpr.cpp:127
const LangOptions & getLangOpts() const
Definition: ASTContext.h:688
static TBAAAccessInfo getMayAliasInfo()
Definition: CodeGenTBAA.h:64
llvm::Value * getPointer() const
Definition: CGValue.h:320
LValue EmitStringLiteralLValue(const StringLiteral *E)
Definition: CGExpr.cpp:2566
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
Definition: CGBlocks.cpp:2265
Abstract information about a function or function prototype.
Definition: CGCall.h:44
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool isScalar() const
Definition: CGValue.h:52
SourceLocation getLocation() const
Definition: DeclBase.h:416
void mergeForCast(const LValueBaseInfo &Info)
Definition: CGValue.h:159
llvm::Constant * getExtVectorElts() const
Definition: CGValue.h:346
Expr * getLength()
Get length of array section.
Definition: ExprOpenMP.h:99
Structure with information about how a bitfield should be accessed.
CheckRecoverableKind
Specify under what conditions this check can be recovered.
Definition: CGExpr.cpp:2744
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2434
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr *> VL, ArrayRef< Expr *> PL, ArrayRef< Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
Definition: ExprOpenMP.h:82
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1070
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, Address AddrWeakObj)=0
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1524
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer...
Definition: CGExpr.cpp:3162
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
Definition: CGExpr.cpp:553