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