1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
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"
29 #include "clang/Frontend/CodeGenOptions.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"
43 using namespace clang;
44 using namespace CodeGen;
46 //===--------------------------------------------------------------------===//
47 // Miscellaneous Helper Methods
48 //===--------------------------------------------------------------------===//
50 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
51 unsigned addressSpace =
52 cast<llvm::PointerType>(value->getType())->getAddressSpace();
54 llvm::PointerType *destType = Int8PtrTy;
56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
58 if (value->getType() == destType) return value;
59 return Builder.CreateBitCast(value, destType);
62 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
64 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
66 llvm::Value *ArraySize,
67 bool CastToDefaultAddrSpace) {
68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
69 Alloca->setAlignment(Align.getQuantity());
70 llvm::Value *V = Alloca;
71 // Alloca always returns a pointer in alloca address space, which may
72 // be different from the type defined by the language. For example,
73 // in C++ the auto variables are in the default address space. Therefore
74 // cast alloca to the default address space when necessary.
75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
77 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
78 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
79 // otherwise alloca is inserted at the current insertion point of the
82 Builder.SetInsertPoint(AllocaInsertPt);
83 V = getTargetHooks().performAddrSpaceCast(
84 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
85 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
88 return Address(V, Align);
91 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
92 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
93 /// insertion point of the builder.
94 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
96 llvm::Value *ArraySize) {
98 return Builder.CreateAlloca(Ty, ArraySize, Name);
99 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
100 ArraySize, Name, AllocaInsertPt);
103 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
104 /// default alignment of the corresponding LLVM type, which is *not*
105 /// guaranteed to be related in any way to the expected alignment of
106 /// an AST type that might have been lowered to Ty.
107 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
110 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
111 return CreateTempAlloca(Ty, Align, Name);
114 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
115 assert(isa<llvm::AllocaInst>(Var.getPointer()));
116 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
117 Store->setAlignment(Var.getAlignment().getQuantity());
118 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
119 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
122 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
123 CharUnits Align = getContext().getTypeAlignInChars(Ty);
124 return CreateTempAlloca(ConvertType(Ty), Align, Name);
127 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
128 bool CastToDefaultAddrSpace) {
129 // FIXME: Should we prefer the preferred type alignment here?
130 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
131 CastToDefaultAddrSpace);
134 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
136 bool CastToDefaultAddrSpace) {
137 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
138 CastToDefaultAddrSpace);
141 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
142 /// expression and compare the result against zero, returning an Int1Ty value.
143 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
144 PGO.setCurrentStmt(E);
145 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
146 llvm::Value *MemPtr = EmitScalarExpr(E);
147 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
150 QualType BoolTy = getContext().BoolTy;
151 SourceLocation Loc = E->getExprLoc();
152 if (!E->getType()->isAnyComplexType())
153 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
155 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
159 /// EmitIgnoredExpr - Emit code to compute the specified expression,
160 /// ignoring the result.
161 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
163 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
165 // Just emit it as an l-value and drop the result.
169 /// EmitAnyExpr - Emit code to compute the specified expression which
170 /// can have any type. The result is returned as an RValue struct.
171 /// If this is an aggregate expression, AggSlot indicates where the
172 /// result should be returned.
173 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
174 AggValueSlot aggSlot,
176 switch (getEvaluationKind(E->getType())) {
178 return RValue::get(EmitScalarExpr(E, ignoreResult));
180 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
182 if (!ignoreResult && aggSlot.isIgnored())
183 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
184 EmitAggExpr(E, aggSlot);
185 return aggSlot.asRValue();
187 llvm_unreachable("bad evaluation kind");
190 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
191 /// always be accessible even if no aggregate location is provided.
192 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
193 AggValueSlot AggSlot = AggValueSlot::ignored();
195 if (hasAggregateEvaluationKind(E->getType()))
196 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
197 return EmitAnyExpr(E, AggSlot);
200 /// EmitAnyExprToMem - Evaluate an expression into a given memory
202 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
206 // FIXME: This function should take an LValue as an argument.
207 switch (getEvaluationKind(E->getType())) {
209 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
213 case TEK_Aggregate: {
214 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
215 AggValueSlot::IsDestructed_t(IsInit),
216 AggValueSlot::DoesNotNeedGCBarriers,
217 AggValueSlot::IsAliased_t(!IsInit)));
222 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
223 LValue LV = MakeAddrLValue(Location, E->getType());
224 EmitStoreThroughLValue(RV, LV);
228 llvm_unreachable("bad evaluation kind");
232 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
233 const Expr *E, Address ReferenceTemporary) {
234 // Objective-C++ ARC:
235 // If we are binding a reference to a temporary that has ownership, we
236 // need to perform retain/release operations on the temporary.
238 // FIXME: This should be looking at E, not M.
239 if (auto Lifetime = M->getType().getObjCLifetime()) {
241 case Qualifiers::OCL_None:
242 case Qualifiers::OCL_ExplicitNone:
243 // Carry on to normal cleanup handling.
246 case Qualifiers::OCL_Autoreleasing:
247 // Nothing to do; cleaned up by an autorelease pool.
250 case Qualifiers::OCL_Strong:
251 case Qualifiers::OCL_Weak:
252 switch (StorageDuration Duration = M->getStorageDuration()) {
254 // Note: we intentionally do not register a cleanup to release
255 // the object on program termination.
259 // FIXME: We should probably register a cleanup in this case.
263 case SD_FullExpression:
264 CodeGenFunction::Destroyer *Destroy;
265 CleanupKind CleanupKind;
266 if (Lifetime == Qualifiers::OCL_Strong) {
267 const ValueDecl *VD = M->getExtendingDecl();
269 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
270 CleanupKind = CGF.getARCCleanupKind();
271 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
272 : &CodeGenFunction::destroyARCStrongImprecise;
274 // __weak objects always get EH cleanups; otherwise, exceptions
275 // could cause really nasty crashes instead of mere leaks.
276 CleanupKind = NormalAndEHCleanup;
277 Destroy = &CodeGenFunction::destroyARCWeak;
279 if (Duration == SD_FullExpression)
280 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
281 M->getType(), *Destroy,
282 CleanupKind & EHCleanup);
284 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
286 *Destroy, CleanupKind & EHCleanup);
290 llvm_unreachable("temporary cannot have dynamic storage duration");
292 llvm_unreachable("unknown storage duration");
296 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
297 if (const RecordType *RT =
298 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
299 // Get the destructor for the reference temporary.
300 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
301 if (!ClassDecl->hasTrivialDestructor())
302 ReferenceTemporaryDtor = ClassDecl->getDestructor();
305 if (!ReferenceTemporaryDtor)
308 // Call the destructor for the temporary.
309 switch (M->getStorageDuration()) {
312 llvm::Constant *CleanupFn;
313 llvm::Constant *CleanupArg;
314 if (E->getType()->isArrayType()) {
315 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
316 ReferenceTemporary, E->getType(),
317 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
318 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
319 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
321 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
322 StructorType::Complete);
323 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
325 CGF.CGM.getCXXABI().registerGlobalDtor(
326 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
330 case SD_FullExpression:
331 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
337 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
338 ReferenceTemporary, E->getType(),
339 CodeGenFunction::destroyCXXObject,
340 CGF.getLangOpts().Exceptions);
344 llvm_unreachable("temporary cannot have dynamic storage duration");
348 static Address createReferenceTemporary(CodeGenFunction &CGF,
349 const MaterializeTemporaryExpr *M,
351 auto &TCG = CGF.getTargetHooks();
352 switch (M->getStorageDuration()) {
353 case SD_FullExpression:
355 // If we have a constant temporary array or record try to promote it into a
356 // constant global under the same rules a normal constant would've been
357 // promoted. This is easier on the optimizer and generally emits fewer
359 QualType Ty = Inner->getType();
360 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
361 (Ty->isArrayType() || Ty->isRecordType()) &&
362 CGF.CGM.isTypeConstant(Ty, true))
363 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
364 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
365 auto AS = AddrSpace.getValue();
366 auto *GV = new llvm::GlobalVariable(
367 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
368 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
369 llvm::GlobalValue::NotThreadLocal,
370 CGF.getContext().getTargetAddressSpace(AS));
371 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
372 GV->setAlignment(alignment.getQuantity());
373 llvm::Constant *C = GV;
374 if (AS != LangAS::Default)
375 C = TCG.performAddrSpaceCast(
376 CGF.CGM, GV, AS, LangAS::Default,
377 GV->getValueType()->getPointerTo(
378 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
379 // FIXME: Should we put the new global into a COMDAT?
380 return Address(C, alignment);
383 return CGF.CreateMemTemp(Ty, "ref.tmp");
387 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
390 llvm_unreachable("temporary can't have dynamic storage duration");
392 llvm_unreachable("unknown storage duration");
395 LValue CodeGenFunction::
396 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
397 const Expr *E = M->GetTemporaryExpr();
399 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
400 // as that will cause the lifetime adjustment to be lost for ARC
401 auto ownership = M->getType().getObjCLifetime();
402 if (ownership != Qualifiers::OCL_None &&
403 ownership != Qualifiers::OCL_ExplicitNone) {
404 Address Object = createReferenceTemporary(*this, M, E);
405 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
406 Object = Address(llvm::ConstantExpr::getBitCast(Var,
407 ConvertTypeForMem(E->getType())
408 ->getPointerTo(Object.getAddressSpace())),
409 Object.getAlignment());
411 // createReferenceTemporary will promote the temporary to a global with a
412 // constant initializer if it can. It can only do this to a value of
413 // ARC-manageable type if the value is global and therefore "immune" to
414 // ref-counting operations. Therefore we have no need to emit either a
415 // dynamic initialization or a cleanup and we can just return the address
417 if (Var->hasInitializer())
418 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
420 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
422 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
423 AlignmentSource::Decl);
425 switch (getEvaluationKind(E->getType())) {
426 default: llvm_unreachable("expected scalar or aggregate expression");
428 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
430 case TEK_Aggregate: {
431 EmitAggExpr(E, AggValueSlot::forAddr(Object,
432 E->getType().getQualifiers(),
433 AggValueSlot::IsDestructed,
434 AggValueSlot::DoesNotNeedGCBarriers,
435 AggValueSlot::IsNotAliased));
440 pushTemporaryCleanup(*this, M, E, Object);
444 SmallVector<const Expr *, 2> CommaLHSs;
445 SmallVector<SubobjectAdjustment, 2> Adjustments;
446 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
448 for (const auto &Ignored : CommaLHSs)
449 EmitIgnoredExpr(Ignored);
451 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
452 if (opaque->getType()->isRecordType()) {
453 assert(Adjustments.empty());
454 return EmitOpaqueValueLValue(opaque);
458 // Create and initialize the reference temporary.
459 Address Object = createReferenceTemporary(*this, M, E);
460 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
461 Object.getPointer()->stripPointerCasts())) {
462 Object = Address(llvm::ConstantExpr::getBitCast(
463 cast<llvm::Constant>(Object.getPointer()),
464 ConvertTypeForMem(E->getType())->getPointerTo()),
465 Object.getAlignment());
466 // If the temporary is a global and has a constant initializer or is a
467 // constant temporary that we promoted to a global, we may have already
469 if (!Var->hasInitializer()) {
470 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
471 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
474 switch (M->getStorageDuration()) {
476 case SD_FullExpression:
477 if (auto *Size = EmitLifetimeStart(
478 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
479 Object.getPointer())) {
480 if (M->getStorageDuration() == SD_Automatic)
481 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
484 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
491 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
493 pushTemporaryCleanup(*this, M, E, Object);
495 // Perform derived-to-base casts and/or field accesses, to get from the
496 // temporary object we created (and, potentially, for which we extended
497 // the lifetime) to the subobject we're binding the reference to.
498 for (unsigned I = Adjustments.size(); I != 0; --I) {
499 SubobjectAdjustment &Adjustment = Adjustments[I-1];
500 switch (Adjustment.Kind) {
501 case SubobjectAdjustment::DerivedToBaseAdjustment:
503 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
504 Adjustment.DerivedToBase.BasePath->path_begin(),
505 Adjustment.DerivedToBase.BasePath->path_end(),
506 /*NullCheckValue=*/ false, E->getExprLoc());
509 case SubobjectAdjustment::FieldAdjustment: {
510 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
511 LV = EmitLValueForField(LV, Adjustment.Field);
512 assert(LV.isSimple() &&
513 "materialized temporary field is not a simple lvalue");
514 Object = LV.getAddress();
518 case SubobjectAdjustment::MemberPointerAdjustment: {
519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
527 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
531 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
532 // Emit the expression as an lvalue.
533 LValue LV = EmitLValue(E);
534 assert(LV.isSimple());
535 llvm::Value *Value = LV.getPointer();
537 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
538 // C++11 [dcl.ref]p5 (as amended by core issue 453):
539 // If a glvalue to which a reference is directly bound designates neither
540 // an existing object or function of an appropriate type nor a region of
541 // storage of suitable size and alignment to contain an object of the
542 // reference's type, the behavior is undefined.
543 QualType Ty = E->getType();
544 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
547 return RValue::get(Value);
551 /// getAccessedFieldNo - Given an encoded value and a result number, return the
552 /// input field number being accessed.
553 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
554 const llvm::Constant *Elts) {
555 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
559 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
560 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
562 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
563 llvm::Value *K47 = Builder.getInt64(47);
564 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
565 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
566 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
567 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
568 return Builder.CreateMul(B1, KMul);
571 bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
572 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
573 TCK == TCK_UpcastToVirtualBase;
576 bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
577 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
578 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
579 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
580 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
581 TCK == TCK_UpcastToVirtualBase);
584 bool CodeGenFunction::sanitizePerformTypeCheck() const {
585 return SanOpts.has(SanitizerKind::Null) |
586 SanOpts.has(SanitizerKind::Alignment) |
587 SanOpts.has(SanitizerKind::ObjectSize) |
588 SanOpts.has(SanitizerKind::Vptr);
591 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
592 llvm::Value *Ptr, QualType Ty,
594 SanitizerSet SkippedChecks) {
595 if (!sanitizePerformTypeCheck())
598 // Don't check pointers outside the default address space. The null check
599 // isn't correct, the object-size check isn't supported by LLVM, and we can't
600 // communicate the addresses to the runtime handler for the vptr check.
601 if (Ptr->getType()->getPointerAddressSpace())
604 // Don't check pointers to volatile data. The behavior here is implementation-
606 if (Ty.isVolatileQualified())
609 SanitizerScope SanScope(this);
611 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
612 llvm::BasicBlock *Done = nullptr;
614 // Quickly determine whether we have a pointer to an alloca. It's possible
615 // to skip null checks, and some alignment checks, for these pointers. This
616 // can reduce compile-time significantly.
618 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
620 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
621 llvm::Value *IsNonNull = nullptr;
622 bool IsGuaranteedNonNull =
623 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
624 bool AllowNullPointers = isNullPointerAllowed(TCK);
625 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
626 !IsGuaranteedNonNull) {
627 // The glvalue must not be an empty glvalue.
628 IsNonNull = Builder.CreateIsNotNull(Ptr);
630 // The IR builder can constant-fold the null check if the pointer points to
632 IsGuaranteedNonNull = IsNonNull == True;
634 // Skip the null check if the pointer is known to be non-null.
635 if (!IsGuaranteedNonNull) {
636 if (AllowNullPointers) {
637 // When performing pointer casts, it's OK if the value is null.
638 // Skip the remaining checks in that case.
639 Done = createBasicBlock("null");
640 llvm::BasicBlock *Rest = createBasicBlock("not.null");
641 Builder.CreateCondBr(IsNonNull, Rest, Done);
644 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
649 if (SanOpts.has(SanitizerKind::ObjectSize) &&
650 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
651 !Ty->isIncompleteType()) {
652 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
654 // The glvalue must refer to a large enough storage region.
655 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
657 // FIXME: Get object address space
658 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
659 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
660 llvm::Value *Min = Builder.getFalse();
661 llvm::Value *NullIsUnknown = Builder.getFalse();
662 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
663 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
664 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
665 llvm::ConstantInt::get(IntPtrTy, Size));
666 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
669 uint64_t AlignVal = 0;
670 llvm::Value *PtrAsInt = nullptr;
672 if (SanOpts.has(SanitizerKind::Alignment) &&
673 !SkippedChecks.has(SanitizerKind::Alignment)) {
674 AlignVal = Alignment.getQuantity();
675 if (!Ty->isIncompleteType() && !AlignVal)
676 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
678 // The glvalue must be suitably aligned.
680 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
681 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
682 llvm::Value *Align = Builder.CreateAnd(
683 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
684 llvm::Value *Aligned =
685 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
687 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
691 if (Checks.size() > 0) {
692 // Make sure we're not losing information. Alignment needs to be a power of
694 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
695 llvm::Constant *StaticData[] = {
696 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
697 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698 llvm::ConstantInt::get(Int8Ty, TCK)};
699 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700 PtrAsInt ? PtrAsInt : Ptr);
703 // If possible, check that the vptr indicates that there is a subobject of
704 // type Ty at offset zero within this object.
706 // C++11 [basic.life]p5,6:
707 // [For storage which does not refer to an object within its lifetime]
708 // The program has undefined behavior if:
709 // -- the [pointer or glvalue] is used to access a non-static data member
710 // or call a non-static member function
711 if (SanOpts.has(SanitizerKind::Vptr) &&
712 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
713 // Ensure that the pointer is non-null before loading it. If there is no
714 // compile-time guarantee, reuse the run-time null check or emit a new one.
715 if (!IsGuaranteedNonNull) {
717 IsNonNull = Builder.CreateIsNotNull(Ptr);
719 Done = createBasicBlock("vptr.null");
720 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722 EmitBlock(VptrNotNull);
725 // Compute a hash of the mangled name of the type.
727 // FIXME: This is not guaranteed to be deterministic! Move to a
728 // fingerprinting mechanism once LLVM provides one. For the time
729 // being the implementation happens to be deterministic.
730 SmallString<64> MangledName;
731 llvm::raw_svector_ostream Out(MangledName);
732 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
735 // Blacklist based on the mangled type.
736 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
737 SanitizerKind::Vptr, Out.str())) {
738 llvm::hash_code TypeHash = hash_value(Out.str());
740 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
743 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
744 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
747 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
750 // Look the hash up in our cache.
751 const int CacheSize = 128;
752 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
753 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
754 "__ubsan_vptr_type_cache");
755 llvm::Value *Slot = Builder.CreateAnd(Hash,
756 llvm::ConstantInt::get(IntPtrTy,
758 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759 llvm::Value *CacheVal =
760 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
763 // If the hash isn't in the cache, call a runtime handler to perform the
764 // hard work of checking whether the vptr is for an object of the right
765 // type. This will either fill in the cache and return, or produce a
767 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
768 llvm::Constant *StaticData[] = {
769 EmitCheckSourceLocation(Loc),
770 EmitCheckTypeDescriptor(Ty),
771 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
772 llvm::ConstantInt::get(Int8Ty, TCK)
774 llvm::Value *DynamicData[] = { Ptr, Hash };
775 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
776 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
782 Builder.CreateBr(Done);
787 /// Determine whether this expression refers to a flexible array member in a
788 /// struct. We disable array bounds checks for such members.
789 static bool isFlexibleArrayMemberExpr(const Expr *E) {
790 // For compatibility with existing code, we treat arrays of length 0 or
791 // 1 as flexible array members.
792 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
793 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
794 if (CAT->getSize().ugt(1))
796 } else if (!isa<IncompleteArrayType>(AT))
799 E = E->IgnoreParens();
801 // A flexible array member must be the last member in the class.
802 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
803 // FIXME: If the base type of the member expr is not FD->getParent(),
804 // this should not be treated as a flexible array member access.
805 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
806 RecordDecl::field_iterator FI(
807 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808 return ++FI == FD->getParent()->field_end();
810 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811 return IRE->getDecl()->getNextIvar() == nullptr;
817 llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
819 ASTContext &C = getContext();
820 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
824 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
828 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
832 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
836 // Don't load the size if it's a lower bound.
837 int POSType = POSAttr->getType();
838 if (POSType != 0 && POSType != 1)
841 // Find the implicit size parameter.
842 auto PassedSizeIt = SizeArguments.find(ParamDecl);
843 if (PassedSizeIt == SizeArguments.end())
846 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
847 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
848 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
849 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
850 C.getSizeType(), E->getExprLoc());
851 llvm::Value *SizeOfElement =
852 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
853 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
856 /// If Base is known to point to the start of an array, return the length of
857 /// that array. Return 0 if the length cannot be determined.
858 static llvm::Value *getArrayIndexingBound(
859 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
860 // For the vector indexing extension, the bound is the number of elements.
861 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
862 IndexedType = Base->getType();
863 return CGF.Builder.getInt32(VT->getNumElements());
866 Base = Base->IgnoreParens();
868 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
869 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
870 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
871 IndexedType = CE->getSubExpr()->getType();
872 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
873 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
874 return CGF.Builder.getInt(CAT->getSize());
875 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
876 return CGF.getVLASize(VAT).first;
877 // Ignore pass_object_size here. It's not applicable on decayed pointers.
881 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
882 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
883 IndexedType = Base->getType();
890 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
891 llvm::Value *Index, QualType IndexType,
893 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
894 "should not be called unless adding bounds checks");
895 SanitizerScope SanScope(this);
897 QualType IndexedType;
898 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
902 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
903 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
904 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
906 llvm::Constant *StaticData[] = {
907 EmitCheckSourceLocation(E->getExprLoc()),
908 EmitCheckTypeDescriptor(IndexedType),
909 EmitCheckTypeDescriptor(IndexType)
911 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
912 : Builder.CreateICmpULE(IndexVal, BoundVal);
913 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
914 SanitizerHandler::OutOfBounds, StaticData, Index);
918 CodeGenFunction::ComplexPairTy CodeGenFunction::
919 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
920 bool isInc, bool isPre) {
921 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
923 llvm::Value *NextVal;
924 if (isa<llvm::IntegerType>(InVal.first->getType())) {
925 uint64_t AmountVal = isInc ? 1 : -1;
926 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
928 // Add the inc/dec to the real part.
929 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
931 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
932 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
935 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
937 // Add the inc/dec to the real part.
938 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
941 ComplexPairTy IncVal(NextVal, InVal.second);
943 // Store the updated result through the lvalue.
944 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
946 // If this is a postinc, return the value read from memory, otherwise use the
948 return isPre ? IncVal : InVal;
951 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
952 CodeGenFunction *CGF) {
953 // Bind VLAs in the cast type.
954 if (CGF && E->getType()->isVariablyModifiedType())
955 CGF->EmitVariablyModifiedType(E->getType());
957 if (CGDebugInfo *DI = getModuleDebugInfo())
958 DI->EmitExplicitCastType(E->getType());
961 //===----------------------------------------------------------------------===//
962 // LValue Expression Emission
963 //===----------------------------------------------------------------------===//
965 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
966 /// derive a more accurate bound on the alignment of the pointer.
967 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
968 LValueBaseInfo *BaseInfo,
969 TBAAAccessInfo *TBAAInfo) {
970 // We allow this with ObjC object pointers because of fragile ABIs.
971 assert(E->getType()->isPointerType() ||
972 E->getType()->isObjCObjectPointerType());
973 E = E->IgnoreParens();
976 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
977 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
978 CGM.EmitExplicitCastExprType(ECE, this);
980 switch (CE->getCastKind()) {
981 // Non-converting casts (but not C's implicit conversion from void*).
984 case CK_AddressSpaceConversion:
985 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
986 if (PtrTy->getPointeeType()->isVoidType())
989 LValueBaseInfo InnerBaseInfo;
990 TBAAAccessInfo InnerTBAAInfo;
991 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
994 if (BaseInfo) *BaseInfo = InnerBaseInfo;
995 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
997 if (isa<ExplicitCastExpr>(CE)) {
998 LValueBaseInfo TargetTypeBaseInfo;
999 TBAAAccessInfo TargetTypeTBAAInfo;
1000 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
1001 &TargetTypeBaseInfo,
1002 &TargetTypeTBAAInfo);
1004 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1005 TargetTypeTBAAInfo);
1006 // If the source l-value is opaque, honor the alignment of the
1008 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1010 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1011 Addr = Address(Addr.getPointer(), Align);
1015 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1016 CE->getCastKind() == CK_BitCast) {
1017 if (auto PT = E->getType()->getAs<PointerType>())
1018 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1020 CodeGenFunction::CFITCK_UnrelatedCast,
1023 return CE->getCastKind() != CK_AddressSpaceConversion
1024 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1025 : Builder.CreateAddrSpaceCast(Addr,
1026 ConvertType(E->getType()));
1030 // Array-to-pointer decay.
1031 case CK_ArrayToPointerDecay:
1032 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1034 // Derived-to-base conversions.
1035 case CK_UncheckedDerivedToBase:
1036 case CK_DerivedToBase: {
1037 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo,
1039 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1040 return GetAddressOfBaseClass(Addr, Derived,
1041 CE->path_begin(), CE->path_end(),
1042 ShouldNullCheckClassCastValue(CE),
1046 // TODO: Is there any reason to treat base-to-derived conversions
1054 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1055 if (UO->getOpcode() == UO_AddrOf) {
1056 LValue LV = EmitLValue(UO->getSubExpr());
1057 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1058 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1059 return LV.getAddress();
1063 // TODO: conditional operators, comma.
1065 // Otherwise, use the alignment of the type.
1066 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1068 return Address(EmitScalarExpr(E), Align);
1071 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1072 if (Ty->isVoidType())
1073 return RValue::get(nullptr);
1075 switch (getEvaluationKind(Ty)) {
1078 ConvertType(Ty->castAs<ComplexType>()->getElementType());
1079 llvm::Value *U = llvm::UndefValue::get(EltTy);
1080 return RValue::getComplex(std::make_pair(U, U));
1083 // If this is a use of an undefined aggregate type, the aggregate must have an
1084 // identifiable address. Just because the contents of the value are undefined
1085 // doesn't mean that the address can't be taken and compared.
1086 case TEK_Aggregate: {
1087 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1088 return RValue::getAggregate(DestPtr);
1092 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1094 llvm_unreachable("bad evaluation kind");
1097 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1099 ErrorUnsupported(E, Name);
1100 return GetUndefRValue(E->getType());
1103 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1105 ErrorUnsupported(E, Name);
1106 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1107 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1111 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1112 const Expr *Base = Obj;
1113 while (!isa<CXXThisExpr>(Base)) {
1114 // The result of a dynamic_cast can be null.
1115 if (isa<CXXDynamicCastExpr>(Base))
1118 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1119 Base = CE->getSubExpr();
1120 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1121 Base = PE->getSubExpr();
1122 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1123 if (UO->getOpcode() == UO_Extension)
1124 Base = UO->getSubExpr();
1134 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1136 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1137 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1140 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1141 SanitizerSet SkippedChecks;
1142 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1143 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1145 SkippedChecks.set(SanitizerKind::Alignment, true);
1146 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1147 SkippedChecks.set(SanitizerKind::Null, true);
1149 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1150 E->getType(), LV.getAlignment(), SkippedChecks);
1155 /// EmitLValue - Emit code to compute a designator that specifies the location
1156 /// of the expression.
1158 /// This can return one of two things: a simple address or a bitfield reference.
1159 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1160 /// an LLVM pointer type.
1162 /// If this returns a bitfield reference, nothing about the pointee type of the
1163 /// LLVM value is known: For example, it may not be a pointer to an integer.
1165 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1166 /// this method guarantees that the returned pointer type will point to an LLVM
1167 /// type of the same size of the lvalue's type. If the lvalue has a variable
1168 /// length type, this is not possible.
1170 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1171 ApplyDebugLocation DL(*this, E);
1172 switch (E->getStmtClass()) {
1173 default: return EmitUnsupportedLValue(E, "l-value expression");
1175 case Expr::ObjCPropertyRefExprClass:
1176 llvm_unreachable("cannot emit a property reference directly");
1178 case Expr::ObjCSelectorExprClass:
1179 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1180 case Expr::ObjCIsaExprClass:
1181 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1182 case Expr::BinaryOperatorClass:
1183 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1184 case Expr::CompoundAssignOperatorClass: {
1185 QualType Ty = E->getType();
1186 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1187 Ty = AT->getValueType();
1188 if (!Ty->isAnyComplexType())
1189 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1190 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1192 case Expr::CallExprClass:
1193 case Expr::CXXMemberCallExprClass:
1194 case Expr::CXXOperatorCallExprClass:
1195 case Expr::UserDefinedLiteralClass:
1196 return EmitCallExprLValue(cast<CallExpr>(E));
1197 case Expr::VAArgExprClass:
1198 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1199 case Expr::DeclRefExprClass:
1200 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1201 case Expr::ParenExprClass:
1202 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1203 case Expr::GenericSelectionExprClass:
1204 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1205 case Expr::PredefinedExprClass:
1206 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1207 case Expr::StringLiteralClass:
1208 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1209 case Expr::ObjCEncodeExprClass:
1210 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1211 case Expr::PseudoObjectExprClass:
1212 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1213 case Expr::InitListExprClass:
1214 return EmitInitListLValue(cast<InitListExpr>(E));
1215 case Expr::CXXTemporaryObjectExprClass:
1216 case Expr::CXXConstructExprClass:
1217 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1218 case Expr::CXXBindTemporaryExprClass:
1219 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1220 case Expr::CXXUuidofExprClass:
1221 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1222 case Expr::LambdaExprClass:
1223 return EmitLambdaLValue(cast<LambdaExpr>(E));
1225 case Expr::ExprWithCleanupsClass: {
1226 const auto *cleanups = cast<ExprWithCleanups>(E);
1227 enterFullExpression(cleanups);
1228 RunCleanupsScope Scope(*this);
1229 LValue LV = EmitLValue(cleanups->getSubExpr());
1230 if (LV.isSimple()) {
1231 // Defend against branches out of gnu statement expressions surrounded by
1233 llvm::Value *V = LV.getPointer();
1234 Scope.ForceCleanup({&V});
1235 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1236 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
1238 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1239 // bitfield lvalue or some other non-simple lvalue?
1243 case Expr::CXXDefaultArgExprClass:
1244 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1245 case Expr::CXXDefaultInitExprClass: {
1246 CXXDefaultInitExprScope Scope(*this);
1247 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1249 case Expr::CXXTypeidExprClass:
1250 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1252 case Expr::ObjCMessageExprClass:
1253 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1254 case Expr::ObjCIvarRefExprClass:
1255 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1256 case Expr::StmtExprClass:
1257 return EmitStmtExprLValue(cast<StmtExpr>(E));
1258 case Expr::UnaryOperatorClass:
1259 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1260 case Expr::ArraySubscriptExprClass:
1261 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1262 case Expr::OMPArraySectionExprClass:
1263 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1264 case Expr::ExtVectorElementExprClass:
1265 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1266 case Expr::MemberExprClass:
1267 return EmitMemberExpr(cast<MemberExpr>(E));
1268 case Expr::CompoundLiteralExprClass:
1269 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1270 case Expr::ConditionalOperatorClass:
1271 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1272 case Expr::BinaryConditionalOperatorClass:
1273 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1274 case Expr::ChooseExprClass:
1275 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1276 case Expr::OpaqueValueExprClass:
1277 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1278 case Expr::SubstNonTypeTemplateParmExprClass:
1279 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1280 case Expr::ImplicitCastExprClass:
1281 case Expr::CStyleCastExprClass:
1282 case Expr::CXXFunctionalCastExprClass:
1283 case Expr::CXXStaticCastExprClass:
1284 case Expr::CXXDynamicCastExprClass:
1285 case Expr::CXXReinterpretCastExprClass:
1286 case Expr::CXXConstCastExprClass:
1287 case Expr::ObjCBridgedCastExprClass:
1288 return EmitCastLValue(cast<CastExpr>(E));
1290 case Expr::MaterializeTemporaryExprClass:
1291 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1293 case Expr::CoawaitExprClass:
1294 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1295 case Expr::CoyieldExprClass:
1296 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1300 /// Given an object of the given canonical type, can we safely copy a
1301 /// value out of it based on its initializer?
1302 static bool isConstantEmittableObjectType(QualType type) {
1303 assert(type.isCanonical());
1304 assert(!type->isReferenceType());
1306 // Must be const-qualified but non-volatile.
1307 Qualifiers qs = type.getLocalQualifiers();
1308 if (!qs.hasConst() || qs.hasVolatile()) return false;
1310 // Otherwise, all object types satisfy this except C++ classes with
1311 // mutable subobjects or non-trivial copy/destroy behavior.
1312 if (const auto *RT = dyn_cast<RecordType>(type))
1313 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1314 if (RD->hasMutableFields() || !RD->isTrivial())
1320 /// Can we constant-emit a load of a reference to a variable of the
1321 /// given type? This is different from predicates like
1322 /// Decl::isUsableInConstantExpressions because we do want it to apply
1323 /// in situations that don't necessarily satisfy the language's rules
1324 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1325 /// to do this with const float variables even if those variables
1326 /// aren't marked 'constexpr'.
1327 enum ConstantEmissionKind {
1329 CEK_AsReferenceOnly,
1330 CEK_AsValueOrReference,
1333 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1334 type = type.getCanonicalType();
1335 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1336 if (isConstantEmittableObjectType(ref->getPointeeType()))
1337 return CEK_AsValueOrReference;
1338 return CEK_AsReferenceOnly;
1340 if (isConstantEmittableObjectType(type))
1341 return CEK_AsValueOnly;
1345 /// Try to emit a reference to the given value without producing it as
1346 /// an l-value. This is actually more than an optimization: we can't
1347 /// produce an l-value for variables that we never actually captured
1348 /// in a block or lambda, which means const int variables or constexpr
1349 /// literals or similar.
1350 CodeGenFunction::ConstantEmission
1351 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1352 ValueDecl *value = refExpr->getDecl();
1354 // The value needs to be an enum constant or a constant variable.
1355 ConstantEmissionKind CEK;
1356 if (isa<ParmVarDecl>(value)) {
1358 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1359 CEK = checkVarTypeForConstantEmission(var->getType());
1360 } else if (isa<EnumConstantDecl>(value)) {
1361 CEK = CEK_AsValueOnly;
1365 if (CEK == CEK_None) return ConstantEmission();
1367 Expr::EvalResult result;
1368 bool resultIsReference;
1369 QualType resultType;
1371 // It's best to evaluate all the way as an r-value if that's permitted.
1372 if (CEK != CEK_AsReferenceOnly &&
1373 refExpr->EvaluateAsRValue(result, getContext())) {
1374 resultIsReference = false;
1375 resultType = refExpr->getType();
1377 // Otherwise, try to evaluate as an l-value.
1378 } else if (CEK != CEK_AsValueOnly &&
1379 refExpr->EvaluateAsLValue(result, getContext())) {
1380 resultIsReference = true;
1381 resultType = value->getType();
1385 return ConstantEmission();
1388 // In any case, if the initializer has side-effects, abandon ship.
1389 if (result.HasSideEffects)
1390 return ConstantEmission();
1392 // Emit as a constant.
1393 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1394 result.Val, resultType);
1396 // Make sure we emit a debug reference to the global variable.
1397 // This should probably fire even for
1398 if (isa<VarDecl>(value)) {
1399 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1400 EmitDeclRefExprDbgValue(refExpr, result.Val);
1402 assert(isa<EnumConstantDecl>(value));
1403 EmitDeclRefExprDbgValue(refExpr, result.Val);
1406 // If we emitted a reference constant, we need to dereference that.
1407 if (resultIsReference)
1408 return ConstantEmission::forReference(C);
1410 return ConstantEmission::forValue(C);
1413 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1414 const MemberExpr *ME) {
1415 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1416 // Try to emit static variable member expressions as DREs.
1417 return DeclRefExpr::Create(
1418 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1419 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1420 ME->getType(), ME->getValueKind());
1425 CodeGenFunction::ConstantEmission
1426 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1427 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1428 return tryEmitAsConstant(DRE);
1429 return ConstantEmission();
1432 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1433 SourceLocation Loc) {
1434 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1435 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1436 lvalue.getTBAAInfo(), lvalue.isNontemporal());
1439 static bool hasBooleanRepresentation(QualType Ty) {
1440 if (Ty->isBooleanType())
1443 if (const EnumType *ET = Ty->getAs<EnumType>())
1444 return ET->getDecl()->getIntegerType()->isBooleanType();
1446 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1447 return hasBooleanRepresentation(AT->getValueType());
1452 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1453 llvm::APInt &Min, llvm::APInt &End,
1454 bool StrictEnums, bool IsBool) {
1455 const EnumType *ET = Ty->getAs<EnumType>();
1456 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1457 ET && !ET->getDecl()->isFixed();
1458 if (!IsBool && !IsRegularCPlusPlusEnum)
1462 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1463 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1465 const EnumDecl *ED = ET->getDecl();
1466 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1467 unsigned Bitwidth = LTy->getScalarSizeInBits();
1468 unsigned NumNegativeBits = ED->getNumNegativeBits();
1469 unsigned NumPositiveBits = ED->getNumPositiveBits();
1471 if (NumNegativeBits) {
1472 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1473 assert(NumBits <= Bitwidth);
1474 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1477 assert(NumPositiveBits <= Bitwidth);
1478 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1479 Min = llvm::APInt(Bitwidth, 0);
1485 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1486 llvm::APInt Min, End;
1487 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1488 hasBooleanRepresentation(Ty)))
1491 llvm::MDBuilder MDHelper(getLLVMContext());
1492 return MDHelper.createRange(Min, End);
1495 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1496 SourceLocation Loc) {
1497 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1498 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1499 if (!HasBoolCheck && !HasEnumCheck)
1502 bool IsBool = hasBooleanRepresentation(Ty) ||
1503 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1504 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1505 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1506 if (!NeedsBoolCheck && !NeedsEnumCheck)
1509 // Single-bit booleans don't need to be checked. Special-case this to avoid
1510 // a bit width mismatch when handling bitfield values. This is handled by
1511 // EmitFromMemory for the non-bitfield case.
1513 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1516 llvm::APInt Min, End;
1517 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1520 auto &Ctx = getLLVMContext();
1521 SanitizerScope SanScope(this);
1525 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1527 llvm::Value *Upper =
1528 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1529 llvm::Value *Lower =
1530 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1531 Check = Builder.CreateAnd(Upper, Lower);
1533 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1534 EmitCheckTypeDescriptor(Ty)};
1535 SanitizerMask Kind =
1536 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1537 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1538 StaticArgs, EmitCheckValue(Value));
1542 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1545 LValueBaseInfo BaseInfo,
1546 TBAAAccessInfo TBAAInfo,
1547 bool isNontemporal) {
1548 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1549 // For better performance, handle vector loads differently.
1550 if (Ty->isVectorType()) {
1551 const llvm::Type *EltTy = Addr.getElementType();
1553 const auto *VTy = cast<llvm::VectorType>(EltTy);
1555 // Handle vectors of size 3 like size 4 for better performance.
1556 if (VTy->getNumElements() == 3) {
1558 // Bitcast to vec4 type.
1559 llvm::VectorType *vec4Ty =
1560 llvm::VectorType::get(VTy->getElementType(), 4);
1561 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1563 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1565 // Shuffle vector to get vec3.
1566 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1567 {0, 1, 2}, "extractVec");
1568 return EmitFromMemory(V, Ty);
1573 // Atomic operations have to be done on integral types.
1574 LValue AtomicLValue =
1575 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1576 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1577 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1580 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1581 if (isNontemporal) {
1582 llvm::MDNode *Node = llvm::MDNode::get(
1583 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1584 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1587 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1589 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1590 // In order to prevent the optimizer from throwing away the check, don't
1591 // attach range metadata to the load.
1592 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1593 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1594 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1596 return EmitFromMemory(Load, Ty);
1599 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1600 // Bool has a different representation in memory than in registers.
1601 if (hasBooleanRepresentation(Ty)) {
1602 // This should really always be an i1, but sometimes it's already
1603 // an i8, and it's awkward to track those cases down.
1604 if (Value->getType()->isIntegerTy(1))
1605 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1606 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1607 "wrong value rep of bool");
1613 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1614 // Bool has a different representation in memory than in registers.
1615 if (hasBooleanRepresentation(Ty)) {
1616 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1617 "wrong value rep of bool");
1618 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1624 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1625 bool Volatile, QualType Ty,
1626 LValueBaseInfo BaseInfo,
1627 TBAAAccessInfo TBAAInfo,
1628 bool isInit, bool isNontemporal) {
1629 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1630 // Handle vectors differently to get better performance.
1631 if (Ty->isVectorType()) {
1632 llvm::Type *SrcTy = Value->getType();
1633 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1634 // Handle vec3 special.
1635 if (VecTy && VecTy->getNumElements() == 3) {
1636 // Our source is a vec3, do a shuffle vector to make it a vec4.
1637 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1638 Builder.getInt32(2),
1639 llvm::UndefValue::get(Builder.getInt32Ty())};
1640 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1641 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1642 MaskV, "extractVec");
1643 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1645 if (Addr.getElementType() != SrcTy) {
1646 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1651 Value = EmitToMemory(Value, Ty);
1653 LValue AtomicLValue =
1654 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1655 if (Ty->isAtomicType() ||
1656 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1657 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1661 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1662 if (isNontemporal) {
1663 llvm::MDNode *Node =
1664 llvm::MDNode::get(Store->getContext(),
1665 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1666 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1669 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1672 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1674 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1675 lvalue.getType(), lvalue.getBaseInfo(),
1676 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1679 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1680 /// method emits the address of the lvalue, then loads the result as an rvalue,
1681 /// returning the rvalue.
1682 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1683 if (LV.isObjCWeak()) {
1684 // load of a __weak object.
1685 Address AddrWeakObj = LV.getAddress();
1686 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1689 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1690 // In MRC mode, we do a load+autorelease.
1691 if (!getLangOpts().ObjCAutoRefCount) {
1692 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1695 // In ARC mode, we load retained and then consume the value.
1696 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1697 Object = EmitObjCConsumeObject(LV.getType(), Object);
1698 return RValue::get(Object);
1701 if (LV.isSimple()) {
1702 assert(!LV.getType()->isFunctionType());
1704 // Everything needs a load.
1705 return RValue::get(EmitLoadOfScalar(LV, Loc));
1708 if (LV.isVectorElt()) {
1709 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1710 LV.isVolatileQualified());
1711 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1715 // If this is a reference to a subset of the elements of a vector, either
1716 // shuffle the input or extract/insert them as appropriate.
1717 if (LV.isExtVectorElt())
1718 return EmitLoadOfExtVectorElementLValue(LV);
1720 // Global Register variables always invoke intrinsics
1721 if (LV.isGlobalReg())
1722 return EmitLoadOfGlobalRegLValue(LV);
1724 assert(LV.isBitField() && "Unknown LValue type!");
1725 return EmitLoadOfBitfieldLValue(LV, Loc);
1728 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1729 SourceLocation Loc) {
1730 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1732 // Get the output type.
1733 llvm::Type *ResLTy = ConvertType(LV.getType());
1735 Address Ptr = LV.getBitFieldAddress();
1736 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1738 if (Info.IsSigned) {
1739 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1740 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1742 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1743 if (Info.Offset + HighBits)
1744 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1747 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1748 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1749 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1753 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1754 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1755 return RValue::get(Val);
1758 // If this is a reference to a subset of the elements of a vector, create an
1759 // appropriate shufflevector.
1760 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1761 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1762 LV.isVolatileQualified());
1764 const llvm::Constant *Elts = LV.getExtVectorElts();
1766 // If the result of the expression is a non-vector type, we must be extracting
1767 // a single element. Just codegen as an extractelement.
1768 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1770 unsigned InIdx = getAccessedFieldNo(0, Elts);
1771 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1772 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1775 // Always use shuffle vector to try to retain the original program structure
1776 unsigned NumResultElts = ExprVT->getNumElements();
1778 SmallVector<llvm::Constant*, 4> Mask;
1779 for (unsigned i = 0; i != NumResultElts; ++i)
1780 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1782 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1783 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1785 return RValue::get(Vec);
1788 /// @brief Generates lvalue for partial ext_vector access.
1789 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1790 Address VectorAddress = LV.getExtVectorAddress();
1791 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1792 QualType EQT = ExprVT->getElementType();
1793 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1795 Address CastToPointerElement =
1796 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1797 "conv.ptr.element");
1799 const llvm::Constant *Elts = LV.getExtVectorElts();
1800 unsigned ix = getAccessedFieldNo(0, Elts);
1802 Address VectorBasePtrPlusIx =
1803 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1804 getContext().getTypeSizeInChars(EQT),
1807 return VectorBasePtrPlusIx;
1810 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1811 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1812 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1813 "Bad type for register variable");
1814 llvm::MDNode *RegName = cast<llvm::MDNode>(
1815 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1817 // We accept integer and pointer types only
1818 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1819 llvm::Type *Ty = OrigTy;
1820 if (OrigTy->isPointerTy())
1821 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1822 llvm::Type *Types[] = { Ty };
1824 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1825 llvm::Value *Call = Builder.CreateCall(
1826 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1827 if (OrigTy->isPointerTy())
1828 Call = Builder.CreateIntToPtr(Call, OrigTy);
1829 return RValue::get(Call);
1833 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1834 /// lvalue, where both are guaranteed to the have the same type, and that type
1836 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1838 if (!Dst.isSimple()) {
1839 if (Dst.isVectorElt()) {
1840 // Read/modify/write the vector, inserting the new element.
1841 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1842 Dst.isVolatileQualified());
1843 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1844 Dst.getVectorIdx(), "vecins");
1845 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1846 Dst.isVolatileQualified());
1850 // If this is an update of extended vector elements, insert them as
1852 if (Dst.isExtVectorElt())
1853 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1855 if (Dst.isGlobalReg())
1856 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1858 assert(Dst.isBitField() && "Unknown LValue type");
1859 return EmitStoreThroughBitfieldLValue(Src, Dst);
1862 // There's special magic for assigning into an ARC-qualified l-value.
1863 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1865 case Qualifiers::OCL_None:
1866 llvm_unreachable("present but none");
1868 case Qualifiers::OCL_ExplicitNone:
1872 case Qualifiers::OCL_Strong:
1874 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1877 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1880 case Qualifiers::OCL_Weak:
1882 // Initialize and then skip the primitive store.
1883 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1885 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1888 case Qualifiers::OCL_Autoreleasing:
1889 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1890 Src.getScalarVal()));
1891 // fall into the normal path
1896 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1897 // load of a __weak object.
1898 Address LvalueDst = Dst.getAddress();
1899 llvm::Value *src = Src.getScalarVal();
1900 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1904 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1905 // load of a __strong object.
1906 Address LvalueDst = Dst.getAddress();
1907 llvm::Value *src = Src.getScalarVal();
1908 if (Dst.isObjCIvar()) {
1909 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1910 llvm::Type *ResultType = IntPtrTy;
1911 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1912 llvm::Value *RHS = dst.getPointer();
1913 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1915 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1916 "sub.ptr.lhs.cast");
1917 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1918 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1920 } else if (Dst.isGlobalObjCRef()) {
1921 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1922 Dst.isThreadLocalRef());
1925 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1929 assert(Src.isScalar() && "Can't emit an agg store with this method");
1930 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1933 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1934 llvm::Value **Result) {
1935 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1936 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1937 Address Ptr = Dst.getBitFieldAddress();
1939 // Get the source value, truncated to the width of the bit-field.
1940 llvm::Value *SrcVal = Src.getScalarVal();
1942 // Cast the source to the storage type and shift it into place.
1943 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1944 /*IsSigned=*/false);
1945 llvm::Value *MaskedVal = SrcVal;
1947 // See if there are other bits in the bitfield's storage we'll need to load
1948 // and mask together with source before storing.
1949 if (Info.StorageSize != Info.Size) {
1950 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1952 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1954 // Mask the source value as needed.
1955 if (!hasBooleanRepresentation(Dst.getType()))
1956 SrcVal = Builder.CreateAnd(SrcVal,
1957 llvm::APInt::getLowBitsSet(Info.StorageSize,
1962 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1964 // Mask out the original value.
1965 Val = Builder.CreateAnd(Val,
1966 ~llvm::APInt::getBitsSet(Info.StorageSize,
1968 Info.Offset + Info.Size),
1971 // Or together the unchanged values and the source value.
1972 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1974 assert(Info.Offset == 0);
1977 // Write the new value back out.
1978 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1980 // Return the new value of the bit-field, if requested.
1982 llvm::Value *ResultVal = MaskedVal;
1984 // Sign extend the value if needed.
1985 if (Info.IsSigned) {
1986 assert(Info.Size <= Info.StorageSize);
1987 unsigned HighBits = Info.StorageSize - Info.Size;
1989 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1990 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1994 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1996 *Result = EmitFromMemory(ResultVal, Dst.getType());
2000 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2002 // This access turns into a read/modify/write of the vector. Load the input
2004 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2005 Dst.isVolatileQualified());
2006 const llvm::Constant *Elts = Dst.getExtVectorElts();
2008 llvm::Value *SrcVal = Src.getScalarVal();
2010 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2011 unsigned NumSrcElts = VTy->getNumElements();
2012 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
2013 if (NumDstElts == NumSrcElts) {
2014 // Use shuffle vector is the src and destination are the same number of
2015 // elements and restore the vector mask since it is on the side it will be
2017 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
2018 for (unsigned i = 0; i != NumSrcElts; ++i)
2019 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
2021 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2022 Vec = Builder.CreateShuffleVector(SrcVal,
2023 llvm::UndefValue::get(Vec->getType()),
2025 } else if (NumDstElts > NumSrcElts) {
2026 // Extended the source vector to the same length and then shuffle it
2027 // into the destination.
2028 // FIXME: since we're shuffling with undef, can we just use the indices
2029 // into that? This could be simpler.
2030 SmallVector<llvm::Constant*, 4> ExtMask;
2031 for (unsigned i = 0; i != NumSrcElts; ++i)
2032 ExtMask.push_back(Builder.getInt32(i));
2033 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
2034 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
2035 llvm::Value *ExtSrcVal =
2036 Builder.CreateShuffleVector(SrcVal,
2037 llvm::UndefValue::get(SrcVal->getType()),
2040 SmallVector<llvm::Constant*, 4> Mask;
2041 for (unsigned i = 0; i != NumDstElts; ++i)
2042 Mask.push_back(Builder.getInt32(i));
2044 // When the vector size is odd and .odd or .hi is used, the last element
2045 // of the Elts constant array will be one past the size of the vector.
2046 // Ignore the last element here, if it is greater than the mask size.
2047 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2050 // modify when what gets shuffled in
2051 for (unsigned i = 0; i != NumSrcElts; ++i)
2052 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
2053 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
2054 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
2056 // We should never shorten the vector
2057 llvm_unreachable("unexpected shorten vector length");
2060 // If the Src is a scalar (not a vector) it must be updating one element.
2061 unsigned InIdx = getAccessedFieldNo(0, Elts);
2062 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2063 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2066 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2067 Dst.isVolatileQualified());
2070 /// @brief Store of global named registers are always calls to intrinsics.
2071 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2072 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2073 "Bad type for register variable");
2074 llvm::MDNode *RegName = cast<llvm::MDNode>(
2075 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2076 assert(RegName && "Register LValue is not metadata");
2078 // We accept integer and pointer types only
2079 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2080 llvm::Type *Ty = OrigTy;
2081 if (OrigTy->isPointerTy())
2082 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2083 llvm::Type *Types[] = { Ty };
2085 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2086 llvm::Value *Value = Src.getScalarVal();
2087 if (OrigTy->isPointerTy())
2088 Value = Builder.CreatePtrToInt(Value, Ty);
2090 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2093 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2094 // generating write-barries API. It is currently a global, ivar,
2096 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2098 bool IsMemberAccess=false) {
2099 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2102 if (isa<ObjCIvarRefExpr>(E)) {
2103 QualType ExpTy = E->getType();
2104 if (IsMemberAccess && ExpTy->isPointerType()) {
2105 // If ivar is a structure pointer, assigning to field of
2106 // this struct follows gcc's behavior and makes it a non-ivar
2107 // writer-barrier conservatively.
2108 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2109 if (ExpTy->isRecordType()) {
2110 LV.setObjCIvar(false);
2114 LV.setObjCIvar(true);
2115 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2116 LV.setBaseIvarExp(Exp->getBase());
2117 LV.setObjCArray(E->getType()->isArrayType());
2121 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2122 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2123 if (VD->hasGlobalStorage()) {
2124 LV.setGlobalObjCRef(true);
2125 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2128 LV.setObjCArray(E->getType()->isArrayType());
2132 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2133 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2137 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2138 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2139 if (LV.isObjCIvar()) {
2140 // If cast is to a structure pointer, follow gcc's behavior and make it
2141 // a non-ivar write-barrier.
2142 QualType ExpTy = E->getType();
2143 if (ExpTy->isPointerType())
2144 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2145 if (ExpTy->isRecordType())
2146 LV.setObjCIvar(false);
2151 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2152 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2156 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2157 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2161 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2162 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2166 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2167 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2171 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2172 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2173 if (LV.isObjCIvar() && !LV.isObjCArray())
2174 // Using array syntax to assigning to what an ivar points to is not
2175 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2176 LV.setObjCIvar(false);
2177 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2178 // Using array syntax to assigning to what global points to is not
2179 // same as assigning to the global itself. {id *G;} G[i] = 0;
2180 LV.setGlobalObjCRef(false);
2184 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2185 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2186 // We don't know if member is an 'ivar', but this flag is looked at
2187 // only in the context of LV.isObjCIvar().
2188 LV.setObjCArray(E->getType()->isArrayType());
2193 static llvm::Value *
2194 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2195 llvm::Value *V, llvm::Type *IRType,
2196 StringRef Name = StringRef()) {
2197 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2198 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2201 static LValue EmitThreadPrivateVarDeclLValue(
2202 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2203 llvm::Type *RealVarTy, SourceLocation Loc) {
2204 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2205 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2206 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2210 CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2211 LValueBaseInfo *PointeeBaseInfo,
2212 TBAAAccessInfo *PointeeTBAAInfo) {
2213 llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2214 RefLVal.isVolatile());
2215 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2217 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2218 PointeeBaseInfo, PointeeTBAAInfo,
2219 /* forPointeeType= */ true);
2220 return Address(Load, Align);
2223 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2224 LValueBaseInfo PointeeBaseInfo;
2225 TBAAAccessInfo PointeeTBAAInfo;
2226 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2228 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2229 PointeeBaseInfo, PointeeTBAAInfo);
2232 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2233 const PointerType *PtrTy,
2234 LValueBaseInfo *BaseInfo,
2235 TBAAAccessInfo *TBAAInfo) {
2236 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2237 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2239 /*forPointeeType=*/true));
2242 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2243 const PointerType *PtrTy) {
2244 LValueBaseInfo BaseInfo;
2245 TBAAAccessInfo TBAAInfo;
2246 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2247 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2250 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2251 const Expr *E, const VarDecl *VD) {
2252 QualType T = E->getType();
2254 // If it's thread_local, emit a call to its wrapper function instead.
2255 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2256 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2257 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2259 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2260 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2261 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2262 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2263 Address Addr(V, Alignment);
2264 // Emit reference to the private copy of the variable if it is an OpenMP
2265 // threadprivate variable.
2266 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2267 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2269 LValue LV = VD->getType()->isReferenceType() ?
2270 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2271 AlignmentSource::Decl) :
2272 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2273 setObjCGCLValueClass(CGF.getContext(), E, LV);
2277 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2278 const FunctionDecl *FD) {
2279 if (FD->hasAttr<WeakRefAttr>()) {
2280 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2281 return aliasee.getPointer();
2284 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2285 if (!FD->hasPrototype()) {
2286 if (const FunctionProtoType *Proto =
2287 FD->getType()->getAs<FunctionProtoType>()) {
2288 // Ugly case: for a K&R-style definition, the type of the definition
2289 // isn't the same as the type of a use. Correct for this with a
2291 QualType NoProtoType =
2292 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2293 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2294 V = llvm::ConstantExpr::getBitCast(V,
2295 CGM.getTypes().ConvertType(NoProtoType));
2301 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2302 const Expr *E, const FunctionDecl *FD) {
2303 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2304 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2305 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2306 AlignmentSource::Decl);
2309 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2310 llvm::Value *ThisValue) {
2311 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2312 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2313 return CGF.EmitLValueForField(LV, FD);
2316 /// Named Registers are named metadata pointing to the register name
2317 /// which will be read from/written to as an argument to the intrinsic
2318 /// @llvm.read/write_register.
2319 /// So far, only the name is being passed down, but other options such as
2320 /// register type, allocation type or even optimization options could be
2321 /// passed down via the metadata node.
2322 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2323 SmallString<64> Name("llvm.named.register.");
2324 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2325 assert(Asm->getLabel().size() < 64-Name.size() &&
2326 "Register name too big");
2327 Name.append(Asm->getLabel());
2328 llvm::NamedMDNode *M =
2329 CGM.getModule().getOrInsertNamedMetadata(Name);
2330 if (M->getNumOperands() == 0) {
2331 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2333 llvm::Metadata *Ops[] = {Str};
2334 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2337 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2340 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2341 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2344 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2345 const NamedDecl *ND = E->getDecl();
2346 QualType T = E->getType();
2348 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2349 // Global Named registers access via intrinsics only
2350 if (VD->getStorageClass() == SC_Register &&
2351 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2352 return EmitGlobalNamedRegister(VD, CGM);
2354 // A DeclRefExpr for a reference initialized by a constant expression can
2355 // appear without being odr-used. Directly emit the constant initializer.
2356 const Expr *Init = VD->getAnyInitializer(VD);
2357 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2358 VD->isUsableInConstantExpressions(getContext()) &&
2359 VD->checkInitIsICE() &&
2360 // Do not emit if it is private OpenMP variable.
2361 !(E->refersToEnclosingVariableOrCapture() &&
2362 ((CapturedStmtInfo &&
2363 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2364 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2365 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2366 isa<BlockDecl>(CurCodeDecl)))) {
2367 llvm::Constant *Val =
2368 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2369 *VD->evaluateValue(),
2371 assert(Val && "failed to emit reference constant expression");
2372 // FIXME: Eventually we will want to emit vector element references.
2374 // Should we be using the alignment of the constant pointer we emitted?
2375 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2376 /* BaseInfo= */ nullptr,
2377 /* TBAAInfo= */ nullptr,
2378 /* forPointeeType= */ true);
2379 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2382 // Check for captured variables.
2383 if (E->refersToEnclosingVariableOrCapture()) {
2384 VD = VD->getCanonicalDecl();
2385 if (auto *FD = LambdaCaptureFields.lookup(VD))
2386 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2387 else if (CapturedStmtInfo) {
2388 auto I = LocalDeclMap.find(VD);
2389 if (I != LocalDeclMap.end()) {
2390 if (VD->getType()->isReferenceType())
2391 return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2392 AlignmentSource::Decl);
2393 return MakeAddrLValue(I->second, T);
2396 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2397 CapturedStmtInfo->getContextValue());
2398 return MakeAddrLValue(
2399 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2400 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2401 CapLVal.getTBAAInfo());
2404 assert(isa<BlockDecl>(CurCodeDecl));
2405 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2406 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2410 // FIXME: We should be able to assert this for FunctionDecls as well!
2411 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2412 // those with a valid source location.
2413 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2414 !E->getLocation().isValid()) &&
2415 "Should not use decl without marking it used!");
2417 if (ND->hasAttr<WeakRefAttr>()) {
2418 const auto *VD = cast<ValueDecl>(ND);
2419 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2420 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2423 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2424 // Check if this is a global variable.
2425 if (VD->hasLinkage() || VD->isStaticDataMember())
2426 return EmitGlobalVarDeclLValue(*this, E, VD);
2428 Address addr = Address::invalid();
2430 // The variable should generally be present in the local decl map.
2431 auto iter = LocalDeclMap.find(VD);
2432 if (iter != LocalDeclMap.end()) {
2433 addr = iter->second;
2435 // Otherwise, it might be static local we haven't emitted yet for
2436 // some reason; most likely, because it's in an outer function.
2437 } else if (VD->isStaticLocal()) {
2438 addr = Address(CGM.getOrCreateStaticVarDecl(
2439 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2440 getContext().getDeclAlign(VD));
2442 // No other cases for now.
2444 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2448 // Check for OpenMP threadprivate variables.
2449 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2450 return EmitThreadPrivateVarDeclLValue(
2451 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2455 // Drill into block byref variables.
2456 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2458 addr = emitBlockByrefAddress(addr, VD);
2461 // Drill into reference types.
2462 LValue LV = VD->getType()->isReferenceType() ?
2463 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2464 MakeAddrLValue(addr, T, AlignmentSource::Decl);
2466 bool isLocalStorage = VD->hasLocalStorage();
2468 bool NonGCable = isLocalStorage &&
2469 !VD->getType()->isReferenceType() &&
2472 LV.getQuals().removeObjCGCAttr();
2476 bool isImpreciseLifetime =
2477 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2478 if (isImpreciseLifetime)
2479 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2480 setObjCGCLValueClass(getContext(), E, LV);
2484 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2485 return EmitFunctionDeclLValue(*this, E, FD);
2487 // FIXME: While we're emitting a binding from an enclosing scope, all other
2488 // DeclRefExprs we see should be implicitly treated as if they also refer to
2489 // an enclosing scope.
2490 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2491 return EmitLValue(BD->getBinding());
2493 llvm_unreachable("Unhandled DeclRefExpr");
2496 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2497 // __extension__ doesn't affect lvalue-ness.
2498 if (E->getOpcode() == UO_Extension)
2499 return EmitLValue(E->getSubExpr());
2501 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2502 switch (E->getOpcode()) {
2503 default: llvm_unreachable("Unknown unary operator lvalue!");
2505 QualType T = E->getSubExpr()->getType()->getPointeeType();
2506 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2508 LValueBaseInfo BaseInfo;
2509 TBAAAccessInfo TBAAInfo;
2510 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2512 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2513 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2515 // We should not generate __weak write barrier on indirect reference
2516 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2517 // But, we continue to generate __strong write barrier on indirect write
2518 // into a pointer to object.
2519 if (getLangOpts().ObjC1 &&
2520 getLangOpts().getGC() != LangOptions::NonGC &&
2522 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2527 LValue LV = EmitLValue(E->getSubExpr());
2528 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2530 // __real is valid on scalars. This is a faster way of testing that.
2531 // __imag can only produce an rvalue on scalars.
2532 if (E->getOpcode() == UO_Real &&
2533 !LV.getAddress().getElementType()->isStructTy()) {
2534 assert(E->getSubExpr()->getType()->isArithmeticType());
2538 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2541 (E->getOpcode() == UO_Real
2542 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2543 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2544 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2545 CGM.getTBAAInfoForSubobject(LV, T));
2546 ElemLV.getQuals().addQualifiers(LV.getQuals());
2551 LValue LV = EmitLValue(E->getSubExpr());
2552 bool isInc = E->getOpcode() == UO_PreInc;
2554 if (E->getType()->isAnyComplexType())
2555 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2557 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2563 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2564 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2565 E->getType(), AlignmentSource::Decl);
2568 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2569 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2570 E->getType(), AlignmentSource::Decl);
2573 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2574 auto SL = E->getFunctionName();
2575 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2576 StringRef FnName = CurFn->getName();
2577 if (FnName.startswith("\01"))
2578 FnName = FnName.substr(1);
2579 StringRef NameItems[] = {
2580 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2581 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2582 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2583 std::string Name = SL->getString();
2584 if (!Name.empty()) {
2585 unsigned Discriminator =
2586 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2588 Name += "_" + Twine(Discriminator + 1).str();
2589 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2590 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2592 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2593 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2596 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2597 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2600 /// Emit a type description suitable for use by a runtime sanitizer library. The
2601 /// format of a type descriptor is
2604 /// { i16 TypeKind, i16 TypeInfo }
2607 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2608 /// integer, 1 for a floating point value, and -1 for anything else.
2609 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2610 // Only emit each type's descriptor once.
2611 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2614 uint16_t TypeKind = -1;
2615 uint16_t TypeInfo = 0;
2617 if (T->isIntegerType()) {
2619 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2620 (T->isSignedIntegerType() ? 1 : 0);
2621 } else if (T->isFloatingType()) {
2623 TypeInfo = getContext().getTypeSize(T);
2626 // Format the type name as if for a diagnostic, including quotes and
2627 // optionally an 'aka'.
2628 SmallString<32> Buffer;
2629 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2630 (intptr_t)T.getAsOpaquePtr(),
2631 StringRef(), StringRef(), None, Buffer,
2634 llvm::Constant *Components[] = {
2635 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2636 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2638 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2640 auto *GV = new llvm::GlobalVariable(
2641 CGM.getModule(), Descriptor->getType(),
2642 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2643 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2644 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2646 // Remember the descriptor for this type.
2647 CGM.setTypeDescriptorInMap(T, GV);
2652 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2653 llvm::Type *TargetTy = IntPtrTy;
2655 if (V->getType() == TargetTy)
2658 // Floating-point types which fit into intptr_t are bitcast to integers
2659 // and then passed directly (after zero-extension, if necessary).
2660 if (V->getType()->isFloatingPointTy()) {
2661 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2662 if (Bits <= TargetTy->getIntegerBitWidth())
2663 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2667 // Integers which fit in intptr_t are zero-extended and passed directly.
2668 if (V->getType()->isIntegerTy() &&
2669 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2670 return Builder.CreateZExt(V, TargetTy);
2672 // Pointers are passed directly, everything else is passed by address.
2673 if (!V->getType()->isPointerTy()) {
2674 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2675 Builder.CreateStore(V, Ptr);
2676 V = Ptr.getPointer();
2678 return Builder.CreatePtrToInt(V, TargetTy);
2681 /// \brief Emit a representation of a SourceLocation for passing to a handler
2682 /// in a sanitizer runtime library. The format for this data is:
2684 /// struct SourceLocation {
2685 /// const char *Filename;
2686 /// int32_t Line, Column;
2689 /// For an invalid SourceLocation, the Filename pointer is null.
2690 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2691 llvm::Constant *Filename;
2694 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2695 if (PLoc.isValid()) {
2696 StringRef FilenameString = PLoc.getFilename();
2698 int PathComponentsToStrip =
2699 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2700 if (PathComponentsToStrip < 0) {
2701 assert(PathComponentsToStrip != INT_MIN);
2702 int PathComponentsToKeep = -PathComponentsToStrip;
2703 auto I = llvm::sys::path::rbegin(FilenameString);
2704 auto E = llvm::sys::path::rend(FilenameString);
2705 while (I != E && --PathComponentsToKeep)
2708 FilenameString = FilenameString.substr(I - E);
2709 } else if (PathComponentsToStrip > 0) {
2710 auto I = llvm::sys::path::begin(FilenameString);
2711 auto E = llvm::sys::path::end(FilenameString);
2712 while (I != E && PathComponentsToStrip--)
2717 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2719 FilenameString = llvm::sys::path::filename(FilenameString);
2722 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2723 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2724 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2725 Filename = FilenameGV.getPointer();
2726 Line = PLoc.getLine();
2727 Column = PLoc.getColumn();
2729 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2733 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2734 Builder.getInt32(Column)};
2736 return llvm::ConstantStruct::getAnon(Data);
2740 /// \brief Specify under what conditions this check can be recovered
2741 enum class CheckRecoverableKind {
2742 /// Always terminate program execution if this check fails.
2744 /// Check supports recovering, runtime has both fatal (noreturn) and
2745 /// non-fatal handlers for this check.
2747 /// Runtime conditionally aborts, always need to support recovery.
2752 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2753 assert(llvm::countPopulation(Kind) == 1);
2755 case SanitizerKind::Vptr:
2756 return CheckRecoverableKind::AlwaysRecoverable;
2757 case SanitizerKind::Return:
2758 case SanitizerKind::Unreachable:
2759 return CheckRecoverableKind::Unrecoverable;
2761 return CheckRecoverableKind::Recoverable;
2766 struct SanitizerHandlerInfo {
2767 char const *const Name;
2772 const SanitizerHandlerInfo SanitizerHandlers[] = {
2773 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2774 LIST_SANITIZER_CHECKS
2775 #undef SANITIZER_CHECK
2778 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2779 llvm::FunctionType *FnType,
2780 ArrayRef<llvm::Value *> FnArgs,
2781 SanitizerHandler CheckHandler,
2782 CheckRecoverableKind RecoverKind, bool IsFatal,
2783 llvm::BasicBlock *ContBB) {
2784 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2785 bool NeedsAbortSuffix =
2786 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2787 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
2788 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2789 const StringRef CheckName = CheckInfo.Name;
2790 std::string FnName = "__ubsan_handle_" + CheckName.str();
2791 if (CheckInfo.Version && !MinimalRuntime)
2792 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2794 FnName += "_minimal";
2795 if (NeedsAbortSuffix)
2798 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2800 llvm::AttrBuilder B;
2802 B.addAttribute(llvm::Attribute::NoReturn)
2803 .addAttribute(llvm::Attribute::NoUnwind);
2805 B.addAttribute(llvm::Attribute::UWTable);
2807 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2809 llvm::AttributeList::get(CGF.getLLVMContext(),
2810 llvm::AttributeList::FunctionIndex, B),
2812 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2814 HandlerCall->setDoesNotReturn();
2815 CGF.Builder.CreateUnreachable();
2817 CGF.Builder.CreateBr(ContBB);
2821 void CodeGenFunction::EmitCheck(
2822 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2823 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2824 ArrayRef<llvm::Value *> DynamicArgs) {
2825 assert(IsSanitizerScope);
2826 assert(Checked.size() > 0);
2827 assert(CheckHandler >= 0 &&
2828 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
2829 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2831 llvm::Value *FatalCond = nullptr;
2832 llvm::Value *RecoverableCond = nullptr;
2833 llvm::Value *TrapCond = nullptr;
2834 for (int i = 0, n = Checked.size(); i < n; ++i) {
2835 llvm::Value *Check = Checked[i].first;
2836 // -fsanitize-trap= overrides -fsanitize-recover=.
2837 llvm::Value *&Cond =
2838 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2840 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2843 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2847 EmitTrapCheck(TrapCond);
2848 if (!FatalCond && !RecoverableCond)
2851 llvm::Value *JointCond;
2852 if (FatalCond && RecoverableCond)
2853 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2855 JointCond = FatalCond ? FatalCond : RecoverableCond;
2858 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2859 assert(SanOpts.has(Checked[0].second));
2861 for (int i = 1, n = Checked.size(); i < n; ++i) {
2862 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2863 "All recoverable kinds in a single check must be same!");
2864 assert(SanOpts.has(Checked[i].second));
2868 llvm::BasicBlock *Cont = createBasicBlock("cont");
2869 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2870 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2871 // Give hint that we very much don't expect to execute the handler
2872 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2873 llvm::MDBuilder MDHelper(getLLVMContext());
2874 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2875 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2876 EmitBlock(Handlers);
2878 // Handler functions take an i8* pointing to the (handler-specific) static
2879 // information block, followed by a sequence of intptr_t arguments
2880 // representing operand values.
2881 SmallVector<llvm::Value *, 4> Args;
2882 SmallVector<llvm::Type *, 4> ArgTypes;
2883 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2884 Args.reserve(DynamicArgs.size() + 1);
2885 ArgTypes.reserve(DynamicArgs.size() + 1);
2887 // Emit handler arguments and create handler function type.
2888 if (!StaticArgs.empty()) {
2889 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2891 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2892 llvm::GlobalVariable::PrivateLinkage, Info);
2893 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2894 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2895 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2896 ArgTypes.push_back(Int8PtrTy);
2899 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2900 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2901 ArgTypes.push_back(IntPtrTy);
2905 llvm::FunctionType *FnType =
2906 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2908 if (!FatalCond || !RecoverableCond) {
2909 // Simple case: we need to generate a single handler call, either
2910 // fatal, or non-fatal.
2911 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2912 (FatalCond != nullptr), Cont);
2914 // Emit two handler calls: first one for set of unrecoverable checks,
2915 // another one for recoverable.
2916 llvm::BasicBlock *NonFatalHandlerBB =
2917 createBasicBlock("non_fatal." + CheckName);
2918 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2919 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2920 EmitBlock(FatalHandlerBB);
2921 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2923 EmitBlock(NonFatalHandlerBB);
2924 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2931 void CodeGenFunction::EmitCfiSlowPathCheck(
2932 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2933 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2934 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2936 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2937 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2939 llvm::MDBuilder MDHelper(getLLVMContext());
2940 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2941 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2945 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2947 llvm::CallInst *CheckCall;
2949 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2951 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2952 llvm::GlobalVariable::PrivateLinkage, Info);
2953 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2954 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2956 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2957 "__cfi_slowpath_diag",
2958 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2960 CheckCall = Builder.CreateCall(
2962 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2964 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2966 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2967 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2970 CheckCall->setDoesNotThrow();
2975 // Emit a stub for __cfi_check function so that the linker knows about this
2976 // symbol in LTO mode.
2977 void CodeGenFunction::EmitCfiCheckStub() {
2978 llvm::Module *M = &CGM.getModule();
2979 auto &Ctx = M->getContext();
2980 llvm::Function *F = llvm::Function::Create(
2981 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2982 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2983 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2984 // FIXME: consider emitting an intrinsic call like
2985 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2986 // which can be lowered in CrossDSOCFI pass to the actual contents of
2987 // __cfi_check. This would allow inlining of __cfi_check calls.
2988 llvm::CallInst::Create(
2989 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2990 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2993 // This function is basically a switch over the CFI failure kind, which is
2994 // extracted from CFICheckFailData (1st function argument). Each case is either
2995 // llvm.trap or a call to one of the two runtime handlers, based on
2996 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2997 // failure kind) traps, but this should really never happen. CFICheckFailData
2998 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2999 // check kind; in this case __cfi_check_fail traps as well.
3000 void CodeGenFunction::EmitCfiCheckFail() {
3001 SanitizerScope SanScope(this);
3002 FunctionArgList Args;
3003 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3004 ImplicitParamDecl::Other);
3005 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3006 ImplicitParamDecl::Other);
3007 Args.push_back(&ArgData);
3008 Args.push_back(&ArgAddr);
3010 const CGFunctionInfo &FI =
3011 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3013 llvm::Function *F = llvm::Function::Create(
3014 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3015 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3016 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3018 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3022 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3023 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3025 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3026 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3028 // Data == nullptr means the calling module has trap behaviour for this check.
3029 llvm::Value *DataIsNotNullPtr =
3030 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3031 EmitTrapCheck(DataIsNotNullPtr);
3033 llvm::StructType *SourceLocationTy =
3034 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3035 llvm::StructType *CfiCheckFailDataTy =
3036 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3038 llvm::Value *V = Builder.CreateConstGEP2_32(
3040 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3042 Address CheckKindAddr(V, getIntAlign());
3043 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3045 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3046 CGM.getLLVMContext(),
3047 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3048 llvm::Value *ValidVtable = Builder.CreateZExt(
3049 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3050 {Addr, AllVtables}),
3053 const std::pair<int, SanitizerMask> CheckKinds[] = {
3054 {CFITCK_VCall, SanitizerKind::CFIVCall},
3055 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3056 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3057 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3058 {CFITCK_ICall, SanitizerKind::CFIICall}};
3060 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3061 for (auto CheckKindMaskPair : CheckKinds) {
3062 int Kind = CheckKindMaskPair.first;
3063 SanitizerMask Mask = CheckKindMaskPair.second;
3065 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3066 if (CGM.getLangOpts().Sanitize.has(Mask))
3067 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3068 {Data, Addr, ValidVtable});
3070 EmitTrapCheck(Cond);
3074 // The only reference to this function will be created during LTO link.
3075 // Make sure it survives until then.
3076 CGM.addUsedGlobal(F);
3079 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
3080 llvm::BasicBlock *Cont = createBasicBlock("cont");
3082 // If we're optimizing, collapse all calls to trap down to just one per
3083 // function to save on code size.
3084 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3085 TrapBB = createBasicBlock("trap");
3086 Builder.CreateCondBr(Checked, Cont, TrapBB);
3088 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3089 TrapCall->setDoesNotReturn();
3090 TrapCall->setDoesNotThrow();
3091 Builder.CreateUnreachable();
3093 Builder.CreateCondBr(Checked, Cont, TrapBB);
3099 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3100 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3102 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3103 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3104 CGM.getCodeGenOpts().TrapFuncName);
3105 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3111 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3112 LValueBaseInfo *BaseInfo,
3113 TBAAAccessInfo *TBAAInfo) {
3114 assert(E->getType()->isArrayType() &&
3115 "Array to pointer decay must have array source type!");
3117 // Expressions of array type can't be bitfields or vector elements.
3118 LValue LV = EmitLValue(E);
3119 Address Addr = LV.getAddress();
3121 // If the array type was an incomplete type, we need to make sure
3122 // the decay ends up being the right type.
3123 llvm::Type *NewTy = ConvertType(E->getType());
3124 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3126 // Note that VLA pointers are always decayed, so we don't need to do
3128 if (!E->getType()->isVariableArrayType()) {
3129 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3130 "Expected pointer to array");
3131 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3134 // The result of this decay conversion points to an array element within the
3135 // base lvalue. However, since TBAA currently does not support representing
3136 // accesses to elements of member arrays, we conservatively represent accesses
3137 // to the pointee object as if it had no any base lvalue specified.
3138 // TODO: Support TBAA for member arrays.
3139 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3140 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3141 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3143 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3146 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3147 /// array to pointer, return the array subexpression.
3148 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3149 // If this isn't just an array->pointer decay, bail out.
3150 const auto *CE = dyn_cast<CastExpr>(E);
3151 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3154 // If this is a decay from variable width array, bail out.
3155 const Expr *SubExpr = CE->getSubExpr();
3156 if (SubExpr->getType()->isVariableArrayType())
3162 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3164 ArrayRef<llvm::Value*> indices,
3168 const llvm::Twine &name = "arrayidx") {
3170 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3171 CodeGenFunction::NotSubtraction, loc,
3174 return CGF.Builder.CreateGEP(ptr, indices, name);
3178 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3180 CharUnits eltSize) {
3181 // If we have a constant index, we can use the exact offset of the
3182 // element we're accessing.
3183 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3184 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3185 return arrayAlign.alignmentAtOffset(offset);
3187 // Otherwise, use the worst-case alignment for any element.
3189 return arrayAlign.alignmentOfArrayElement(eltSize);
3193 static QualType getFixedSizeElementType(const ASTContext &ctx,
3194 const VariableArrayType *vla) {
3197 eltType = vla->getElementType();
3198 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3202 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3203 ArrayRef<llvm::Value *> indices,
3204 QualType eltType, bool inbounds,
3205 bool signedIndices, SourceLocation loc,
3206 const llvm::Twine &name = "arrayidx") {
3207 // All the indices except that last must be zero.
3209 for (auto idx : indices.drop_back())
3210 assert(isa<llvm::ConstantInt>(idx) &&
3211 cast<llvm::ConstantInt>(idx)->isZero());
3214 // Determine the element size of the statically-sized base. This is
3215 // the thing that the indices are expressed in terms of.
3216 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3217 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3220 // We can use that to compute the best alignment of the element.
3221 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3222 CharUnits eltAlign =
3223 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3225 llvm::Value *eltPtr = emitArraySubscriptGEP(
3226 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
3227 return Address(eltPtr, eltAlign);
3230 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3232 // The index must always be an integer, which is not an aggregate. Emit it
3233 // in lexical order (this complexity is, sadly, required by C++17).
3234 llvm::Value *IdxPre =
3235 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3236 bool SignedIndices = false;
3237 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3239 if (E->getLHS() != E->getIdx()) {
3240 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3241 Idx = EmitScalarExpr(E->getIdx());
3244 QualType IdxTy = E->getIdx()->getType();
3245 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3246 SignedIndices |= IdxSigned;
3248 if (SanOpts.has(SanitizerKind::ArrayBounds))
3249 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3251 // Extend or truncate the index type to 32 or 64-bits.
3252 if (Promote && Idx->getType() != IntPtrTy)
3253 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3259 // If the base is a vector type, then we are forming a vector element lvalue
3260 // with this subscript.
3261 if (E->getBase()->getType()->isVectorType() &&
3262 !isa<ExtVectorElementExpr>(E->getBase())) {
3263 // Emit the vector as an lvalue to get its address.
3264 LValue LHS = EmitLValue(E->getBase());
3265 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3266 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3267 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3268 LHS.getBaseInfo(), TBAAAccessInfo());
3271 // All the other cases basically behave like simple offsetting.
3273 // Handle the extvector case we ignored above.
3274 if (isa<ExtVectorElementExpr>(E->getBase())) {
3275 LValue LV = EmitLValue(E->getBase());
3276 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3277 Address Addr = EmitExtVectorElementLValue(LV);
3279 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3280 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3281 SignedIndices, E->getExprLoc());
3282 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3283 CGM.getTBAAInfoForSubobject(LV, EltType));
3286 LValueBaseInfo EltBaseInfo;
3287 TBAAAccessInfo EltTBAAInfo;
3288 Address Addr = Address::invalid();
3289 if (const VariableArrayType *vla =
3290 getContext().getAsVariableArrayType(E->getType())) {
3291 // The base must be a pointer, which is not an aggregate. Emit
3292 // it. It needs to be emitted first in case it's what captures
3294 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3295 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3297 // The element count here is the total number of non-VLA elements.
3298 llvm::Value *numElements = getVLASize(vla).first;
3300 // Effectively, the multiply by the VLA size is part of the GEP.
3301 // GEP indexes are signed, and scaling an index isn't permitted to
3302 // signed-overflow, so we use the same semantics for our explicit
3303 // multiply. We suppress this if overflow is not undefined behavior.
3304 if (getLangOpts().isSignedOverflowDefined()) {
3305 Idx = Builder.CreateMul(Idx, numElements);
3307 Idx = Builder.CreateNSWMul(Idx, numElements);
3310 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3311 !getLangOpts().isSignedOverflowDefined(),
3312 SignedIndices, E->getExprLoc());
3314 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3315 // Indexing over an interface, as in "NSString *P; P[4];"
3317 // Emit the base pointer.
3318 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3319 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3321 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3322 llvm::Value *InterfaceSizeVal =
3323 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3325 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3327 // We don't necessarily build correct LLVM struct types for ObjC
3328 // interfaces, so we can't rely on GEP to do this scaling
3329 // correctly, so we need to cast to i8*. FIXME: is this actually
3330 // true? A lot of other things in the fragile ABI would break...
3331 llvm::Type *OrigBaseTy = Addr.getType();
3332 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3335 CharUnits EltAlign =
3336 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3337 llvm::Value *EltPtr =
3338 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3339 SignedIndices, E->getExprLoc());
3340 Addr = Address(EltPtr, EltAlign);
3343 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3344 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3345 // If this is A[i] where A is an array, the frontend will have decayed the
3346 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3347 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3348 // "gep x, i" here. Emit one "gep A, 0, i".
3349 assert(Array->getType()->isArrayType() &&
3350 "Array to pointer decay must have array source type!");
3352 // For simple multidimensional array indexing, set the 'accessed' flag for
3353 // better bounds-checking of the base expression.
3354 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3355 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3357 ArrayLV = EmitLValue(Array);
3358 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3360 // Propagate the alignment from the array itself to the result.
3361 Addr = emitArraySubscriptGEP(
3362 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3363 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3365 EltBaseInfo = ArrayLV.getBaseInfo();
3366 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3368 // The base must be a pointer; emit it with an estimate of its alignment.
3369 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3370 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3371 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3372 !getLangOpts().isSignedOverflowDefined(),
3373 SignedIndices, E->getExprLoc());
3376 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3378 if (getLangOpts().ObjC1 &&
3379 getLangOpts().getGC() != LangOptions::NonGC) {
3380 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3381 setObjCGCLValueClass(getContext(), E, LV);
3386 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3387 LValueBaseInfo &BaseInfo,
3388 TBAAAccessInfo &TBAAInfo,
3389 QualType BaseTy, QualType ElTy,
3390 bool IsLowerBound) {
3392 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3393 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3394 if (BaseTy->isArrayType()) {
3395 Address Addr = BaseLVal.getAddress();
3396 BaseInfo = BaseLVal.getBaseInfo();
3398 // If the array type was an incomplete type, we need to make sure
3399 // the decay ends up being the right type.
3400 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3401 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3403 // Note that VLA pointers are always decayed, so we don't need to do
3405 if (!BaseTy->isVariableArrayType()) {
3406 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3407 "Expected pointer to array");
3408 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3412 return CGF.Builder.CreateElementBitCast(Addr,
3413 CGF.ConvertTypeForMem(ElTy));
3415 LValueBaseInfo TypeBaseInfo;
3416 TBAAAccessInfo TypeTBAAInfo;
3417 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3419 BaseInfo.mergeForCast(TypeBaseInfo);
3420 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3421 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3423 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3426 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3427 bool IsLowerBound) {
3428 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
3429 QualType ResultExprTy;
3430 if (auto *AT = getContext().getAsArrayType(BaseTy))
3431 ResultExprTy = AT->getElementType();
3433 ResultExprTy = BaseTy->getPointeeType();
3434 llvm::Value *Idx = nullptr;
3435 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3436 // Requesting lower bound or upper bound, but without provided length and
3437 // without ':' symbol for the default length -> length = 1.
3438 // Idx = LowerBound ?: 0;
3439 if (auto *LowerBound = E->getLowerBound()) {
3440 Idx = Builder.CreateIntCast(
3441 EmitScalarExpr(LowerBound), IntPtrTy,
3442 LowerBound->getType()->hasSignedIntegerRepresentation());
3444 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3446 // Try to emit length or lower bound as constant. If this is possible, 1
3447 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3448 // IR (LB + Len) - 1.
3449 auto &C = CGM.getContext();
3450 auto *Length = E->getLength();
3451 llvm::APSInt ConstLength;
3453 // Idx = LowerBound + Length - 1;
3454 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3455 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3458 auto *LowerBound = E->getLowerBound();
3459 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3460 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3461 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3462 LowerBound = nullptr;
3466 else if (!LowerBound)
3469 if (Length || LowerBound) {
3470 auto *LowerBoundVal =
3472 ? Builder.CreateIntCast(
3473 EmitScalarExpr(LowerBound), IntPtrTy,
3474 LowerBound->getType()->hasSignedIntegerRepresentation())
3475 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3478 ? Builder.CreateIntCast(
3479 EmitScalarExpr(Length), IntPtrTy,
3480 Length->getType()->hasSignedIntegerRepresentation())
3481 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3482 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3484 !getLangOpts().isSignedOverflowDefined());
3485 if (Length && LowerBound) {
3486 Idx = Builder.CreateSub(
3487 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3488 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3491 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3493 // Idx = ArraySize - 1;
3494 QualType ArrayTy = BaseTy->isPointerType()
3495 ? E->getBase()->IgnoreParenImpCasts()->getType()
3497 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3498 Length = VAT->getSizeExpr();
3499 if (Length->isIntegerConstantExpr(ConstLength, C))
3502 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3503 ConstLength = CAT->getSize();
3506 auto *LengthVal = Builder.CreateIntCast(
3507 EmitScalarExpr(Length), IntPtrTy,
3508 Length->getType()->hasSignedIntegerRepresentation());
3509 Idx = Builder.CreateSub(
3510 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3511 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3513 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3515 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3521 Address EltPtr = Address::invalid();
3522 LValueBaseInfo BaseInfo;
3523 TBAAAccessInfo TBAAInfo;
3524 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3525 // The base must be a pointer, which is not an aggregate. Emit
3526 // it. It needs to be emitted first in case it's what captures
3529 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3530 BaseTy, VLA->getElementType(), IsLowerBound);
3531 // The element count here is the total number of non-VLA elements.
3532 llvm::Value *NumElements = getVLASize(VLA).first;
3534 // Effectively, the multiply by the VLA size is part of the GEP.
3535 // GEP indexes are signed, and scaling an index isn't permitted to
3536 // signed-overflow, so we use the same semantics for our explicit
3537 // multiply. We suppress this if overflow is not undefined behavior.
3538 if (getLangOpts().isSignedOverflowDefined())
3539 Idx = Builder.CreateMul(Idx, NumElements);
3541 Idx = Builder.CreateNSWMul(Idx, NumElements);
3542 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3543 !getLangOpts().isSignedOverflowDefined(),
3544 /*SignedIndices=*/false, E->getExprLoc());
3545 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3546 // If this is A[i] where A is an array, the frontend will have decayed the
3547 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3548 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3549 // "gep x, i" here. Emit one "gep A, 0, i".
3550 assert(Array->getType()->isArrayType() &&
3551 "Array to pointer decay must have array source type!");
3553 // For simple multidimensional array indexing, set the 'accessed' flag for
3554 // better bounds-checking of the base expression.
3555 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3556 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3558 ArrayLV = EmitLValue(Array);
3560 // Propagate the alignment from the array itself to the result.
3561 EltPtr = emitArraySubscriptGEP(
3562 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3563 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3564 /*SignedIndices=*/false, E->getExprLoc());
3565 BaseInfo = ArrayLV.getBaseInfo();
3566 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
3568 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3569 TBAAInfo, BaseTy, ResultExprTy,
3571 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3572 !getLangOpts().isSignedOverflowDefined(),
3573 /*SignedIndices=*/false, E->getExprLoc());
3576 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
3579 LValue CodeGenFunction::
3580 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3581 // Emit the base vector as an l-value.
3584 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3586 // If it is a pointer to a vector, emit the address and form an lvalue with
3588 LValueBaseInfo BaseInfo;
3589 TBAAAccessInfo TBAAInfo;
3590 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
3591 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3592 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
3593 Base.getQuals().removeObjCGCAttr();
3594 } else if (E->getBase()->isGLValue()) {
3595 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3596 // emit the base as an lvalue.
3597 assert(E->getBase()->getType()->isVectorType());
3598 Base = EmitLValue(E->getBase());
3600 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3601 assert(E->getBase()->getType()->isVectorType() &&
3602 "Result must be a vector");
3603 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3605 // Store the vector to memory (because LValue wants an address).
3606 Address VecMem = CreateMemTemp(E->getBase()->getType());
3607 Builder.CreateStore(Vec, VecMem);
3608 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3609 AlignmentSource::Decl);
3613 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3615 // Encode the element access list into a vector of unsigned indices.
3616 SmallVector<uint32_t, 4> Indices;
3617 E->getEncodedElementAccess(Indices);
3619 if (Base.isSimple()) {
3620 llvm::Constant *CV =
3621 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3622 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3623 Base.getBaseInfo(), TBAAAccessInfo());
3625 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3627 llvm::Constant *BaseElts = Base.getExtVectorElts();
3628 SmallVector<llvm::Constant *, 4> CElts;
3630 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3631 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3632 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3633 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3634 Base.getBaseInfo(), TBAAAccessInfo());
3637 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3638 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3639 EmitIgnoredExpr(E->getBase());
3640 return EmitDeclRefLValue(DRE);
3643 Expr *BaseExpr = E->getBase();
3644 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3647 LValueBaseInfo BaseInfo;
3648 TBAAAccessInfo TBAAInfo;
3649 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
3650 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3651 SanitizerSet SkippedChecks;
3652 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3654 SkippedChecks.set(SanitizerKind::Alignment, true);
3655 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3656 SkippedChecks.set(SanitizerKind::Null, true);
3657 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3658 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3659 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
3661 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3663 NamedDecl *ND = E->getMemberDecl();
3664 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3665 LValue LV = EmitLValueForField(BaseLV, Field);
3666 setObjCGCLValueClass(getContext(), E, LV);
3670 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3671 return EmitFunctionDeclLValue(*this, E, FD);
3673 llvm_unreachable("Unhandled member declaration!");
3676 /// Given that we are currently emitting a lambda, emit an l-value for
3677 /// one of its members.
3678 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3679 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3680 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3681 QualType LambdaTagType =
3682 getContext().getTagDeclType(Field->getParent());
3683 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3684 return EmitLValueForField(LambdaLV, Field);
3687 /// Drill down to the storage of a field without walking into
3688 /// reference types.
3690 /// The resulting address doesn't necessarily have the right type.
3691 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3692 const FieldDecl *field) {
3693 const RecordDecl *rec = field->getParent();
3696 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3699 // Adjust the alignment down to the given offset.
3700 // As a special case, if the LLVM field index is 0, we know that this
3702 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3703 .getFieldOffset(field->getFieldIndex()) == 0) &&
3704 "LLVM field at index zero had non-zero offset?");
3706 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3707 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3708 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3711 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3714 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3715 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3719 if (RD->isDynamicClass())
3722 for (const auto &Base : RD->bases())
3723 if (hasAnyVptr(Base.getType(), Context))
3726 for (const FieldDecl *Field : RD->fields())
3727 if (hasAnyVptr(Field->getType(), Context))
3733 LValue CodeGenFunction::EmitLValueForField(LValue base,
3734 const FieldDecl *field) {
3735 LValueBaseInfo BaseInfo = base.getBaseInfo();
3737 if (field->isBitField()) {
3738 const CGRecordLayout &RL =
3739 CGM.getTypes().getCGRecordLayout(field->getParent());
3740 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3741 Address Addr = base.getAddress();
3742 unsigned Idx = RL.getLLVMFieldNo(field);
3744 // For structs, we GEP to the field that the record layout suggests.
3745 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3747 // Get the access type.
3748 llvm::Type *FieldIntTy =
3749 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3750 if (Addr.getElementType() != FieldIntTy)
3751 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3753 QualType fieldType =
3754 field->getType().withCVRQualifiers(base.getVRQualifiers());
3755 // TODO: Support TBAA for bit fields.
3756 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
3757 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3761 // Fields of may-alias structures are may-alias themselves.
3762 // FIXME: this should get propagated down through anonymous structs
3764 QualType FieldType = field->getType();
3765 const RecordDecl *rec = field->getParent();
3766 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
3767 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
3768 TBAAAccessInfo FieldTBAAInfo;
3769 if (base.getTBAAInfo().isMayAlias() ||
3770 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
3771 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3772 } else if (rec->isUnion()) {
3773 // TODO: Support TBAA for unions.
3774 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
3776 // If no base type been assigned for the base access, then try to generate
3777 // one for this base lvalue.
3778 FieldTBAAInfo = base.getTBAAInfo();
3779 if (!FieldTBAAInfo.BaseType) {
3780 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3781 assert(!FieldTBAAInfo.Offset &&
3782 "Nonzero offset for an access with no base type!");
3785 // Adjust offset to be relative to the base type.
3786 const ASTRecordLayout &Layout =
3787 getContext().getASTRecordLayout(field->getParent());
3788 unsigned CharWidth = getContext().getCharWidth();
3789 if (FieldTBAAInfo.BaseType)
3790 FieldTBAAInfo.Offset +=
3791 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3793 // Update the final access type.
3794 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
3797 Address addr = base.getAddress();
3798 unsigned RecordCVR = base.getVRQualifiers();
3799 if (rec->isUnion()) {
3800 // For unions, there is no pointer adjustment.
3801 assert(!FieldType->isReferenceType() && "union has reference member");
3802 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3803 hasAnyVptr(FieldType, getContext()))
3804 // Because unions can easily skip invariant.barriers, we need to add
3805 // a barrier every time CXXRecord field with vptr is referenced.
3806 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3807 addr.getAlignment());
3809 // For structs, we GEP to the field that the record layout suggests.
3810 addr = emitAddrOfFieldStorage(*this, addr, field);
3812 // If this is a reference field, load the reference right now.
3813 if (FieldType->isReferenceType()) {
3814 LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3816 if (RecordCVR & Qualifiers::Volatile)
3817 RefLVal.getQuals().setVolatile(true);
3818 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
3820 // Qualifiers on the struct don't apply to the referencee.
3822 FieldType = FieldType->getPointeeType();
3826 // Make sure that the address is pointing to the right type. This is critical
3827 // for both unions and structs. A union needs a bitcast, a struct element
3828 // will need a bitcast if the LLVM type laid out doesn't match the desired
3830 addr = Builder.CreateElementBitCast(
3831 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
3833 if (field->hasAttr<AnnotateAttr>())
3834 addr = EmitFieldAnnotations(field, addr);
3836 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
3837 LV.getQuals().addCVRQualifiers(RecordCVR);
3839 // __weak attribute on a field is ignored.
3840 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3841 LV.getQuals().removeObjCGCAttr();
3847 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3848 const FieldDecl *Field) {
3849 QualType FieldType = Field->getType();
3851 if (!FieldType->isReferenceType())
3852 return EmitLValueForField(Base, Field);
3854 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3856 // Make sure that the address is pointing to the right type.
3857 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3858 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3860 // TODO: Generate TBAA information that describes this access as a structure
3861 // member access and not just an access to an object of the field's type. This
3862 // should be similar to what we do in EmitLValueForField().
3863 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3864 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
3865 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
3866 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
3867 CGM.getTBAAInfoForSubobject(Base, FieldType));
3870 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3871 if (E->isFileScope()) {
3872 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3873 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3875 if (E->getType()->isVariablyModifiedType())
3876 // make sure to emit the VLA size.
3877 EmitVariablyModifiedType(E->getType());
3879 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3880 const Expr *InitExpr = E->getInitializer();
3881 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3883 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3889 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3890 if (!E->isGLValue())
3891 // Initializing an aggregate temporary in C++11: T{...}.
3892 return EmitAggExprToLValue(E);
3894 // An lvalue initializer list must be initializing a reference.
3895 assert(E->isTransparent() && "non-transparent glvalue init list");
3896 return EmitLValue(E->getInit(0));
3899 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3900 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3901 /// LValue is returned and the current block has been terminated.
3902 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3903 const Expr *Operand) {
3904 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3905 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3909 return CGF.EmitLValue(Operand);
3912 LValue CodeGenFunction::
3913 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3914 if (!expr->isGLValue()) {
3915 // ?: here should be an aggregate.
3916 assert(hasAggregateEvaluationKind(expr->getType()) &&
3917 "Unexpected conditional operator!");
3918 return EmitAggExprToLValue(expr);
3921 OpaqueValueMapping binding(*this, expr);
3923 const Expr *condExpr = expr->getCond();
3925 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3926 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3927 if (!CondExprBool) std::swap(live, dead);
3929 if (!ContainsLabel(dead)) {
3930 // If the true case is live, we need to track its region.
3932 incrementProfileCounter(expr);
3933 return EmitLValue(live);
3937 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3938 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3939 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3941 ConditionalEvaluation eval(*this);
3942 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3944 // Any temporaries created here are conditional.
3945 EmitBlock(lhsBlock);
3946 incrementProfileCounter(expr);
3948 Optional<LValue> lhs =
3949 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3952 if (lhs && !lhs->isSimple())
3953 return EmitUnsupportedLValue(expr, "conditional operator");
3955 lhsBlock = Builder.GetInsertBlock();
3957 Builder.CreateBr(contBlock);
3959 // Any temporaries created here are conditional.
3960 EmitBlock(rhsBlock);
3962 Optional<LValue> rhs =
3963 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3965 if (rhs && !rhs->isSimple())
3966 return EmitUnsupportedLValue(expr, "conditional operator");
3967 rhsBlock = Builder.GetInsertBlock();
3969 EmitBlock(contBlock);
3972 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3974 phi->addIncoming(lhs->getPointer(), lhsBlock);
3975 phi->addIncoming(rhs->getPointer(), rhsBlock);
3976 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3977 AlignmentSource alignSource =
3978 std::max(lhs->getBaseInfo().getAlignmentSource(),
3979 rhs->getBaseInfo().getAlignmentSource());
3980 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
3981 lhs->getTBAAInfo(), rhs->getTBAAInfo());
3982 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
3985 assert((lhs || rhs) &&
3986 "both operands of glvalue conditional are throw-expressions?");
3987 return lhs ? *lhs : *rhs;
3991 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3992 /// type. If the cast is to a reference, we can have the usual lvalue result,
3993 /// otherwise if a cast is needed by the code generator in an lvalue context,
3994 /// then it must mean that we need the address of an aggregate in order to
3995 /// access one of its members. This can happen for all the reasons that casts
3996 /// are permitted with aggregate result, including noop aggregate casts, and
3997 /// cast from scalar to union.
3998 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3999 switch (E->getCastKind()) {
4002 case CK_ArrayToPointerDecay:
4003 case CK_FunctionToPointerDecay:
4004 case CK_NullToMemberPointer:
4005 case CK_NullToPointer:
4006 case CK_IntegralToPointer:
4007 case CK_PointerToIntegral:
4008 case CK_PointerToBoolean:
4009 case CK_VectorSplat:
4010 case CK_IntegralCast:
4011 case CK_BooleanToSignedIntegral:
4012 case CK_IntegralToBoolean:
4013 case CK_IntegralToFloating:
4014 case CK_FloatingToIntegral:
4015 case CK_FloatingToBoolean:
4016 case CK_FloatingCast:
4017 case CK_FloatingRealToComplex:
4018 case CK_FloatingComplexToReal:
4019 case CK_FloatingComplexToBoolean:
4020 case CK_FloatingComplexCast:
4021 case CK_FloatingComplexToIntegralComplex:
4022 case CK_IntegralRealToComplex:
4023 case CK_IntegralComplexToReal:
4024 case CK_IntegralComplexToBoolean:
4025 case CK_IntegralComplexCast:
4026 case CK_IntegralComplexToFloatingComplex:
4027 case CK_DerivedToBaseMemberPointer:
4028 case CK_BaseToDerivedMemberPointer:
4029 case CK_MemberPointerToBoolean:
4030 case CK_ReinterpretMemberPointer:
4031 case CK_AnyPointerToBlockPointerCast:
4032 case CK_ARCProduceObject:
4033 case CK_ARCConsumeObject:
4034 case CK_ARCReclaimReturnedObject:
4035 case CK_ARCExtendBlockObject:
4036 case CK_CopyAndAutoreleaseBlockObject:
4037 case CK_AddressSpaceConversion:
4038 case CK_IntToOCLSampler:
4039 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4042 llvm_unreachable("dependent cast kind in IR gen!");
4044 case CK_BuiltinFnToFnPtr:
4045 llvm_unreachable("builtin functions are handled elsewhere");
4047 // These are never l-values; just use the aggregate emission code.
4048 case CK_NonAtomicToAtomic:
4049 case CK_AtomicToNonAtomic:
4050 return EmitAggExprToLValue(E);
4053 LValue LV = EmitLValue(E->getSubExpr());
4054 Address V = LV.getAddress();
4055 const auto *DCE = cast<CXXDynamicCastExpr>(E);
4056 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4059 case CK_ConstructorConversion:
4060 case CK_UserDefinedConversion:
4061 case CK_CPointerToObjCPointerCast:
4062 case CK_BlockPointerToObjCPointerCast:
4064 case CK_LValueToRValue:
4065 return EmitLValue(E->getSubExpr());
4067 case CK_UncheckedDerivedToBase:
4068 case CK_DerivedToBase: {
4069 const RecordType *DerivedClassTy =
4070 E->getSubExpr()->getType()->getAs<RecordType>();
4071 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4073 LValue LV = EmitLValue(E->getSubExpr());
4074 Address This = LV.getAddress();
4076 // Perform the derived-to-base conversion
4077 Address Base = GetAddressOfBaseClass(
4078 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4079 /*NullCheckValue=*/false, E->getExprLoc());
4081 // TODO: Support accesses to members of base classes in TBAA. For now, we
4082 // conservatively pretend that the complete object is of the base class
4084 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4085 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4088 return EmitAggExprToLValue(E);
4089 case CK_BaseToDerived: {
4090 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
4091 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4093 LValue LV = EmitLValue(E->getSubExpr());
4095 // Perform the base-to-derived conversion
4097 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
4098 E->path_begin(), E->path_end(),
4099 /*NullCheckValue=*/false);
4101 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4102 // performed and the object is not of the derived type.
4103 if (sanitizePerformTypeCheck())
4104 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4105 Derived.getPointer(), E->getType());
4107 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4108 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4109 /*MayBeNull=*/false,
4110 CFITCK_DerivedCast, E->getLocStart());
4112 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4113 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4115 case CK_LValueBitCast: {
4116 // This must be a reinterpret_cast (or c-style equivalent).
4117 const auto *CE = cast<ExplicitCastExpr>(E);
4119 CGM.EmitExplicitCastExprType(CE, this);
4120 LValue LV = EmitLValue(E->getSubExpr());
4121 Address V = Builder.CreateBitCast(LV.getAddress(),
4122 ConvertType(CE->getTypeAsWritten()));
4124 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4125 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4126 /*MayBeNull=*/false,
4127 CFITCK_UnrelatedCast, E->getLocStart());
4129 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4130 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4132 case CK_ObjCObjectLValueCast: {
4133 LValue LV = EmitLValue(E->getSubExpr());
4134 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4135 ConvertType(E->getType()));
4136 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4137 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4139 case CK_ZeroToOCLQueue:
4140 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4141 case CK_ZeroToOCLEvent:
4142 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4145 llvm_unreachable("Unhandled lvalue cast kind?");
4148 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4149 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4150 return getOpaqueLValueMapping(e);
4153 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4154 const FieldDecl *FD,
4155 SourceLocation Loc) {
4156 QualType FT = FD->getType();
4157 LValue FieldLV = EmitLValueForField(LV, FD);
4158 switch (getEvaluationKind(FT)) {
4160 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4162 return FieldLV.asAggregateRValue();
4164 // This routine is used to load fields one-by-one to perform a copy, so
4165 // don't load reference fields.
4166 if (FD->getType()->isReferenceType())
4167 return RValue::get(FieldLV.getPointer());
4168 return EmitLoadOfLValue(FieldLV, Loc);
4170 llvm_unreachable("bad evaluation kind");
4173 //===--------------------------------------------------------------------===//
4174 // Expression Emission
4175 //===--------------------------------------------------------------------===//
4177 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4178 ReturnValueSlot ReturnValue) {
4179 // Builtins never have block type.
4180 if (E->getCallee()->getType()->isBlockPointerType())
4181 return EmitBlockCallExpr(E, ReturnValue);
4183 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4184 return EmitCXXMemberCallExpr(CE, ReturnValue);
4186 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4187 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4189 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4190 if (const CXXMethodDecl *MD =
4191 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4192 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4194 CGCallee callee = EmitCallee(E->getCallee());
4196 if (callee.isBuiltin()) {
4197 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4201 if (callee.isPseudoDestructor()) {
4202 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4205 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4208 /// Emit a CallExpr without considering whether it might be a subclass.
4209 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4210 ReturnValueSlot ReturnValue) {
4211 CGCallee Callee = EmitCallee(E->getCallee());
4212 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4215 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4216 if (auto builtinID = FD->getBuiltinID()) {
4217 return CGCallee::forBuiltin(builtinID, FD);
4220 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4221 return CGCallee::forDirect(calleePtr, FD);
4224 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4225 E = E->IgnoreParens();
4227 // Look through function-to-pointer decay.
4228 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4229 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4230 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4231 return EmitCallee(ICE->getSubExpr());
4234 // Resolve direct calls.
4235 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4236 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4237 return EmitDirectCallee(*this, FD);
4239 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4240 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4241 EmitIgnoredExpr(ME->getBase());
4242 return EmitDirectCallee(*this, FD);
4245 // Look through template substitutions.
4246 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4247 return EmitCallee(NTTP->getReplacement());
4249 // Treat pseudo-destructor calls differently.
4250 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4251 return CGCallee::forPseudoDestructor(PDE);
4254 // Otherwise, we have an indirect reference.
4255 llvm::Value *calleePtr;
4256 QualType functionType;
4257 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4258 calleePtr = EmitScalarExpr(E);
4259 functionType = ptrType->getPointeeType();
4261 functionType = E->getType();
4262 calleePtr = EmitLValue(E).getPointer();
4264 assert(functionType->isFunctionType());
4265 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4266 E->getReferencedDeclOfCallee());
4267 CGCallee callee(calleeInfo, calleePtr);
4271 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4272 // Comma expressions just emit their LHS then their RHS as an l-value.
4273 if (E->getOpcode() == BO_Comma) {
4274 EmitIgnoredExpr(E->getLHS());
4275 EnsureInsertPoint();
4276 return EmitLValue(E->getRHS());
4279 if (E->getOpcode() == BO_PtrMemD ||
4280 E->getOpcode() == BO_PtrMemI)
4281 return EmitPointerToDataMemberBinaryExpr(E);
4283 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4285 // Note that in all of these cases, __block variables need the RHS
4286 // evaluated first just in case the variable gets moved by the RHS.
4288 switch (getEvaluationKind(E->getType())) {
4290 switch (E->getLHS()->getType().getObjCLifetime()) {
4291 case Qualifiers::OCL_Strong:
4292 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4294 case Qualifiers::OCL_Autoreleasing:
4295 return EmitARCStoreAutoreleasing(E).first;
4297 // No reason to do any of these differently.
4298 case Qualifiers::OCL_None:
4299 case Qualifiers::OCL_ExplicitNone:
4300 case Qualifiers::OCL_Weak:
4304 RValue RV = EmitAnyExpr(E->getRHS());
4305 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4307 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4308 EmitStoreThroughLValue(RV, LV);
4313 return EmitComplexAssignmentLValue(E);
4316 return EmitAggExprToLValue(E);
4318 llvm_unreachable("bad evaluation kind");
4321 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4322 RValue RV = EmitCallExpr(E);
4325 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4326 AlignmentSource::Decl);
4328 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4329 "Can't have a scalar return unless the return type is a "
4332 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4335 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4336 // FIXME: This shouldn't require another copy.
4337 return EmitAggExprToLValue(E);
4340 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4341 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4342 && "binding l-value to type which needs a temporary");
4343 AggValueSlot Slot = CreateAggTemp(E->getType());
4344 EmitCXXConstructExpr(E, Slot);
4345 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4349 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4350 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4353 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4354 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4355 ConvertType(E->getType()));
4358 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4359 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4360 AlignmentSource::Decl);
4364 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4365 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4366 Slot.setExternallyDestructed();
4367 EmitAggExpr(E->getSubExpr(), Slot);
4368 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4369 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4373 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4374 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4375 EmitLambdaExpr(E, Slot);
4376 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
4379 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4380 RValue RV = EmitObjCMessageExpr(E);
4383 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4384 AlignmentSource::Decl);
4386 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4387 "Can't have a scalar return unless the return type is a "
4390 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4393 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4395 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4396 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4399 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4400 const ObjCIvarDecl *Ivar) {
4401 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4404 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4405 llvm::Value *BaseValue,
4406 const ObjCIvarDecl *Ivar,
4407 unsigned CVRQualifiers) {
4408 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4409 Ivar, CVRQualifiers);
4412 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4413 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4414 llvm::Value *BaseValue = nullptr;
4415 const Expr *BaseExpr = E->getBase();
4416 Qualifiers BaseQuals;
4419 BaseValue = EmitScalarExpr(BaseExpr);
4420 ObjectTy = BaseExpr->getType()->getPointeeType();
4421 BaseQuals = ObjectTy.getQualifiers();
4423 LValue BaseLV = EmitLValue(BaseExpr);
4424 BaseValue = BaseLV.getPointer();
4425 ObjectTy = BaseExpr->getType();
4426 BaseQuals = ObjectTy.getQualifiers();
4430 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4431 BaseQuals.getCVRQualifiers());
4432 setObjCGCLValueClass(getContext(), E, LV);
4436 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4437 // Can only get l-value for message expression returning aggregate type
4438 RValue RV = EmitAnyExprToTemp(E);
4439 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4440 AlignmentSource::Decl);
4443 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4444 const CallExpr *E, ReturnValueSlot ReturnValue,
4445 llvm::Value *Chain) {
4446 // Get the actual function type. The callee type will always be a pointer to
4447 // function type or a block pointer type.
4448 assert(CalleeType->isFunctionPointerType() &&
4449 "Call must have function pointer type!");
4451 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4453 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4454 // We can only guarantee that a function is called from the correct
4455 // context/function based on the appropriate target attributes,
4456 // so only check in the case where we have both always_inline and target
4457 // since otherwise we could be making a conditional call after a check for
4458 // the proper cpu features (and it won't cause code generation issues due to
4459 // function based code generation).
4460 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4461 TargetDecl->hasAttr<TargetAttr>())
4462 checkTargetFeatures(E, FD);
4464 CalleeType = getContext().getCanonicalType(CalleeType);
4466 const auto *FnType =
4467 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4469 CGCallee Callee = OrigCallee;
4471 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4472 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4473 if (llvm::Constant *PrefixSig =
4474 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4475 SanitizerScope SanScope(this);
4476 llvm::Constant *FTRTTIConst =
4477 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4478 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
4479 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4480 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4482 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4484 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4485 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4486 llvm::Value *CalleeSigPtr =
4487 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4488 llvm::Value *CalleeSig =
4489 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4490 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4492 llvm::BasicBlock *Cont = createBasicBlock("cont");
4493 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4494 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4496 EmitBlock(TypeCheck);
4497 llvm::Value *CalleeRTTIPtr =
4498 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4499 llvm::Value *CalleeRTTIEncoded =
4500 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4501 llvm::Value *CalleeRTTI =
4502 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
4503 llvm::Value *CalleeRTTIMatch =
4504 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4505 llvm::Constant *StaticData[] = {
4506 EmitCheckSourceLocation(E->getLocStart()),
4507 EmitCheckTypeDescriptor(CalleeType)
4509 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4510 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4512 Builder.CreateBr(Cont);
4517 // If we are checking indirect calls and this call is indirect, check that the
4518 // function pointer is a member of the bit set for the function type.
4519 if (SanOpts.has(SanitizerKind::CFIICall) &&
4520 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4521 SanitizerScope SanScope(this);
4522 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4525 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4526 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
4528 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4530 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4532 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4533 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4534 llvm::Value *TypeTest = Builder.CreateCall(
4535 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4537 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4538 llvm::Constant *StaticData[] = {
4539 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4540 EmitCheckSourceLocation(E->getLocStart()),
4541 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4543 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4544 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4545 CastedCallee, StaticData);
4547 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4548 SanitizerHandler::CFICheckFail, StaticData,
4549 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4555 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4556 CGM.getContext().VoidPtrTy);
4558 // C++17 requires that we evaluate arguments to a call using assignment syntax
4559 // right-to-left, and that we evaluate arguments to certain other operators
4560 // left-to-right. Note that we allow this to override the order dictated by
4561 // the calling convention on the MS ABI, which means that parameter
4562 // destruction order is not necessarily reverse construction order.
4563 // FIXME: Revisit this based on C++ committee response to unimplementability.
4564 EvaluationOrder Order = EvaluationOrder::Default;
4565 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4566 if (OCE->isAssignmentOp())
4567 Order = EvaluationOrder::ForceRightToLeft;
4569 switch (OCE->getOperator()) {
4571 case OO_GreaterGreater:
4576 Order = EvaluationOrder::ForceLeftToRight;
4584 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4585 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4587 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4588 Args, FnType, /*isChainCall=*/Chain);
4591 // If the expression that denotes the called function has a type
4592 // that does not include a prototype, [the default argument
4593 // promotions are performed]. If the number of arguments does not
4594 // equal the number of parameters, the behavior is undefined. If
4595 // the function is defined with a type that includes a prototype,
4596 // and either the prototype ends with an ellipsis (, ...) or the
4597 // types of the arguments after promotion are not compatible with
4598 // the types of the parameters, the behavior is undefined. If the
4599 // function is defined with a type that does not include a
4600 // prototype, and the types of the arguments after promotion are
4601 // not compatible with those of the parameters after promotion,
4602 // the behavior is undefined [except in some trivial cases].
4603 // That is, in the general case, we should assume that a call
4604 // through an unprototyped function type works like a *non-variadic*
4605 // call. The way we make this work is to cast to the exact type
4606 // of the promoted arguments.
4608 // Chain calls use this same code path to add the invisible chain parameter
4609 // to the function type.
4610 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4611 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4612 CalleeTy = CalleeTy->getPointerTo();
4614 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4615 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4616 Callee.setFunctionPointer(CalleePtr);
4619 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4622 LValue CodeGenFunction::
4623 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4624 Address BaseAddr = Address::invalid();
4625 if (E->getOpcode() == BO_PtrMemI) {
4626 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4628 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4631 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4633 const MemberPointerType *MPT
4634 = E->getRHS()->getType()->getAs<MemberPointerType>();
4636 LValueBaseInfo BaseInfo;
4637 TBAAAccessInfo TBAAInfo;
4638 Address MemberAddr =
4639 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4642 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
4645 /// Given the address of a temporary variable, produce an r-value of
4647 RValue CodeGenFunction::convertTempToRValue(Address addr,
4649 SourceLocation loc) {
4650 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4651 switch (getEvaluationKind(type)) {
4653 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4655 return lvalue.asAggregateRValue();
4657 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4659 llvm_unreachable("bad evaluation kind");
4662 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4663 assert(Val->getType()->isFPOrFPVectorTy());
4664 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4667 llvm::MDBuilder MDHelper(getLLVMContext());
4668 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4670 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4674 struct LValueOrRValue {
4680 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4681 const PseudoObjectExpr *E,
4683 AggValueSlot slot) {
4684 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4686 // Find the result expression, if any.
4687 const Expr *resultExpr = E->getResultExpr();
4688 LValueOrRValue result;
4690 for (PseudoObjectExpr::const_semantics_iterator
4691 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4692 const Expr *semantic = *i;
4694 // If this semantic expression is an opaque value, bind it
4695 // to the result of its source expression.
4696 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4698 // If this is the result expression, we may need to evaluate
4699 // directly into the slot.
4700 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4702 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4703 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4704 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4705 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4706 AlignmentSource::Decl);
4707 opaqueData = OVMA::bind(CGF, ov, LV);
4708 result.RV = slot.asRValue();
4710 // Otherwise, emit as normal.
4712 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4714 // If this is the result, also evaluate the result now.
4715 if (ov == resultExpr) {
4717 result.LV = CGF.EmitLValue(ov);
4719 result.RV = CGF.EmitAnyExpr(ov, slot);
4723 opaques.push_back(opaqueData);
4725 // Otherwise, if the expression is the result, evaluate it
4726 // and remember the result.
4727 } else if (semantic == resultExpr) {
4729 result.LV = CGF.EmitLValue(semantic);
4731 result.RV = CGF.EmitAnyExpr(semantic, slot);
4733 // Otherwise, evaluate the expression in an ignored context.
4735 CGF.EmitIgnoredExpr(semantic);
4739 // Unbind all the opaques now.
4740 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4741 opaques[i].unbind(CGF);
4746 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4747 AggValueSlot slot) {
4748 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4751 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4752 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;