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 "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/ADT/Hashing.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/Support/ConvertUTF.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
42 using namespace clang;
43 using namespace CodeGen;
45 //===--------------------------------------------------------------------===//
46 // Miscellaneous Helper Methods
47 //===--------------------------------------------------------------------===//
49 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
53 llvm::PointerType *destType = Int8PtrTy;
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
61 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
63 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
70 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
72 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
74 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
75 nullptr, Name, AllocaInsertPt);
78 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
79 /// default alignment of the corresponding LLVM type, which is *not*
80 /// guaranteed to be related in any way to the expected alignment of
81 /// an AST type that might have been lowered to Ty.
82 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
85 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
86 return CreateTempAlloca(Ty, Align, Name);
89 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
90 assert(isa<llvm::AllocaInst>(Var.getPointer()));
91 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
92 Store->setAlignment(Var.getAlignment().getQuantity());
93 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
94 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
97 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
98 CharUnits Align = getContext().getTypeAlignInChars(Ty);
99 return CreateTempAlloca(ConvertType(Ty), Align, Name);
102 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
103 // FIXME: Should we prefer the preferred type alignment here?
104 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
107 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
109 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
112 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
113 /// expression and compare the result against zero, returning an Int1Ty value.
114 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
115 PGO.setCurrentStmt(E);
116 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
117 llvm::Value *MemPtr = EmitScalarExpr(E);
118 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
121 QualType BoolTy = getContext().BoolTy;
122 SourceLocation Loc = E->getExprLoc();
123 if (!E->getType()->isAnyComplexType())
124 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
126 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
130 /// EmitIgnoredExpr - Emit code to compute the specified expression,
131 /// ignoring the result.
132 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
134 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
136 // Just emit it as an l-value and drop the result.
140 /// EmitAnyExpr - Emit code to compute the specified expression which
141 /// can have any type. The result is returned as an RValue struct.
142 /// If this is an aggregate expression, AggSlot indicates where the
143 /// result should be returned.
144 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
145 AggValueSlot aggSlot,
147 switch (getEvaluationKind(E->getType())) {
149 return RValue::get(EmitScalarExpr(E, ignoreResult));
151 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
153 if (!ignoreResult && aggSlot.isIgnored())
154 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
155 EmitAggExpr(E, aggSlot);
156 return aggSlot.asRValue();
158 llvm_unreachable("bad evaluation kind");
161 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
162 /// always be accessible even if no aggregate location is provided.
163 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
164 AggValueSlot AggSlot = AggValueSlot::ignored();
166 if (hasAggregateEvaluationKind(E->getType()))
167 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
168 return EmitAnyExpr(E, AggSlot);
171 /// EmitAnyExprToMem - Evaluate an expression into a given memory
173 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
177 // FIXME: This function should take an LValue as an argument.
178 switch (getEvaluationKind(E->getType())) {
180 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
184 case TEK_Aggregate: {
185 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
186 AggValueSlot::IsDestructed_t(IsInit),
187 AggValueSlot::DoesNotNeedGCBarriers,
188 AggValueSlot::IsAliased_t(!IsInit)));
193 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
194 LValue LV = MakeAddrLValue(Location, E->getType());
195 EmitStoreThroughLValue(RV, LV);
199 llvm_unreachable("bad evaluation kind");
203 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
204 const Expr *E, Address ReferenceTemporary) {
205 // Objective-C++ ARC:
206 // If we are binding a reference to a temporary that has ownership, we
207 // need to perform retain/release operations on the temporary.
209 // FIXME: This should be looking at E, not M.
210 if (auto Lifetime = M->getType().getObjCLifetime()) {
212 case Qualifiers::OCL_None:
213 case Qualifiers::OCL_ExplicitNone:
214 // Carry on to normal cleanup handling.
217 case Qualifiers::OCL_Autoreleasing:
218 // Nothing to do; cleaned up by an autorelease pool.
221 case Qualifiers::OCL_Strong:
222 case Qualifiers::OCL_Weak:
223 switch (StorageDuration Duration = M->getStorageDuration()) {
225 // Note: we intentionally do not register a cleanup to release
226 // the object on program termination.
230 // FIXME: We should probably register a cleanup in this case.
234 case SD_FullExpression:
235 CodeGenFunction::Destroyer *Destroy;
236 CleanupKind CleanupKind;
237 if (Lifetime == Qualifiers::OCL_Strong) {
238 const ValueDecl *VD = M->getExtendingDecl();
240 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
241 CleanupKind = CGF.getARCCleanupKind();
242 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
243 : &CodeGenFunction::destroyARCStrongImprecise;
245 // __weak objects always get EH cleanups; otherwise, exceptions
246 // could cause really nasty crashes instead of mere leaks.
247 CleanupKind = NormalAndEHCleanup;
248 Destroy = &CodeGenFunction::destroyARCWeak;
250 if (Duration == SD_FullExpression)
251 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
252 M->getType(), *Destroy,
253 CleanupKind & EHCleanup);
255 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
257 *Destroy, CleanupKind & EHCleanup);
261 llvm_unreachable("temporary cannot have dynamic storage duration");
263 llvm_unreachable("unknown storage duration");
267 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
268 if (const RecordType *RT =
269 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
270 // Get the destructor for the reference temporary.
271 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
272 if (!ClassDecl->hasTrivialDestructor())
273 ReferenceTemporaryDtor = ClassDecl->getDestructor();
276 if (!ReferenceTemporaryDtor)
279 // Call the destructor for the temporary.
280 switch (M->getStorageDuration()) {
283 llvm::Constant *CleanupFn;
284 llvm::Constant *CleanupArg;
285 if (E->getType()->isArrayType()) {
286 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
287 ReferenceTemporary, E->getType(),
288 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
289 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
290 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
292 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
293 StructorType::Complete);
294 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
296 CGF.CGM.getCXXABI().registerGlobalDtor(
297 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
301 case SD_FullExpression:
302 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
303 CodeGenFunction::destroyCXXObject,
304 CGF.getLangOpts().Exceptions);
308 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
309 ReferenceTemporary, E->getType(),
310 CodeGenFunction::destroyCXXObject,
311 CGF.getLangOpts().Exceptions);
315 llvm_unreachable("temporary cannot have dynamic storage duration");
320 createReferenceTemporary(CodeGenFunction &CGF,
321 const MaterializeTemporaryExpr *M, const Expr *Inner) {
322 switch (M->getStorageDuration()) {
323 case SD_FullExpression:
325 // If we have a constant temporary array or record try to promote it into a
326 // constant global under the same rules a normal constant would've been
327 // promoted. This is easier on the optimizer and generally emits fewer
329 QualType Ty = Inner->getType();
330 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
331 (Ty->isArrayType() || Ty->isRecordType()) &&
332 CGF.CGM.isTypeConstant(Ty, true))
333 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
334 auto *GV = new llvm::GlobalVariable(
335 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
336 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
337 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
338 GV->setAlignment(alignment.getQuantity());
339 // FIXME: Should we put the new global into a COMDAT?
340 return Address(GV, alignment);
342 return CGF.CreateMemTemp(Ty, "ref.tmp");
346 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
349 llvm_unreachable("temporary can't have dynamic storage duration");
351 llvm_unreachable("unknown storage duration");
354 LValue CodeGenFunction::
355 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
356 const Expr *E = M->GetTemporaryExpr();
358 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
359 // as that will cause the lifetime adjustment to be lost for ARC
360 auto ownership = M->getType().getObjCLifetime();
361 if (ownership != Qualifiers::OCL_None &&
362 ownership != Qualifiers::OCL_ExplicitNone) {
363 Address Object = createReferenceTemporary(*this, M, E);
364 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
365 Object = Address(llvm::ConstantExpr::getBitCast(Var,
366 ConvertTypeForMem(E->getType())
367 ->getPointerTo(Object.getAddressSpace())),
368 Object.getAlignment());
370 // createReferenceTemporary will promote the temporary to a global with a
371 // constant initializer if it can. It can only do this to a value of
372 // ARC-manageable type if the value is global and therefore "immune" to
373 // ref-counting operations. Therefore we have no need to emit either a
374 // dynamic initialization or a cleanup and we can just return the address
376 if (Var->hasInitializer())
377 return MakeAddrLValue(Object, M->getType(),
378 LValueBaseInfo(AlignmentSource::Decl, false));
380 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
382 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
383 LValueBaseInfo(AlignmentSource::Decl,
386 switch (getEvaluationKind(E->getType())) {
387 default: llvm_unreachable("expected scalar or aggregate expression");
389 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
391 case TEK_Aggregate: {
392 EmitAggExpr(E, AggValueSlot::forAddr(Object,
393 E->getType().getQualifiers(),
394 AggValueSlot::IsDestructed,
395 AggValueSlot::DoesNotNeedGCBarriers,
396 AggValueSlot::IsNotAliased));
401 pushTemporaryCleanup(*this, M, E, Object);
405 SmallVector<const Expr *, 2> CommaLHSs;
406 SmallVector<SubobjectAdjustment, 2> Adjustments;
407 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
409 for (const auto &Ignored : CommaLHSs)
410 EmitIgnoredExpr(Ignored);
412 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
413 if (opaque->getType()->isRecordType()) {
414 assert(Adjustments.empty());
415 return EmitOpaqueValueLValue(opaque);
419 // Create and initialize the reference temporary.
420 Address Object = createReferenceTemporary(*this, M, E);
421 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
422 Object = Address(llvm::ConstantExpr::getBitCast(
423 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
424 Object.getAlignment());
425 // If the temporary is a global and has a constant initializer or is a
426 // constant temporary that we promoted to a global, we may have already
428 if (!Var->hasInitializer()) {
429 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
430 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
433 switch (M->getStorageDuration()) {
435 case SD_FullExpression:
436 if (auto *Size = EmitLifetimeStart(
437 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
438 Object.getPointer())) {
439 if (M->getStorageDuration() == SD_Automatic)
440 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
443 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
450 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
452 pushTemporaryCleanup(*this, M, E, Object);
454 // Perform derived-to-base casts and/or field accesses, to get from the
455 // temporary object we created (and, potentially, for which we extended
456 // the lifetime) to the subobject we're binding the reference to.
457 for (unsigned I = Adjustments.size(); I != 0; --I) {
458 SubobjectAdjustment &Adjustment = Adjustments[I-1];
459 switch (Adjustment.Kind) {
460 case SubobjectAdjustment::DerivedToBaseAdjustment:
462 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
463 Adjustment.DerivedToBase.BasePath->path_begin(),
464 Adjustment.DerivedToBase.BasePath->path_end(),
465 /*NullCheckValue=*/ false, E->getExprLoc());
468 case SubobjectAdjustment::FieldAdjustment: {
469 LValue LV = MakeAddrLValue(Object, E->getType(),
470 LValueBaseInfo(AlignmentSource::Decl, false));
471 LV = EmitLValueForField(LV, Adjustment.Field);
472 assert(LV.isSimple() &&
473 "materialized temporary field is not a simple lvalue");
474 Object = LV.getAddress();
478 case SubobjectAdjustment::MemberPointerAdjustment: {
479 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
480 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
487 return MakeAddrLValue(Object, M->getType(),
488 LValueBaseInfo(AlignmentSource::Decl, false));
492 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
493 // Emit the expression as an lvalue.
494 LValue LV = EmitLValue(E);
495 assert(LV.isSimple());
496 llvm::Value *Value = LV.getPointer();
498 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
499 // C++11 [dcl.ref]p5 (as amended by core issue 453):
500 // If a glvalue to which a reference is directly bound designates neither
501 // an existing object or function of an appropriate type nor a region of
502 // storage of suitable size and alignment to contain an object of the
503 // reference's type, the behavior is undefined.
504 QualType Ty = E->getType();
505 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
508 return RValue::get(Value);
512 /// getAccessedFieldNo - Given an encoded value and a result number, return the
513 /// input field number being accessed.
514 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
515 const llvm::Constant *Elts) {
516 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
520 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
521 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
523 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
524 llvm::Value *K47 = Builder.getInt64(47);
525 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
526 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
527 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
528 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
529 return Builder.CreateMul(B1, KMul);
532 bool CodeGenFunction::sanitizePerformTypeCheck() const {
533 return SanOpts.has(SanitizerKind::Null) |
534 SanOpts.has(SanitizerKind::Alignment) |
535 SanOpts.has(SanitizerKind::ObjectSize) |
536 SanOpts.has(SanitizerKind::Vptr);
539 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
540 llvm::Value *Ptr, QualType Ty,
542 SanitizerSet SkippedChecks) {
543 if (!sanitizePerformTypeCheck())
546 // Don't check pointers outside the default address space. The null check
547 // isn't correct, the object-size check isn't supported by LLVM, and we can't
548 // communicate the addresses to the runtime handler for the vptr check.
549 if (Ptr->getType()->getPointerAddressSpace())
552 SanitizerScope SanScope(this);
554 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
555 llvm::BasicBlock *Done = nullptr;
557 // Quickly determine whether we have a pointer to an alloca. It's possible
558 // to skip null checks, and some alignment checks, for these pointers. This
559 // can reduce compile-time significantly.
561 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
563 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
564 TCK == TCK_UpcastToVirtualBase;
565 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
566 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
567 // The glvalue must not be an empty glvalue.
568 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
570 // The IR builder can constant-fold the null check if the pointer points to
573 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
575 // Skip the null check if the pointer is known to be non-null.
577 if (AllowNullPointers) {
578 // When performing pointer casts, it's OK if the value is null.
579 // Skip the remaining checks in that case.
580 Done = createBasicBlock("null");
581 llvm::BasicBlock *Rest = createBasicBlock("not.null");
582 Builder.CreateCondBr(IsNonNull, Rest, Done);
585 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
590 if (SanOpts.has(SanitizerKind::ObjectSize) &&
591 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
592 !Ty->isIncompleteType()) {
593 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
595 // The glvalue must refer to a large enough storage region.
596 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
598 // FIXME: Get object address space
599 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
600 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
601 llvm::Value *Min = Builder.getFalse();
602 llvm::Value *NullIsUnknown = Builder.getFalse();
603 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
604 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
605 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
606 llvm::ConstantInt::get(IntPtrTy, Size));
607 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
610 uint64_t AlignVal = 0;
612 if (SanOpts.has(SanitizerKind::Alignment) &&
613 !SkippedChecks.has(SanitizerKind::Alignment)) {
614 AlignVal = Alignment.getQuantity();
615 if (!Ty->isIncompleteType() && !AlignVal)
616 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
618 // The glvalue must be suitably aligned.
620 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
622 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
623 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
624 llvm::Value *Aligned =
625 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
626 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
630 if (Checks.size() > 0) {
631 // Make sure we're not losing information. Alignment needs to be a power of
633 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
634 llvm::Constant *StaticData[] = {
635 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
636 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
637 llvm::ConstantInt::get(Int8Ty, TCK)};
638 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
641 // If possible, check that the vptr indicates that there is a subobject of
642 // type Ty at offset zero within this object.
644 // C++11 [basic.life]p5,6:
645 // [For storage which does not refer to an object within its lifetime]
646 // The program has undefined behavior if:
647 // -- the [pointer or glvalue] is used to access a non-static data member
648 // or call a non-static member function
649 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
650 if (SanOpts.has(SanitizerKind::Vptr) &&
651 !SkippedChecks.has(SanitizerKind::Vptr) &&
652 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
653 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
654 TCK == TCK_UpcastToVirtualBase) &&
655 RD && RD->hasDefinition() && RD->isDynamicClass()) {
656 // Compute a hash of the mangled name of the type.
658 // FIXME: This is not guaranteed to be deterministic! Move to a
659 // fingerprinting mechanism once LLVM provides one. For the time
660 // being the implementation happens to be deterministic.
661 SmallString<64> MangledName;
662 llvm::raw_svector_ostream Out(MangledName);
663 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
666 // Blacklist based on the mangled type.
667 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
669 llvm::hash_code TypeHash = hash_value(Out.str());
671 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
672 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
673 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
674 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
675 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
676 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
678 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
679 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
681 // Look the hash up in our cache.
682 const int CacheSize = 128;
683 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
684 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
685 "__ubsan_vptr_type_cache");
686 llvm::Value *Slot = Builder.CreateAnd(Hash,
687 llvm::ConstantInt::get(IntPtrTy,
689 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
690 llvm::Value *CacheVal =
691 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
694 // If the hash isn't in the cache, call a runtime handler to perform the
695 // hard work of checking whether the vptr is for an object of the right
696 // type. This will either fill in the cache and return, or produce a
698 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
699 llvm::Constant *StaticData[] = {
700 EmitCheckSourceLocation(Loc),
701 EmitCheckTypeDescriptor(Ty),
702 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
703 llvm::ConstantInt::get(Int8Ty, TCK)
705 llvm::Value *DynamicData[] = { Ptr, Hash };
706 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
707 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
713 Builder.CreateBr(Done);
718 /// Determine whether this expression refers to a flexible array member in a
719 /// struct. We disable array bounds checks for such members.
720 static bool isFlexibleArrayMemberExpr(const Expr *E) {
721 // For compatibility with existing code, we treat arrays of length 0 or
722 // 1 as flexible array members.
723 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
724 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
725 if (CAT->getSize().ugt(1))
727 } else if (!isa<IncompleteArrayType>(AT))
730 E = E->IgnoreParens();
732 // A flexible array member must be the last member in the class.
733 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
734 // FIXME: If the base type of the member expr is not FD->getParent(),
735 // this should not be treated as a flexible array member access.
736 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
737 RecordDecl::field_iterator FI(
738 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
739 return ++FI == FD->getParent()->field_end();
741 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
742 return IRE->getDecl()->getNextIvar() == nullptr;
748 /// If Base is known to point to the start of an array, return the length of
749 /// that array. Return 0 if the length cannot be determined.
750 static llvm::Value *getArrayIndexingBound(
751 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
752 // For the vector indexing extension, the bound is the number of elements.
753 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
754 IndexedType = Base->getType();
755 return CGF.Builder.getInt32(VT->getNumElements());
758 Base = Base->IgnoreParens();
760 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
761 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
762 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
763 IndexedType = CE->getSubExpr()->getType();
764 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
766 return CGF.Builder.getInt(CAT->getSize());
767 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
768 return CGF.getVLASize(VAT).first;
775 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
776 llvm::Value *Index, QualType IndexType,
778 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
779 "should not be called unless adding bounds checks");
780 SanitizerScope SanScope(this);
782 QualType IndexedType;
783 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
787 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
788 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
789 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
791 llvm::Constant *StaticData[] = {
792 EmitCheckSourceLocation(E->getExprLoc()),
793 EmitCheckTypeDescriptor(IndexedType),
794 EmitCheckTypeDescriptor(IndexType)
796 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
797 : Builder.CreateICmpULE(IndexVal, BoundVal);
798 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
799 SanitizerHandler::OutOfBounds, StaticData, Index);
803 CodeGenFunction::ComplexPairTy CodeGenFunction::
804 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
805 bool isInc, bool isPre) {
806 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
808 llvm::Value *NextVal;
809 if (isa<llvm::IntegerType>(InVal.first->getType())) {
810 uint64_t AmountVal = isInc ? 1 : -1;
811 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
813 // Add the inc/dec to the real part.
814 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
816 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
817 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
820 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
822 // Add the inc/dec to the real part.
823 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
826 ComplexPairTy IncVal(NextVal, InVal.second);
828 // Store the updated result through the lvalue.
829 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
831 // If this is a postinc, return the value read from memory, otherwise use the
833 return isPre ? IncVal : InVal;
836 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
837 CodeGenFunction *CGF) {
838 // Bind VLAs in the cast type.
839 if (CGF && E->getType()->isVariablyModifiedType())
840 CGF->EmitVariablyModifiedType(E->getType());
842 if (CGDebugInfo *DI = getModuleDebugInfo())
843 DI->EmitExplicitCastType(E->getType());
846 //===----------------------------------------------------------------------===//
847 // LValue Expression Emission
848 //===----------------------------------------------------------------------===//
850 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
851 /// derive a more accurate bound on the alignment of the pointer.
852 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
853 LValueBaseInfo *BaseInfo) {
854 // We allow this with ObjC object pointers because of fragile ABIs.
855 assert(E->getType()->isPointerType() ||
856 E->getType()->isObjCObjectPointerType());
857 E = E->IgnoreParens();
860 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
861 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
862 CGM.EmitExplicitCastExprType(ECE, this);
864 switch (CE->getCastKind()) {
865 // Non-converting casts (but not C's implicit conversion from void*).
868 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
869 if (PtrTy->getPointeeType()->isVoidType())
872 LValueBaseInfo InnerInfo;
873 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
874 if (BaseInfo) *BaseInfo = InnerInfo;
876 // If this is an explicit bitcast, and the source l-value is
877 // opaque, honor the alignment of the casted-to type.
878 if (isa<ExplicitCastExpr>(CE) &&
879 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
880 LValueBaseInfo ExpInfo;
881 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
884 BaseInfo->mergeForCast(ExpInfo);
885 Addr = Address(Addr.getPointer(), Align);
888 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
889 CE->getCastKind() == CK_BitCast) {
890 if (auto PT = E->getType()->getAs<PointerType>())
891 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
893 CodeGenFunction::CFITCK_UnrelatedCast,
897 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
901 // Array-to-pointer decay.
902 case CK_ArrayToPointerDecay:
903 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
905 // Derived-to-base conversions.
906 case CK_UncheckedDerivedToBase:
907 case CK_DerivedToBase: {
908 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
909 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
910 return GetAddressOfBaseClass(Addr, Derived,
911 CE->path_begin(), CE->path_end(),
912 ShouldNullCheckClassCastValue(CE),
916 // TODO: Is there any reason to treat base-to-derived conversions
924 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
925 if (UO->getOpcode() == UO_AddrOf) {
926 LValue LV = EmitLValue(UO->getSubExpr());
927 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
928 return LV.getAddress();
932 // TODO: conditional operators, comma.
934 // Otherwise, use the alignment of the type.
935 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
936 return Address(EmitScalarExpr(E), Align);
939 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
940 if (Ty->isVoidType())
941 return RValue::get(nullptr);
943 switch (getEvaluationKind(Ty)) {
946 ConvertType(Ty->castAs<ComplexType>()->getElementType());
947 llvm::Value *U = llvm::UndefValue::get(EltTy);
948 return RValue::getComplex(std::make_pair(U, U));
951 // If this is a use of an undefined aggregate type, the aggregate must have an
952 // identifiable address. Just because the contents of the value are undefined
953 // doesn't mean that the address can't be taken and compared.
954 case TEK_Aggregate: {
955 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
956 return RValue::getAggregate(DestPtr);
960 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
962 llvm_unreachable("bad evaluation kind");
965 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
967 ErrorUnsupported(E, Name);
968 return GetUndefRValue(E->getType());
971 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
973 ErrorUnsupported(E, Name);
974 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
975 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
979 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
980 const Expr *Base = Obj;
981 while (!isa<CXXThisExpr>(Base)) {
982 // The result of a dynamic_cast can be null.
983 if (isa<CXXDynamicCastExpr>(Base))
986 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
987 Base = CE->getSubExpr();
988 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
989 Base = PE->getSubExpr();
990 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
991 if (UO->getOpcode() == UO_Extension)
992 Base = UO->getSubExpr();
1002 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1004 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1005 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1008 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1009 SanitizerSet SkippedChecks;
1010 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1011 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1013 SkippedChecks.set(SanitizerKind::Alignment, true);
1014 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1015 SkippedChecks.set(SanitizerKind::Null, true);
1017 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1018 E->getType(), LV.getAlignment(), SkippedChecks);
1023 /// EmitLValue - Emit code to compute a designator that specifies the location
1024 /// of the expression.
1026 /// This can return one of two things: a simple address or a bitfield reference.
1027 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1028 /// an LLVM pointer type.
1030 /// If this returns a bitfield reference, nothing about the pointee type of the
1031 /// LLVM value is known: For example, it may not be a pointer to an integer.
1033 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1034 /// this method guarantees that the returned pointer type will point to an LLVM
1035 /// type of the same size of the lvalue's type. If the lvalue has a variable
1036 /// length type, this is not possible.
1038 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1039 ApplyDebugLocation DL(*this, E);
1040 switch (E->getStmtClass()) {
1041 default: return EmitUnsupportedLValue(E, "l-value expression");
1043 case Expr::ObjCPropertyRefExprClass:
1044 llvm_unreachable("cannot emit a property reference directly");
1046 case Expr::ObjCSelectorExprClass:
1047 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1048 case Expr::ObjCIsaExprClass:
1049 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1050 case Expr::BinaryOperatorClass:
1051 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1052 case Expr::CompoundAssignOperatorClass: {
1053 QualType Ty = E->getType();
1054 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1055 Ty = AT->getValueType();
1056 if (!Ty->isAnyComplexType())
1057 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1058 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1060 case Expr::CallExprClass:
1061 case Expr::CXXMemberCallExprClass:
1062 case Expr::CXXOperatorCallExprClass:
1063 case Expr::UserDefinedLiteralClass:
1064 return EmitCallExprLValue(cast<CallExpr>(E));
1065 case Expr::VAArgExprClass:
1066 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1067 case Expr::DeclRefExprClass:
1068 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1069 case Expr::ParenExprClass:
1070 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1071 case Expr::GenericSelectionExprClass:
1072 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1073 case Expr::PredefinedExprClass:
1074 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1075 case Expr::StringLiteralClass:
1076 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1077 case Expr::ObjCEncodeExprClass:
1078 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1079 case Expr::PseudoObjectExprClass:
1080 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1081 case Expr::InitListExprClass:
1082 return EmitInitListLValue(cast<InitListExpr>(E));
1083 case Expr::CXXTemporaryObjectExprClass:
1084 case Expr::CXXConstructExprClass:
1085 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1086 case Expr::CXXBindTemporaryExprClass:
1087 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1088 case Expr::CXXUuidofExprClass:
1089 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1090 case Expr::LambdaExprClass:
1091 return EmitLambdaLValue(cast<LambdaExpr>(E));
1093 case Expr::ExprWithCleanupsClass: {
1094 const auto *cleanups = cast<ExprWithCleanups>(E);
1095 enterFullExpression(cleanups);
1096 RunCleanupsScope Scope(*this);
1097 LValue LV = EmitLValue(cleanups->getSubExpr());
1098 if (LV.isSimple()) {
1099 // Defend against branches out of gnu statement expressions surrounded by
1101 llvm::Value *V = LV.getPointer();
1102 Scope.ForceCleanup({&V});
1103 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1104 getContext(), LV.getBaseInfo(),
1107 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1108 // bitfield lvalue or some other non-simple lvalue?
1112 case Expr::CXXDefaultArgExprClass:
1113 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1114 case Expr::CXXDefaultInitExprClass: {
1115 CXXDefaultInitExprScope Scope(*this);
1116 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1118 case Expr::CXXTypeidExprClass:
1119 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1121 case Expr::ObjCMessageExprClass:
1122 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1123 case Expr::ObjCIvarRefExprClass:
1124 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1125 case Expr::StmtExprClass:
1126 return EmitStmtExprLValue(cast<StmtExpr>(E));
1127 case Expr::UnaryOperatorClass:
1128 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1129 case Expr::ArraySubscriptExprClass:
1130 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1131 case Expr::OMPArraySectionExprClass:
1132 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1133 case Expr::ExtVectorElementExprClass:
1134 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1135 case Expr::MemberExprClass:
1136 return EmitMemberExpr(cast<MemberExpr>(E));
1137 case Expr::CompoundLiteralExprClass:
1138 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1139 case Expr::ConditionalOperatorClass:
1140 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1141 case Expr::BinaryConditionalOperatorClass:
1142 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1143 case Expr::ChooseExprClass:
1144 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1145 case Expr::OpaqueValueExprClass:
1146 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1147 case Expr::SubstNonTypeTemplateParmExprClass:
1148 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1149 case Expr::ImplicitCastExprClass:
1150 case Expr::CStyleCastExprClass:
1151 case Expr::CXXFunctionalCastExprClass:
1152 case Expr::CXXStaticCastExprClass:
1153 case Expr::CXXDynamicCastExprClass:
1154 case Expr::CXXReinterpretCastExprClass:
1155 case Expr::CXXConstCastExprClass:
1156 case Expr::ObjCBridgedCastExprClass:
1157 return EmitCastLValue(cast<CastExpr>(E));
1159 case Expr::MaterializeTemporaryExprClass:
1160 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1164 /// Given an object of the given canonical type, can we safely copy a
1165 /// value out of it based on its initializer?
1166 static bool isConstantEmittableObjectType(QualType type) {
1167 assert(type.isCanonical());
1168 assert(!type->isReferenceType());
1170 // Must be const-qualified but non-volatile.
1171 Qualifiers qs = type.getLocalQualifiers();
1172 if (!qs.hasConst() || qs.hasVolatile()) return false;
1174 // Otherwise, all object types satisfy this except C++ classes with
1175 // mutable subobjects or non-trivial copy/destroy behavior.
1176 if (const auto *RT = dyn_cast<RecordType>(type))
1177 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1178 if (RD->hasMutableFields() || !RD->isTrivial())
1184 /// Can we constant-emit a load of a reference to a variable of the
1185 /// given type? This is different from predicates like
1186 /// Decl::isUsableInConstantExpressions because we do want it to apply
1187 /// in situations that don't necessarily satisfy the language's rules
1188 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1189 /// to do this with const float variables even if those variables
1190 /// aren't marked 'constexpr'.
1191 enum ConstantEmissionKind {
1193 CEK_AsReferenceOnly,
1194 CEK_AsValueOrReference,
1197 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1198 type = type.getCanonicalType();
1199 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1200 if (isConstantEmittableObjectType(ref->getPointeeType()))
1201 return CEK_AsValueOrReference;
1202 return CEK_AsReferenceOnly;
1204 if (isConstantEmittableObjectType(type))
1205 return CEK_AsValueOnly;
1209 /// Try to emit a reference to the given value without producing it as
1210 /// an l-value. This is actually more than an optimization: we can't
1211 /// produce an l-value for variables that we never actually captured
1212 /// in a block or lambda, which means const int variables or constexpr
1213 /// literals or similar.
1214 CodeGenFunction::ConstantEmission
1215 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1216 ValueDecl *value = refExpr->getDecl();
1218 // The value needs to be an enum constant or a constant variable.
1219 ConstantEmissionKind CEK;
1220 if (isa<ParmVarDecl>(value)) {
1222 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1223 CEK = checkVarTypeForConstantEmission(var->getType());
1224 } else if (isa<EnumConstantDecl>(value)) {
1225 CEK = CEK_AsValueOnly;
1229 if (CEK == CEK_None) return ConstantEmission();
1231 Expr::EvalResult result;
1232 bool resultIsReference;
1233 QualType resultType;
1235 // It's best to evaluate all the way as an r-value if that's permitted.
1236 if (CEK != CEK_AsReferenceOnly &&
1237 refExpr->EvaluateAsRValue(result, getContext())) {
1238 resultIsReference = false;
1239 resultType = refExpr->getType();
1241 // Otherwise, try to evaluate as an l-value.
1242 } else if (CEK != CEK_AsValueOnly &&
1243 refExpr->EvaluateAsLValue(result, getContext())) {
1244 resultIsReference = true;
1245 resultType = value->getType();
1249 return ConstantEmission();
1252 // In any case, if the initializer has side-effects, abandon ship.
1253 if (result.HasSideEffects)
1254 return ConstantEmission();
1256 // Emit as a constant.
1257 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1259 // Make sure we emit a debug reference to the global variable.
1260 // This should probably fire even for
1261 if (isa<VarDecl>(value)) {
1262 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1263 EmitDeclRefExprDbgValue(refExpr, result.Val);
1265 assert(isa<EnumConstantDecl>(value));
1266 EmitDeclRefExprDbgValue(refExpr, result.Val);
1269 // If we emitted a reference constant, we need to dereference that.
1270 if (resultIsReference)
1271 return ConstantEmission::forReference(C);
1273 return ConstantEmission::forValue(C);
1276 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1277 SourceLocation Loc) {
1278 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1279 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1280 lvalue.getTBAAInfo(),
1281 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1282 lvalue.isNontemporal());
1285 static bool hasBooleanRepresentation(QualType Ty) {
1286 if (Ty->isBooleanType())
1289 if (const EnumType *ET = Ty->getAs<EnumType>())
1290 return ET->getDecl()->getIntegerType()->isBooleanType();
1292 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1293 return hasBooleanRepresentation(AT->getValueType());
1298 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1299 llvm::APInt &Min, llvm::APInt &End,
1300 bool StrictEnums, bool IsBool) {
1301 const EnumType *ET = Ty->getAs<EnumType>();
1302 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1303 ET && !ET->getDecl()->isFixed();
1304 if (!IsBool && !IsRegularCPlusPlusEnum)
1308 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1309 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1311 const EnumDecl *ED = ET->getDecl();
1312 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1313 unsigned Bitwidth = LTy->getScalarSizeInBits();
1314 unsigned NumNegativeBits = ED->getNumNegativeBits();
1315 unsigned NumPositiveBits = ED->getNumPositiveBits();
1317 if (NumNegativeBits) {
1318 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1319 assert(NumBits <= Bitwidth);
1320 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1323 assert(NumPositiveBits <= Bitwidth);
1324 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1325 Min = llvm::APInt(Bitwidth, 0);
1331 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1332 llvm::APInt Min, End;
1333 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1334 hasBooleanRepresentation(Ty)))
1337 llvm::MDBuilder MDHelper(getLLVMContext());
1338 return MDHelper.createRange(Min, End);
1341 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1342 SourceLocation Loc) {
1343 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1344 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1345 if (!HasBoolCheck && !HasEnumCheck)
1348 bool IsBool = hasBooleanRepresentation(Ty) ||
1349 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1350 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1351 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1352 if (!NeedsBoolCheck && !NeedsEnumCheck)
1355 // Single-bit booleans don't need to be checked. Special-case this to avoid
1356 // a bit width mismatch when handling bitfield values. This is handled by
1357 // EmitFromMemory for the non-bitfield case.
1359 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1362 llvm::APInt Min, End;
1363 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1366 SanitizerScope SanScope(this);
1370 Check = Builder.CreateICmpULE(
1371 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1373 llvm::Value *Upper = Builder.CreateICmpSLE(
1374 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1375 llvm::Value *Lower = Builder.CreateICmpSGE(
1376 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1377 Check = Builder.CreateAnd(Upper, Lower);
1379 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1380 EmitCheckTypeDescriptor(Ty)};
1381 SanitizerMask Kind =
1382 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1383 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1384 StaticArgs, EmitCheckValue(Value));
1388 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1391 LValueBaseInfo BaseInfo,
1392 llvm::MDNode *TBAAInfo,
1393 QualType TBAABaseType,
1394 uint64_t TBAAOffset,
1395 bool isNontemporal) {
1396 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1397 // For better performance, handle vector loads differently.
1398 if (Ty->isVectorType()) {
1399 const llvm::Type *EltTy = Addr.getElementType();
1401 const auto *VTy = cast<llvm::VectorType>(EltTy);
1403 // Handle vectors of size 3 like size 4 for better performance.
1404 if (VTy->getNumElements() == 3) {
1406 // Bitcast to vec4 type.
1407 llvm::VectorType *vec4Ty =
1408 llvm::VectorType::get(VTy->getElementType(), 4);
1409 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1411 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1413 // Shuffle vector to get vec3.
1414 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1415 {0, 1, 2}, "extractVec");
1416 return EmitFromMemory(V, Ty);
1421 // Atomic operations have to be done on integral types.
1422 LValue AtomicLValue =
1423 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1424 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1425 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1428 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1429 if (isNontemporal) {
1430 llvm::MDNode *Node = llvm::MDNode::get(
1431 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1432 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1435 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1438 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1439 false /*ConvertTypeToTag*/);
1442 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1443 // In order to prevent the optimizer from throwing away the check, don't
1444 // attach range metadata to the load.
1445 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1446 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1447 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1449 return EmitFromMemory(Load, Ty);
1452 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1453 // Bool has a different representation in memory than in registers.
1454 if (hasBooleanRepresentation(Ty)) {
1455 // This should really always be an i1, but sometimes it's already
1456 // an i8, and it's awkward to track those cases down.
1457 if (Value->getType()->isIntegerTy(1))
1458 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1459 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1460 "wrong value rep of bool");
1466 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1467 // Bool has a different representation in memory than in registers.
1468 if (hasBooleanRepresentation(Ty)) {
1469 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1470 "wrong value rep of bool");
1471 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1477 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1478 bool Volatile, QualType Ty,
1479 LValueBaseInfo BaseInfo,
1480 llvm::MDNode *TBAAInfo,
1481 bool isInit, QualType TBAABaseType,
1482 uint64_t TBAAOffset,
1483 bool isNontemporal) {
1485 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1486 // Handle vectors differently to get better performance.
1487 if (Ty->isVectorType()) {
1488 llvm::Type *SrcTy = Value->getType();
1489 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1490 // Handle vec3 special.
1491 if (VecTy->getNumElements() == 3) {
1492 // Our source is a vec3, do a shuffle vector to make it a vec4.
1493 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1494 Builder.getInt32(2),
1495 llvm::UndefValue::get(Builder.getInt32Ty())};
1496 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1497 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1498 MaskV, "extractVec");
1499 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1501 if (Addr.getElementType() != SrcTy) {
1502 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1507 Value = EmitToMemory(Value, Ty);
1509 LValue AtomicLValue =
1510 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1511 if (Ty->isAtomicType() ||
1512 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1513 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1517 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1518 if (isNontemporal) {
1519 llvm::MDNode *Node =
1520 llvm::MDNode::get(Store->getContext(),
1521 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1522 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1525 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1528 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1529 false /*ConvertTypeToTag*/);
1533 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1535 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1536 lvalue.getType(), lvalue.getBaseInfo(),
1537 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1538 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1541 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1542 /// method emits the address of the lvalue, then loads the result as an rvalue,
1543 /// returning the rvalue.
1544 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1545 if (LV.isObjCWeak()) {
1546 // load of a __weak object.
1547 Address AddrWeakObj = LV.getAddress();
1548 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1551 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1552 // In MRC mode, we do a load+autorelease.
1553 if (!getLangOpts().ObjCAutoRefCount) {
1554 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1557 // In ARC mode, we load retained and then consume the value.
1558 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1559 Object = EmitObjCConsumeObject(LV.getType(), Object);
1560 return RValue::get(Object);
1563 if (LV.isSimple()) {
1564 assert(!LV.getType()->isFunctionType());
1566 // Everything needs a load.
1567 return RValue::get(EmitLoadOfScalar(LV, Loc));
1570 if (LV.isVectorElt()) {
1571 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1572 LV.isVolatileQualified());
1573 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1577 // If this is a reference to a subset of the elements of a vector, either
1578 // shuffle the input or extract/insert them as appropriate.
1579 if (LV.isExtVectorElt())
1580 return EmitLoadOfExtVectorElementLValue(LV);
1582 // Global Register variables always invoke intrinsics
1583 if (LV.isGlobalReg())
1584 return EmitLoadOfGlobalRegLValue(LV);
1586 assert(LV.isBitField() && "Unknown LValue type!");
1587 return EmitLoadOfBitfieldLValue(LV, Loc);
1590 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1591 SourceLocation Loc) {
1592 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1594 // Get the output type.
1595 llvm::Type *ResLTy = ConvertType(LV.getType());
1597 Address Ptr = LV.getBitFieldAddress();
1598 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1600 if (Info.IsSigned) {
1601 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1602 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1604 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1605 if (Info.Offset + HighBits)
1606 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1609 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1610 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1611 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1615 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1616 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1617 return RValue::get(Val);
1620 // If this is a reference to a subset of the elements of a vector, create an
1621 // appropriate shufflevector.
1622 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1623 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1624 LV.isVolatileQualified());
1626 const llvm::Constant *Elts = LV.getExtVectorElts();
1628 // If the result of the expression is a non-vector type, we must be extracting
1629 // a single element. Just codegen as an extractelement.
1630 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1632 unsigned InIdx = getAccessedFieldNo(0, Elts);
1633 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1634 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1637 // Always use shuffle vector to try to retain the original program structure
1638 unsigned NumResultElts = ExprVT->getNumElements();
1640 SmallVector<llvm::Constant*, 4> Mask;
1641 for (unsigned i = 0; i != NumResultElts; ++i)
1642 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1644 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1645 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1647 return RValue::get(Vec);
1650 /// @brief Generates lvalue for partial ext_vector access.
1651 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1652 Address VectorAddress = LV.getExtVectorAddress();
1653 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1654 QualType EQT = ExprVT->getElementType();
1655 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1657 Address CastToPointerElement =
1658 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1659 "conv.ptr.element");
1661 const llvm::Constant *Elts = LV.getExtVectorElts();
1662 unsigned ix = getAccessedFieldNo(0, Elts);
1664 Address VectorBasePtrPlusIx =
1665 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1666 getContext().getTypeSizeInChars(EQT),
1669 return VectorBasePtrPlusIx;
1672 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1673 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1674 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1675 "Bad type for register variable");
1676 llvm::MDNode *RegName = cast<llvm::MDNode>(
1677 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1679 // We accept integer and pointer types only
1680 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1681 llvm::Type *Ty = OrigTy;
1682 if (OrigTy->isPointerTy())
1683 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1684 llvm::Type *Types[] = { Ty };
1686 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1687 llvm::Value *Call = Builder.CreateCall(
1688 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1689 if (OrigTy->isPointerTy())
1690 Call = Builder.CreateIntToPtr(Call, OrigTy);
1691 return RValue::get(Call);
1695 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1696 /// lvalue, where both are guaranteed to the have the same type, and that type
1698 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1700 if (!Dst.isSimple()) {
1701 if (Dst.isVectorElt()) {
1702 // Read/modify/write the vector, inserting the new element.
1703 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1704 Dst.isVolatileQualified());
1705 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1706 Dst.getVectorIdx(), "vecins");
1707 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1708 Dst.isVolatileQualified());
1712 // If this is an update of extended vector elements, insert them as
1714 if (Dst.isExtVectorElt())
1715 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1717 if (Dst.isGlobalReg())
1718 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1720 assert(Dst.isBitField() && "Unknown LValue type");
1721 return EmitStoreThroughBitfieldLValue(Src, Dst);
1724 // There's special magic for assigning into an ARC-qualified l-value.
1725 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1727 case Qualifiers::OCL_None:
1728 llvm_unreachable("present but none");
1730 case Qualifiers::OCL_ExplicitNone:
1734 case Qualifiers::OCL_Strong:
1736 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1739 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1742 case Qualifiers::OCL_Weak:
1744 // Initialize and then skip the primitive store.
1745 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1747 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1750 case Qualifiers::OCL_Autoreleasing:
1751 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1752 Src.getScalarVal()));
1753 // fall into the normal path
1758 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1759 // load of a __weak object.
1760 Address LvalueDst = Dst.getAddress();
1761 llvm::Value *src = Src.getScalarVal();
1762 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1766 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1767 // load of a __strong object.
1768 Address LvalueDst = Dst.getAddress();
1769 llvm::Value *src = Src.getScalarVal();
1770 if (Dst.isObjCIvar()) {
1771 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1772 llvm::Type *ResultType = IntPtrTy;
1773 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1774 llvm::Value *RHS = dst.getPointer();
1775 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1777 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1778 "sub.ptr.lhs.cast");
1779 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1780 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1782 } else if (Dst.isGlobalObjCRef()) {
1783 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1784 Dst.isThreadLocalRef());
1787 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1791 assert(Src.isScalar() && "Can't emit an agg store with this method");
1792 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1795 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1796 llvm::Value **Result) {
1797 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1798 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1799 Address Ptr = Dst.getBitFieldAddress();
1801 // Get the source value, truncated to the width of the bit-field.
1802 llvm::Value *SrcVal = Src.getScalarVal();
1804 // Cast the source to the storage type and shift it into place.
1805 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1806 /*IsSigned=*/false);
1807 llvm::Value *MaskedVal = SrcVal;
1809 // See if there are other bits in the bitfield's storage we'll need to load
1810 // and mask together with source before storing.
1811 if (Info.StorageSize != Info.Size) {
1812 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1814 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1816 // Mask the source value as needed.
1817 if (!hasBooleanRepresentation(Dst.getType()))
1818 SrcVal = Builder.CreateAnd(SrcVal,
1819 llvm::APInt::getLowBitsSet(Info.StorageSize,
1824 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1826 // Mask out the original value.
1827 Val = Builder.CreateAnd(Val,
1828 ~llvm::APInt::getBitsSet(Info.StorageSize,
1830 Info.Offset + Info.Size),
1833 // Or together the unchanged values and the source value.
1834 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1836 assert(Info.Offset == 0);
1839 // Write the new value back out.
1840 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1842 // Return the new value of the bit-field, if requested.
1844 llvm::Value *ResultVal = MaskedVal;
1846 // Sign extend the value if needed.
1847 if (Info.IsSigned) {
1848 assert(Info.Size <= Info.StorageSize);
1849 unsigned HighBits = Info.StorageSize - Info.Size;
1851 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1852 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1856 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1858 *Result = EmitFromMemory(ResultVal, Dst.getType());
1862 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1864 // This access turns into a read/modify/write of the vector. Load the input
1866 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1867 Dst.isVolatileQualified());
1868 const llvm::Constant *Elts = Dst.getExtVectorElts();
1870 llvm::Value *SrcVal = Src.getScalarVal();
1872 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1873 unsigned NumSrcElts = VTy->getNumElements();
1874 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1875 if (NumDstElts == NumSrcElts) {
1876 // Use shuffle vector is the src and destination are the same number of
1877 // elements and restore the vector mask since it is on the side it will be
1879 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1880 for (unsigned i = 0; i != NumSrcElts; ++i)
1881 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1883 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1884 Vec = Builder.CreateShuffleVector(SrcVal,
1885 llvm::UndefValue::get(Vec->getType()),
1887 } else if (NumDstElts > NumSrcElts) {
1888 // Extended the source vector to the same length and then shuffle it
1889 // into the destination.
1890 // FIXME: since we're shuffling with undef, can we just use the indices
1891 // into that? This could be simpler.
1892 SmallVector<llvm::Constant*, 4> ExtMask;
1893 for (unsigned i = 0; i != NumSrcElts; ++i)
1894 ExtMask.push_back(Builder.getInt32(i));
1895 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1896 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1897 llvm::Value *ExtSrcVal =
1898 Builder.CreateShuffleVector(SrcVal,
1899 llvm::UndefValue::get(SrcVal->getType()),
1902 SmallVector<llvm::Constant*, 4> Mask;
1903 for (unsigned i = 0; i != NumDstElts; ++i)
1904 Mask.push_back(Builder.getInt32(i));
1906 // When the vector size is odd and .odd or .hi is used, the last element
1907 // of the Elts constant array will be one past the size of the vector.
1908 // Ignore the last element here, if it is greater than the mask size.
1909 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1912 // modify when what gets shuffled in
1913 for (unsigned i = 0; i != NumSrcElts; ++i)
1914 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1915 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1916 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1918 // We should never shorten the vector
1919 llvm_unreachable("unexpected shorten vector length");
1922 // If the Src is a scalar (not a vector) it must be updating one element.
1923 unsigned InIdx = getAccessedFieldNo(0, Elts);
1924 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1925 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1928 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1929 Dst.isVolatileQualified());
1932 /// @brief Store of global named registers are always calls to intrinsics.
1933 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1934 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1935 "Bad type for register variable");
1936 llvm::MDNode *RegName = cast<llvm::MDNode>(
1937 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1938 assert(RegName && "Register LValue is not metadata");
1940 // We accept integer and pointer types only
1941 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1942 llvm::Type *Ty = OrigTy;
1943 if (OrigTy->isPointerTy())
1944 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1945 llvm::Type *Types[] = { Ty };
1947 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1948 llvm::Value *Value = Src.getScalarVal();
1949 if (OrigTy->isPointerTy())
1950 Value = Builder.CreatePtrToInt(Value, Ty);
1952 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1955 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1956 // generating write-barries API. It is currently a global, ivar,
1958 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1960 bool IsMemberAccess=false) {
1961 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1964 if (isa<ObjCIvarRefExpr>(E)) {
1965 QualType ExpTy = E->getType();
1966 if (IsMemberAccess && ExpTy->isPointerType()) {
1967 // If ivar is a structure pointer, assigning to field of
1968 // this struct follows gcc's behavior and makes it a non-ivar
1969 // writer-barrier conservatively.
1970 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1971 if (ExpTy->isRecordType()) {
1972 LV.setObjCIvar(false);
1976 LV.setObjCIvar(true);
1977 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1978 LV.setBaseIvarExp(Exp->getBase());
1979 LV.setObjCArray(E->getType()->isArrayType());
1983 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1984 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1985 if (VD->hasGlobalStorage()) {
1986 LV.setGlobalObjCRef(true);
1987 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1990 LV.setObjCArray(E->getType()->isArrayType());
1994 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1995 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1999 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2000 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2001 if (LV.isObjCIvar()) {
2002 // If cast is to a structure pointer, follow gcc's behavior and make it
2003 // a non-ivar write-barrier.
2004 QualType ExpTy = E->getType();
2005 if (ExpTy->isPointerType())
2006 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2007 if (ExpTy->isRecordType())
2008 LV.setObjCIvar(false);
2013 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2014 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2018 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2019 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2023 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2024 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2028 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2029 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2033 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2034 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2035 if (LV.isObjCIvar() && !LV.isObjCArray())
2036 // Using array syntax to assigning to what an ivar points to is not
2037 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2038 LV.setObjCIvar(false);
2039 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2040 // Using array syntax to assigning to what global points to is not
2041 // same as assigning to the global itself. {id *G;} G[i] = 0;
2042 LV.setGlobalObjCRef(false);
2046 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2047 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2048 // We don't know if member is an 'ivar', but this flag is looked at
2049 // only in the context of LV.isObjCIvar().
2050 LV.setObjCArray(E->getType()->isArrayType());
2055 static llvm::Value *
2056 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2057 llvm::Value *V, llvm::Type *IRType,
2058 StringRef Name = StringRef()) {
2059 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2060 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2063 static LValue EmitThreadPrivateVarDeclLValue(
2064 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2065 llvm::Type *RealVarTy, SourceLocation Loc) {
2066 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2067 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2068 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2069 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
2072 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2073 const ReferenceType *RefTy,
2074 LValueBaseInfo *BaseInfo) {
2075 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2076 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2077 BaseInfo, /*forPointee*/ true));
2080 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2081 const ReferenceType *RefTy) {
2082 LValueBaseInfo BaseInfo;
2083 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2084 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
2087 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2088 const PointerType *PtrTy,
2089 LValueBaseInfo *BaseInfo) {
2090 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2091 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2093 /*forPointeeType=*/true));
2096 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2097 const PointerType *PtrTy) {
2098 LValueBaseInfo BaseInfo;
2099 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2100 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
2103 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2104 const Expr *E, const VarDecl *VD) {
2105 QualType T = E->getType();
2107 // If it's thread_local, emit a call to its wrapper function instead.
2108 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2109 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2110 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2112 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2113 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2114 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2115 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2116 Address Addr(V, Alignment);
2118 // Emit reference to the private copy of the variable if it is an OpenMP
2119 // threadprivate variable.
2120 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2121 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2123 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2124 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2126 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2127 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
2129 setObjCGCLValueClass(CGF.getContext(), E, LV);
2133 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2134 const FunctionDecl *FD) {
2135 if (FD->hasAttr<WeakRefAttr>()) {
2136 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2137 return aliasee.getPointer();
2140 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2141 if (!FD->hasPrototype()) {
2142 if (const FunctionProtoType *Proto =
2143 FD->getType()->getAs<FunctionProtoType>()) {
2144 // Ugly case: for a K&R-style definition, the type of the definition
2145 // isn't the same as the type of a use. Correct for this with a
2147 QualType NoProtoType =
2148 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2149 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2150 V = llvm::ConstantExpr::getBitCast(V,
2151 CGM.getTypes().ConvertType(NoProtoType));
2157 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2158 const Expr *E, const FunctionDecl *FD) {
2159 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2160 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2161 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2162 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
2165 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2166 llvm::Value *ThisValue) {
2167 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2168 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2169 return CGF.EmitLValueForField(LV, FD);
2172 /// Named Registers are named metadata pointing to the register name
2173 /// which will be read from/written to as an argument to the intrinsic
2174 /// @llvm.read/write_register.
2175 /// So far, only the name is being passed down, but other options such as
2176 /// register type, allocation type or even optimization options could be
2177 /// passed down via the metadata node.
2178 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2179 SmallString<64> Name("llvm.named.register.");
2180 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2181 assert(Asm->getLabel().size() < 64-Name.size() &&
2182 "Register name too big");
2183 Name.append(Asm->getLabel());
2184 llvm::NamedMDNode *M =
2185 CGM.getModule().getOrInsertNamedMetadata(Name);
2186 if (M->getNumOperands() == 0) {
2187 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2189 llvm::Metadata *Ops[] = {Str};
2190 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2193 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2196 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2197 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2200 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2201 const NamedDecl *ND = E->getDecl();
2202 QualType T = E->getType();
2204 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2205 // Global Named registers access via intrinsics only
2206 if (VD->getStorageClass() == SC_Register &&
2207 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2208 return EmitGlobalNamedRegister(VD, CGM);
2210 // A DeclRefExpr for a reference initialized by a constant expression can
2211 // appear without being odr-used. Directly emit the constant initializer.
2212 const Expr *Init = VD->getAnyInitializer(VD);
2213 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2214 VD->isUsableInConstantExpressions(getContext()) &&
2215 VD->checkInitIsICE() &&
2216 // Do not emit if it is private OpenMP variable.
2217 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2218 LocalDeclMap.count(VD))) {
2219 llvm::Constant *Val =
2220 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2221 assert(Val && "failed to emit reference constant expression");
2222 // FIXME: Eventually we will want to emit vector element references.
2224 // Should we be using the alignment of the constant pointer we emitted?
2225 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2227 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2228 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
2231 // Check for captured variables.
2232 if (E->refersToEnclosingVariableOrCapture()) {
2233 if (auto *FD = LambdaCaptureFields.lookup(VD))
2234 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2235 else if (CapturedStmtInfo) {
2236 auto I = LocalDeclMap.find(VD);
2237 if (I != LocalDeclMap.end()) {
2238 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2239 return EmitLoadOfReferenceLValue(I->second, RefTy);
2240 return MakeAddrLValue(I->second, T);
2243 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2244 CapturedStmtInfo->getContextValue());
2245 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
2246 return MakeAddrLValue(
2247 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2248 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
2251 assert(isa<BlockDecl>(CurCodeDecl));
2252 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2253 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2254 return MakeAddrLValue(addr, T, BaseInfo);
2258 // FIXME: We should be able to assert this for FunctionDecls as well!
2259 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2260 // those with a valid source location.
2261 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2262 !E->getLocation().isValid()) &&
2263 "Should not use decl without marking it used!");
2265 if (ND->hasAttr<WeakRefAttr>()) {
2266 const auto *VD = cast<ValueDecl>(ND);
2267 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2268 return MakeAddrLValue(Aliasee, T,
2269 LValueBaseInfo(AlignmentSource::Decl, false));
2272 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2273 // Check if this is a global variable.
2274 if (VD->hasLinkage() || VD->isStaticDataMember())
2275 return EmitGlobalVarDeclLValue(*this, E, VD);
2277 Address addr = Address::invalid();
2279 // The variable should generally be present in the local decl map.
2280 auto iter = LocalDeclMap.find(VD);
2281 if (iter != LocalDeclMap.end()) {
2282 addr = iter->second;
2284 // Otherwise, it might be static local we haven't emitted yet for
2285 // some reason; most likely, because it's in an outer function.
2286 } else if (VD->isStaticLocal()) {
2287 addr = Address(CGM.getOrCreateStaticVarDecl(
2288 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2289 getContext().getDeclAlign(VD));
2291 // No other cases for now.
2293 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2297 // Check for OpenMP threadprivate variables.
2298 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2299 return EmitThreadPrivateVarDeclLValue(
2300 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2304 // Drill into block byref variables.
2305 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2307 addr = emitBlockByrefAddress(addr, VD);
2310 // Drill into reference types.
2312 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2313 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2315 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2316 LV = MakeAddrLValue(addr, T, BaseInfo);
2319 bool isLocalStorage = VD->hasLocalStorage();
2321 bool NonGCable = isLocalStorage &&
2322 !VD->getType()->isReferenceType() &&
2325 LV.getQuals().removeObjCGCAttr();
2329 bool isImpreciseLifetime =
2330 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2331 if (isImpreciseLifetime)
2332 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2333 setObjCGCLValueClass(getContext(), E, LV);
2337 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2338 return EmitFunctionDeclLValue(*this, E, FD);
2340 // FIXME: While we're emitting a binding from an enclosing scope, all other
2341 // DeclRefExprs we see should be implicitly treated as if they also refer to
2342 // an enclosing scope.
2343 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2344 return EmitLValue(BD->getBinding());
2346 llvm_unreachable("Unhandled DeclRefExpr");
2349 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2350 // __extension__ doesn't affect lvalue-ness.
2351 if (E->getOpcode() == UO_Extension)
2352 return EmitLValue(E->getSubExpr());
2354 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2355 switch (E->getOpcode()) {
2356 default: llvm_unreachable("Unknown unary operator lvalue!");
2358 QualType T = E->getSubExpr()->getType()->getPointeeType();
2359 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2361 LValueBaseInfo BaseInfo;
2362 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2363 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
2364 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2366 // We should not generate __weak write barrier on indirect reference
2367 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2368 // But, we continue to generate __strong write barrier on indirect write
2369 // into a pointer to object.
2370 if (getLangOpts().ObjC1 &&
2371 getLangOpts().getGC() != LangOptions::NonGC &&
2373 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2378 LValue LV = EmitLValue(E->getSubExpr());
2379 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2381 // __real is valid on scalars. This is a faster way of testing that.
2382 // __imag can only produce an rvalue on scalars.
2383 if (E->getOpcode() == UO_Real &&
2384 !LV.getAddress().getElementType()->isStructTy()) {
2385 assert(E->getSubExpr()->getType()->isArithmeticType());
2389 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2392 (E->getOpcode() == UO_Real
2393 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2394 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2395 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
2396 ElemLV.getQuals().addQualifiers(LV.getQuals());
2401 LValue LV = EmitLValue(E->getSubExpr());
2402 bool isInc = E->getOpcode() == UO_PreInc;
2404 if (E->getType()->isAnyComplexType())
2405 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2407 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2413 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2414 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2416 LValueBaseInfo(AlignmentSource::Decl, false));
2419 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2420 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2422 LValueBaseInfo(AlignmentSource::Decl, false));
2425 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2426 auto SL = E->getFunctionName();
2427 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2428 StringRef FnName = CurFn->getName();
2429 if (FnName.startswith("\01"))
2430 FnName = FnName.substr(1);
2431 StringRef NameItems[] = {
2432 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2433 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2434 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2435 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2436 std::string Name = SL->getString();
2437 if (!Name.empty()) {
2438 unsigned Discriminator =
2439 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2441 Name += "_" + Twine(Discriminator + 1).str();
2442 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2443 return MakeAddrLValue(C, E->getType(), BaseInfo);
2445 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2446 return MakeAddrLValue(C, E->getType(), BaseInfo);
2449 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2450 return MakeAddrLValue(C, E->getType(), BaseInfo);
2453 /// Emit a type description suitable for use by a runtime sanitizer library. The
2454 /// format of a type descriptor is
2457 /// { i16 TypeKind, i16 TypeInfo }
2460 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2461 /// integer, 1 for a floating point value, and -1 for anything else.
2462 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2463 // Only emit each type's descriptor once.
2464 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2467 uint16_t TypeKind = -1;
2468 uint16_t TypeInfo = 0;
2470 if (T->isIntegerType()) {
2472 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2473 (T->isSignedIntegerType() ? 1 : 0);
2474 } else if (T->isFloatingType()) {
2476 TypeInfo = getContext().getTypeSize(T);
2479 // Format the type name as if for a diagnostic, including quotes and
2480 // optionally an 'aka'.
2481 SmallString<32> Buffer;
2482 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2483 (intptr_t)T.getAsOpaquePtr(),
2484 StringRef(), StringRef(), None, Buffer,
2487 llvm::Constant *Components[] = {
2488 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2489 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2491 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2493 auto *GV = new llvm::GlobalVariable(
2494 CGM.getModule(), Descriptor->getType(),
2495 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2496 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2497 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2499 // Remember the descriptor for this type.
2500 CGM.setTypeDescriptorInMap(T, GV);
2505 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2506 llvm::Type *TargetTy = IntPtrTy;
2508 // Floating-point types which fit into intptr_t are bitcast to integers
2509 // and then passed directly (after zero-extension, if necessary).
2510 if (V->getType()->isFloatingPointTy()) {
2511 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2512 if (Bits <= TargetTy->getIntegerBitWidth())
2513 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2517 // Integers which fit in intptr_t are zero-extended and passed directly.
2518 if (V->getType()->isIntegerTy() &&
2519 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2520 return Builder.CreateZExt(V, TargetTy);
2522 // Pointers are passed directly, everything else is passed by address.
2523 if (!V->getType()->isPointerTy()) {
2524 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2525 Builder.CreateStore(V, Ptr);
2526 V = Ptr.getPointer();
2528 return Builder.CreatePtrToInt(V, TargetTy);
2531 /// \brief Emit a representation of a SourceLocation for passing to a handler
2532 /// in a sanitizer runtime library. The format for this data is:
2534 /// struct SourceLocation {
2535 /// const char *Filename;
2536 /// int32_t Line, Column;
2539 /// For an invalid SourceLocation, the Filename pointer is null.
2540 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2541 llvm::Constant *Filename;
2544 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2545 if (PLoc.isValid()) {
2546 StringRef FilenameString = PLoc.getFilename();
2548 int PathComponentsToStrip =
2549 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2550 if (PathComponentsToStrip < 0) {
2551 assert(PathComponentsToStrip != INT_MIN);
2552 int PathComponentsToKeep = -PathComponentsToStrip;
2553 auto I = llvm::sys::path::rbegin(FilenameString);
2554 auto E = llvm::sys::path::rend(FilenameString);
2555 while (I != E && --PathComponentsToKeep)
2558 FilenameString = FilenameString.substr(I - E);
2559 } else if (PathComponentsToStrip > 0) {
2560 auto I = llvm::sys::path::begin(FilenameString);
2561 auto E = llvm::sys::path::end(FilenameString);
2562 while (I != E && PathComponentsToStrip--)
2567 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2569 FilenameString = llvm::sys::path::filename(FilenameString);
2572 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2573 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2574 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2575 Filename = FilenameGV.getPointer();
2576 Line = PLoc.getLine();
2577 Column = PLoc.getColumn();
2579 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2583 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2584 Builder.getInt32(Column)};
2586 return llvm::ConstantStruct::getAnon(Data);
2590 /// \brief Specify under what conditions this check can be recovered
2591 enum class CheckRecoverableKind {
2592 /// Always terminate program execution if this check fails.
2594 /// Check supports recovering, runtime has both fatal (noreturn) and
2595 /// non-fatal handlers for this check.
2597 /// Runtime conditionally aborts, always need to support recovery.
2602 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2603 assert(llvm::countPopulation(Kind) == 1);
2605 case SanitizerKind::Vptr:
2606 return CheckRecoverableKind::AlwaysRecoverable;
2607 case SanitizerKind::Return:
2608 case SanitizerKind::Unreachable:
2609 return CheckRecoverableKind::Unrecoverable;
2611 return CheckRecoverableKind::Recoverable;
2616 struct SanitizerHandlerInfo {
2617 char const *const Name;
2622 const SanitizerHandlerInfo SanitizerHandlers[] = {
2623 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2624 LIST_SANITIZER_CHECKS
2625 #undef SANITIZER_CHECK
2628 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2629 llvm::FunctionType *FnType,
2630 ArrayRef<llvm::Value *> FnArgs,
2631 SanitizerHandler CheckHandler,
2632 CheckRecoverableKind RecoverKind, bool IsFatal,
2633 llvm::BasicBlock *ContBB) {
2634 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2635 bool NeedsAbortSuffix =
2636 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2637 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2638 const StringRef CheckName = CheckInfo.Name;
2639 std::string FnName =
2640 ("__ubsan_handle_" + CheckName +
2641 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2642 (NeedsAbortSuffix ? "_abort" : ""))
2645 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2647 llvm::AttrBuilder B;
2649 B.addAttribute(llvm::Attribute::NoReturn)
2650 .addAttribute(llvm::Attribute::NoUnwind);
2652 B.addAttribute(llvm::Attribute::UWTable);
2654 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2656 llvm::AttributeList::get(CGF.getLLVMContext(),
2657 llvm::AttributeList::FunctionIndex, B),
2659 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2661 HandlerCall->setDoesNotReturn();
2662 CGF.Builder.CreateUnreachable();
2664 CGF.Builder.CreateBr(ContBB);
2668 void CodeGenFunction::EmitCheck(
2669 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2670 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2671 ArrayRef<llvm::Value *> DynamicArgs) {
2672 assert(IsSanitizerScope);
2673 assert(Checked.size() > 0);
2674 assert(CheckHandler >= 0 &&
2675 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2676 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2678 llvm::Value *FatalCond = nullptr;
2679 llvm::Value *RecoverableCond = nullptr;
2680 llvm::Value *TrapCond = nullptr;
2681 for (int i = 0, n = Checked.size(); i < n; ++i) {
2682 llvm::Value *Check = Checked[i].first;
2683 // -fsanitize-trap= overrides -fsanitize-recover=.
2684 llvm::Value *&Cond =
2685 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2687 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2690 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2694 EmitTrapCheck(TrapCond);
2695 if (!FatalCond && !RecoverableCond)
2698 llvm::Value *JointCond;
2699 if (FatalCond && RecoverableCond)
2700 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2702 JointCond = FatalCond ? FatalCond : RecoverableCond;
2705 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2706 assert(SanOpts.has(Checked[0].second));
2708 for (int i = 1, n = Checked.size(); i < n; ++i) {
2709 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2710 "All recoverable kinds in a single check must be same!");
2711 assert(SanOpts.has(Checked[i].second));
2715 llvm::BasicBlock *Cont = createBasicBlock("cont");
2716 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2717 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2718 // Give hint that we very much don't expect to execute the handler
2719 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2720 llvm::MDBuilder MDHelper(getLLVMContext());
2721 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2722 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2723 EmitBlock(Handlers);
2725 // Handler functions take an i8* pointing to the (handler-specific) static
2726 // information block, followed by a sequence of intptr_t arguments
2727 // representing operand values.
2728 SmallVector<llvm::Value *, 4> Args;
2729 SmallVector<llvm::Type *, 4> ArgTypes;
2730 Args.reserve(DynamicArgs.size() + 1);
2731 ArgTypes.reserve(DynamicArgs.size() + 1);
2733 // Emit handler arguments and create handler function type.
2734 if (!StaticArgs.empty()) {
2735 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2737 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2738 llvm::GlobalVariable::PrivateLinkage, Info);
2739 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2740 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2741 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2742 ArgTypes.push_back(Int8PtrTy);
2745 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2746 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2747 ArgTypes.push_back(IntPtrTy);
2750 llvm::FunctionType *FnType =
2751 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2753 if (!FatalCond || !RecoverableCond) {
2754 // Simple case: we need to generate a single handler call, either
2755 // fatal, or non-fatal.
2756 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2757 (FatalCond != nullptr), Cont);
2759 // Emit two handler calls: first one for set of unrecoverable checks,
2760 // another one for recoverable.
2761 llvm::BasicBlock *NonFatalHandlerBB =
2762 createBasicBlock("non_fatal." + CheckName);
2763 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2764 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2765 EmitBlock(FatalHandlerBB);
2766 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2768 EmitBlock(NonFatalHandlerBB);
2769 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2776 void CodeGenFunction::EmitCfiSlowPathCheck(
2777 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2778 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2779 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2781 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2782 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2784 llvm::MDBuilder MDHelper(getLLVMContext());
2785 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2786 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2790 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2792 llvm::CallInst *CheckCall;
2794 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2796 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2797 llvm::GlobalVariable::PrivateLinkage, Info);
2798 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2799 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2801 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2802 "__cfi_slowpath_diag",
2803 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2805 CheckCall = Builder.CreateCall(
2807 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2809 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2811 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2812 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2815 CheckCall->setDoesNotThrow();
2820 // Emit a stub for __cfi_check function so that the linker knows about this
2821 // symbol in LTO mode.
2822 void CodeGenFunction::EmitCfiCheckStub() {
2823 llvm::Module *M = &CGM.getModule();
2824 auto &Ctx = M->getContext();
2825 llvm::Function *F = llvm::Function::Create(
2826 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2827 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2828 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2829 // FIXME: consider emitting an intrinsic call like
2830 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2831 // which can be lowered in CrossDSOCFI pass to the actual contents of
2832 // __cfi_check. This would allow inlining of __cfi_check calls.
2833 llvm::CallInst::Create(
2834 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2835 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2838 // This function is basically a switch over the CFI failure kind, which is
2839 // extracted from CFICheckFailData (1st function argument). Each case is either
2840 // llvm.trap or a call to one of the two runtime handlers, based on
2841 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2842 // failure kind) traps, but this should really never happen. CFICheckFailData
2843 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2844 // check kind; in this case __cfi_check_fail traps as well.
2845 void CodeGenFunction::EmitCfiCheckFail() {
2846 SanitizerScope SanScope(this);
2847 FunctionArgList Args;
2848 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2849 getContext().VoidPtrTy);
2850 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2851 getContext().VoidPtrTy);
2852 Args.push_back(&ArgData);
2853 Args.push_back(&ArgAddr);
2855 const CGFunctionInfo &FI =
2856 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2858 llvm::Function *F = llvm::Function::Create(
2859 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2860 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2861 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2863 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2867 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2868 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2870 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2871 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2873 // Data == nullptr means the calling module has trap behaviour for this check.
2874 llvm::Value *DataIsNotNullPtr =
2875 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2876 EmitTrapCheck(DataIsNotNullPtr);
2878 llvm::StructType *SourceLocationTy =
2879 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
2880 llvm::StructType *CfiCheckFailDataTy =
2881 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
2883 llvm::Value *V = Builder.CreateConstGEP2_32(
2885 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2887 Address CheckKindAddr(V, getIntAlign());
2888 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2890 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2891 CGM.getLLVMContext(),
2892 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2893 llvm::Value *ValidVtable = Builder.CreateZExt(
2894 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2895 {Addr, AllVtables}),
2898 const std::pair<int, SanitizerMask> CheckKinds[] = {
2899 {CFITCK_VCall, SanitizerKind::CFIVCall},
2900 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2901 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2902 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2903 {CFITCK_ICall, SanitizerKind::CFIICall}};
2905 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2906 for (auto CheckKindMaskPair : CheckKinds) {
2907 int Kind = CheckKindMaskPair.first;
2908 SanitizerMask Mask = CheckKindMaskPair.second;
2910 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2911 if (CGM.getLangOpts().Sanitize.has(Mask))
2912 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2913 {Data, Addr, ValidVtable});
2915 EmitTrapCheck(Cond);
2919 // The only reference to this function will be created during LTO link.
2920 // Make sure it survives until then.
2921 CGM.addUsedGlobal(F);
2924 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2925 llvm::BasicBlock *Cont = createBasicBlock("cont");
2927 // If we're optimizing, collapse all calls to trap down to just one per
2928 // function to save on code size.
2929 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2930 TrapBB = createBasicBlock("trap");
2931 Builder.CreateCondBr(Checked, Cont, TrapBB);
2933 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2934 TrapCall->setDoesNotReturn();
2935 TrapCall->setDoesNotThrow();
2936 Builder.CreateUnreachable();
2938 Builder.CreateCondBr(Checked, Cont, TrapBB);
2944 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2945 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2947 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2948 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2949 CGM.getCodeGenOpts().TrapFuncName);
2950 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
2956 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2957 LValueBaseInfo *BaseInfo) {
2958 assert(E->getType()->isArrayType() &&
2959 "Array to pointer decay must have array source type!");
2961 // Expressions of array type can't be bitfields or vector elements.
2962 LValue LV = EmitLValue(E);
2963 Address Addr = LV.getAddress();
2964 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
2966 // If the array type was an incomplete type, we need to make sure
2967 // the decay ends up being the right type.
2968 llvm::Type *NewTy = ConvertType(E->getType());
2969 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2971 // Note that VLA pointers are always decayed, so we don't need to do
2973 if (!E->getType()->isVariableArrayType()) {
2974 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2975 "Expected pointer to array");
2976 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2979 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2980 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2983 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2984 /// array to pointer, return the array subexpression.
2985 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2986 // If this isn't just an array->pointer decay, bail out.
2987 const auto *CE = dyn_cast<CastExpr>(E);
2988 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2991 // If this is a decay from variable width array, bail out.
2992 const Expr *SubExpr = CE->getSubExpr();
2993 if (SubExpr->getType()->isVariableArrayType())
2999 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3001 ArrayRef<llvm::Value*> indices,
3003 const llvm::Twine &name = "arrayidx") {
3005 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
3007 return CGF.Builder.CreateGEP(ptr, indices, name);
3011 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3013 CharUnits eltSize) {
3014 // If we have a constant index, we can use the exact offset of the
3015 // element we're accessing.
3016 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3017 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3018 return arrayAlign.alignmentAtOffset(offset);
3020 // Otherwise, use the worst-case alignment for any element.
3022 return arrayAlign.alignmentOfArrayElement(eltSize);
3026 static QualType getFixedSizeElementType(const ASTContext &ctx,
3027 const VariableArrayType *vla) {
3030 eltType = vla->getElementType();
3031 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3035 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3036 ArrayRef<llvm::Value*> indices,
3037 QualType eltType, bool inbounds,
3038 const llvm::Twine &name = "arrayidx") {
3039 // All the indices except that last must be zero.
3041 for (auto idx : indices.drop_back())
3042 assert(isa<llvm::ConstantInt>(idx) &&
3043 cast<llvm::ConstantInt>(idx)->isZero());
3046 // Determine the element size of the statically-sized base. This is
3047 // the thing that the indices are expressed in terms of.
3048 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3049 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3052 // We can use that to compute the best alignment of the element.
3053 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3054 CharUnits eltAlign =
3055 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3057 llvm::Value *eltPtr =
3058 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3059 return Address(eltPtr, eltAlign);
3062 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3064 // The index must always be an integer, which is not an aggregate. Emit it
3065 // in lexical order (this complexity is, sadly, required by C++17).
3066 llvm::Value *IdxPre =
3067 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3068 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3070 if (E->getLHS() != E->getIdx()) {
3071 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3072 Idx = EmitScalarExpr(E->getIdx());
3075 QualType IdxTy = E->getIdx()->getType();
3076 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3078 if (SanOpts.has(SanitizerKind::ArrayBounds))
3079 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3081 // Extend or truncate the index type to 32 or 64-bits.
3082 if (Promote && Idx->getType() != IntPtrTy)
3083 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3089 // If the base is a vector type, then we are forming a vector element lvalue
3090 // with this subscript.
3091 if (E->getBase()->getType()->isVectorType() &&
3092 !isa<ExtVectorElementExpr>(E->getBase())) {
3093 // Emit the vector as an lvalue to get its address.
3094 LValue LHS = EmitLValue(E->getBase());
3095 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3096 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3097 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3098 E->getBase()->getType(),
3102 // All the other cases basically behave like simple offsetting.
3104 // Handle the extvector case we ignored above.
3105 if (isa<ExtVectorElementExpr>(E->getBase())) {
3106 LValue LV = EmitLValue(E->getBase());
3107 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3108 Address Addr = EmitExtVectorElementLValue(LV);
3110 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3111 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3112 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
3115 LValueBaseInfo BaseInfo;
3116 Address Addr = Address::invalid();
3117 if (const VariableArrayType *vla =
3118 getContext().getAsVariableArrayType(E->getType())) {
3119 // The base must be a pointer, which is not an aggregate. Emit
3120 // it. It needs to be emitted first in case it's what captures
3122 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3123 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3125 // The element count here is the total number of non-VLA elements.
3126 llvm::Value *numElements = getVLASize(vla).first;
3128 // Effectively, the multiply by the VLA size is part of the GEP.
3129 // GEP indexes are signed, and scaling an index isn't permitted to
3130 // signed-overflow, so we use the same semantics for our explicit
3131 // multiply. We suppress this if overflow is not undefined behavior.
3132 if (getLangOpts().isSignedOverflowDefined()) {
3133 Idx = Builder.CreateMul(Idx, numElements);
3135 Idx = Builder.CreateNSWMul(Idx, numElements);
3138 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3139 !getLangOpts().isSignedOverflowDefined());
3141 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3142 // Indexing over an interface, as in "NSString *P; P[4];"
3144 // Emit the base pointer.
3145 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3146 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3148 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3149 llvm::Value *InterfaceSizeVal =
3150 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3152 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3154 // We don't necessarily build correct LLVM struct types for ObjC
3155 // interfaces, so we can't rely on GEP to do this scaling
3156 // correctly, so we need to cast to i8*. FIXME: is this actually
3157 // true? A lot of other things in the fragile ABI would break...
3158 llvm::Type *OrigBaseTy = Addr.getType();
3159 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3162 CharUnits EltAlign =
3163 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3164 llvm::Value *EltPtr =
3165 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3166 Addr = Address(EltPtr, EltAlign);
3169 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3170 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3171 // If this is A[i] where A is an array, the frontend will have decayed the
3172 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3173 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3174 // "gep x, i" here. Emit one "gep A, 0, i".
3175 assert(Array->getType()->isArrayType() &&
3176 "Array to pointer decay must have array source type!");
3178 // For simple multidimensional array indexing, set the 'accessed' flag for
3179 // better bounds-checking of the base expression.
3180 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3181 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3183 ArrayLV = EmitLValue(Array);
3184 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3186 // Propagate the alignment from the array itself to the result.
3187 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3188 {CGM.getSize(CharUnits::Zero()), Idx},
3190 !getLangOpts().isSignedOverflowDefined());
3191 BaseInfo = ArrayLV.getBaseInfo();
3193 // The base must be a pointer; emit it with an estimate of its alignment.
3194 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3195 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3196 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3197 !getLangOpts().isSignedOverflowDefined());
3200 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
3202 // TODO: Preserve/extend path TBAA metadata?
3204 if (getLangOpts().ObjC1 &&
3205 getLangOpts().getGC() != LangOptions::NonGC) {
3206 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3207 setObjCGCLValueClass(getContext(), E, LV);
3212 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3213 LValueBaseInfo &BaseInfo,
3214 QualType BaseTy, QualType ElTy,
3215 bool IsLowerBound) {
3217 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3218 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3219 if (BaseTy->isArrayType()) {
3220 Address Addr = BaseLVal.getAddress();
3221 BaseInfo = BaseLVal.getBaseInfo();
3223 // If the array type was an incomplete type, we need to make sure
3224 // the decay ends up being the right type.
3225 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3226 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3228 // Note that VLA pointers are always decayed, so we don't need to do
3230 if (!BaseTy->isVariableArrayType()) {
3231 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3232 "Expected pointer to array");
3233 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3237 return CGF.Builder.CreateElementBitCast(Addr,
3238 CGF.ConvertTypeForMem(ElTy));
3240 LValueBaseInfo TypeInfo;
3241 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3242 BaseInfo.mergeForCast(TypeInfo);
3243 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3245 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
3248 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3249 bool IsLowerBound) {
3252 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3253 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3255 BaseTy = E->getBase()->getType();
3256 QualType ResultExprTy;
3257 if (auto *AT = getContext().getAsArrayType(BaseTy))
3258 ResultExprTy = AT->getElementType();
3260 ResultExprTy = BaseTy->getPointeeType();
3261 llvm::Value *Idx = nullptr;
3262 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3263 // Requesting lower bound or upper bound, but without provided length and
3264 // without ':' symbol for the default length -> length = 1.
3265 // Idx = LowerBound ?: 0;
3266 if (auto *LowerBound = E->getLowerBound()) {
3267 Idx = Builder.CreateIntCast(
3268 EmitScalarExpr(LowerBound), IntPtrTy,
3269 LowerBound->getType()->hasSignedIntegerRepresentation());
3271 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3273 // Try to emit length or lower bound as constant. If this is possible, 1
3274 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3275 // IR (LB + Len) - 1.
3276 auto &C = CGM.getContext();
3277 auto *Length = E->getLength();
3278 llvm::APSInt ConstLength;
3280 // Idx = LowerBound + Length - 1;
3281 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3282 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3285 auto *LowerBound = E->getLowerBound();
3286 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3287 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3288 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3289 LowerBound = nullptr;
3293 else if (!LowerBound)
3296 if (Length || LowerBound) {
3297 auto *LowerBoundVal =
3299 ? Builder.CreateIntCast(
3300 EmitScalarExpr(LowerBound), IntPtrTy,
3301 LowerBound->getType()->hasSignedIntegerRepresentation())
3302 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3305 ? Builder.CreateIntCast(
3306 EmitScalarExpr(Length), IntPtrTy,
3307 Length->getType()->hasSignedIntegerRepresentation())
3308 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3309 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3311 !getLangOpts().isSignedOverflowDefined());
3312 if (Length && LowerBound) {
3313 Idx = Builder.CreateSub(
3314 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3315 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3318 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3320 // Idx = ArraySize - 1;
3321 QualType ArrayTy = BaseTy->isPointerType()
3322 ? E->getBase()->IgnoreParenImpCasts()->getType()
3324 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3325 Length = VAT->getSizeExpr();
3326 if (Length->isIntegerConstantExpr(ConstLength, C))
3329 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3330 ConstLength = CAT->getSize();
3333 auto *LengthVal = Builder.CreateIntCast(
3334 EmitScalarExpr(Length), IntPtrTy,
3335 Length->getType()->hasSignedIntegerRepresentation());
3336 Idx = Builder.CreateSub(
3337 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3338 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3340 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3342 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3348 Address EltPtr = Address::invalid();
3349 LValueBaseInfo BaseInfo;
3350 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3351 // The base must be a pointer, which is not an aggregate. Emit
3352 // it. It needs to be emitted first in case it's what captures
3355 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
3356 VLA->getElementType(), IsLowerBound);
3357 // The element count here is the total number of non-VLA elements.
3358 llvm::Value *NumElements = getVLASize(VLA).first;
3360 // Effectively, the multiply by the VLA size is part of the GEP.
3361 // GEP indexes are signed, and scaling an index isn't permitted to
3362 // signed-overflow, so we use the same semantics for our explicit
3363 // multiply. We suppress this if overflow is not undefined behavior.
3364 if (getLangOpts().isSignedOverflowDefined())
3365 Idx = Builder.CreateMul(Idx, NumElements);
3367 Idx = Builder.CreateNSWMul(Idx, NumElements);
3368 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3369 !getLangOpts().isSignedOverflowDefined());
3370 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3371 // If this is A[i] where A is an array, the frontend will have decayed the
3372 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3373 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3374 // "gep x, i" here. Emit one "gep A, 0, i".
3375 assert(Array->getType()->isArrayType() &&
3376 "Array to pointer decay must have array source type!");
3378 // For simple multidimensional array indexing, set the 'accessed' flag for
3379 // better bounds-checking of the base expression.
3380 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3381 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3383 ArrayLV = EmitLValue(Array);
3385 // Propagate the alignment from the array itself to the result.
3386 EltPtr = emitArraySubscriptGEP(
3387 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3388 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3389 BaseInfo = ArrayLV.getBaseInfo();
3391 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3392 BaseTy, ResultExprTy, IsLowerBound);
3393 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3394 !getLangOpts().isSignedOverflowDefined());
3397 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
3400 LValue CodeGenFunction::
3401 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3402 // Emit the base vector as an l-value.
3405 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3407 // If it is a pointer to a vector, emit the address and form an lvalue with
3409 LValueBaseInfo BaseInfo;
3410 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3411 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3412 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
3413 Base.getQuals().removeObjCGCAttr();
3414 } else if (E->getBase()->isGLValue()) {
3415 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3416 // emit the base as an lvalue.
3417 assert(E->getBase()->getType()->isVectorType());
3418 Base = EmitLValue(E->getBase());
3420 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3421 assert(E->getBase()->getType()->isVectorType() &&
3422 "Result must be a vector");
3423 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3425 // Store the vector to memory (because LValue wants an address).
3426 Address VecMem = CreateMemTemp(E->getBase()->getType());
3427 Builder.CreateStore(Vec, VecMem);
3428 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3429 LValueBaseInfo(AlignmentSource::Decl, false));
3433 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3435 // Encode the element access list into a vector of unsigned indices.
3436 SmallVector<uint32_t, 4> Indices;
3437 E->getEncodedElementAccess(Indices);
3439 if (Base.isSimple()) {
3440 llvm::Constant *CV =
3441 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3442 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3443 Base.getBaseInfo());
3445 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3447 llvm::Constant *BaseElts = Base.getExtVectorElts();
3448 SmallVector<llvm::Constant *, 4> CElts;
3450 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3451 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3452 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3453 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3454 Base.getBaseInfo());
3457 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3458 Expr *BaseExpr = E->getBase();
3459 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3462 LValueBaseInfo BaseInfo;
3463 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
3464 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3465 SanitizerSet SkippedChecks;
3466 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3468 SkippedChecks.set(SanitizerKind::Alignment, true);
3469 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3470 SkippedChecks.set(SanitizerKind::Null, true);
3471 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3472 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3473 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
3475 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3477 NamedDecl *ND = E->getMemberDecl();
3478 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3479 LValue LV = EmitLValueForField(BaseLV, Field);
3480 setObjCGCLValueClass(getContext(), E, LV);
3484 if (auto *VD = dyn_cast<VarDecl>(ND))
3485 return EmitGlobalVarDeclLValue(*this, E, VD);
3487 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3488 return EmitFunctionDeclLValue(*this, E, FD);
3490 llvm_unreachable("Unhandled member declaration!");
3493 /// Given that we are currently emitting a lambda, emit an l-value for
3494 /// one of its members.
3495 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3496 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3497 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3498 QualType LambdaTagType =
3499 getContext().getTagDeclType(Field->getParent());
3500 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3501 return EmitLValueForField(LambdaLV, Field);
3504 /// Drill down to the storage of a field without walking into
3505 /// reference types.
3507 /// The resulting address doesn't necessarily have the right type.
3508 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3509 const FieldDecl *field) {
3510 const RecordDecl *rec = field->getParent();
3513 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3516 // Adjust the alignment down to the given offset.
3517 // As a special case, if the LLVM field index is 0, we know that this
3519 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3520 .getFieldOffset(field->getFieldIndex()) == 0) &&
3521 "LLVM field at index zero had non-zero offset?");
3523 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3524 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3525 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3528 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3531 LValue CodeGenFunction::EmitLValueForField(LValue base,
3532 const FieldDecl *field) {
3533 LValueBaseInfo BaseInfo = base.getBaseInfo();
3534 AlignmentSource fieldAlignSource =
3535 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3536 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
3538 if (field->isBitField()) {
3539 const CGRecordLayout &RL =
3540 CGM.getTypes().getCGRecordLayout(field->getParent());
3541 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3542 Address Addr = base.getAddress();
3543 unsigned Idx = RL.getLLVMFieldNo(field);
3545 // For structs, we GEP to the field that the record layout suggests.
3546 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3548 // Get the access type.
3549 llvm::Type *FieldIntTy =
3550 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3551 if (Addr.getElementType() != FieldIntTy)
3552 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3554 QualType fieldType =
3555 field->getType().withCVRQualifiers(base.getVRQualifiers());
3556 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
3559 const RecordDecl *rec = field->getParent();
3560 QualType type = field->getType();
3562 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3564 Address addr = base.getAddress();
3565 unsigned cvr = base.getVRQualifiers();
3566 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3567 if (rec->isUnion()) {
3568 // For unions, there is no pointer adjustment.
3569 assert(!type->isReferenceType() && "union has reference member");
3570 // TODO: handle path-aware TBAA for union.
3573 // For structs, we GEP to the field that the record layout suggests.
3574 addr = emitAddrOfFieldStorage(*this, addr, field);
3576 // If this is a reference field, load the reference right now.
3577 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3578 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3579 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3581 // Loading the reference will disable path-aware TBAA.
3583 if (CGM.shouldUseTBAA()) {
3586 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3588 tbaa = CGM.getTBAAInfo(type);
3590 CGM.DecorateInstructionWithTBAA(load, tbaa);
3594 type = refType->getPointeeType();
3596 CharUnits alignment =
3597 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3598 FieldBaseInfo.setMayAlias(false);
3599 addr = Address(load, alignment);
3601 // Qualifiers on the struct don't apply to the referencee, and
3602 // we'll pick up CVR from the actual type later, so reset these
3603 // additional qualifiers now.
3608 // Make sure that the address is pointing to the right type. This is critical
3609 // for both unions and structs. A union needs a bitcast, a struct element
3610 // will need a bitcast if the LLVM type laid out doesn't match the desired
3612 addr = Builder.CreateElementBitCast(addr,
3613 CGM.getTypes().ConvertTypeForMem(type),
3616 if (field->hasAttr<AnnotateAttr>())
3617 addr = EmitFieldAnnotations(field, addr);
3619 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
3620 LV.getQuals().addCVRQualifiers(cvr);
3622 const ASTRecordLayout &Layout =
3623 getContext().getASTRecordLayout(field->getParent());
3624 // Set the base type to be the base type of the base LValue and
3625 // update offset to be relative to the base type.
3626 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3627 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3628 Layout.getFieldOffset(field->getFieldIndex()) /
3629 getContext().getCharWidth());
3632 // __weak attribute on a field is ignored.
3633 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3634 LV.getQuals().removeObjCGCAttr();
3636 // Fields of may_alias structs act like 'char' for TBAA purposes.
3637 // FIXME: this should get propagated down through anonymous structs
3639 if (mayAlias && LV.getTBAAInfo())
3640 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3646 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3647 const FieldDecl *Field) {
3648 QualType FieldType = Field->getType();
3650 if (!FieldType->isReferenceType())
3651 return EmitLValueForField(Base, Field);
3653 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3655 // Make sure that the address is pointing to the right type.
3656 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3657 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3659 // TODO: access-path TBAA?
3660 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3661 LValueBaseInfo FieldBaseInfo(
3662 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3663 BaseInfo.getMayAlias());
3664 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
3667 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3668 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
3669 if (E->isFileScope()) {
3670 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3671 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
3673 if (E->getType()->isVariablyModifiedType())
3674 // make sure to emit the VLA size.
3675 EmitVariablyModifiedType(E->getType());
3677 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3678 const Expr *InitExpr = E->getInitializer();
3679 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
3681 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3687 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3688 if (!E->isGLValue())
3689 // Initializing an aggregate temporary in C++11: T{...}.
3690 return EmitAggExprToLValue(E);
3692 // An lvalue initializer list must be initializing a reference.
3693 assert(E->isTransparent() && "non-transparent glvalue init list");
3694 return EmitLValue(E->getInit(0));
3697 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3698 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3699 /// LValue is returned and the current block has been terminated.
3700 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3701 const Expr *Operand) {
3702 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3703 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3707 return CGF.EmitLValue(Operand);
3710 LValue CodeGenFunction::
3711 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3712 if (!expr->isGLValue()) {
3713 // ?: here should be an aggregate.
3714 assert(hasAggregateEvaluationKind(expr->getType()) &&
3715 "Unexpected conditional operator!");
3716 return EmitAggExprToLValue(expr);
3719 OpaqueValueMapping binding(*this, expr);
3721 const Expr *condExpr = expr->getCond();
3723 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3724 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3725 if (!CondExprBool) std::swap(live, dead);
3727 if (!ContainsLabel(dead)) {
3728 // If the true case is live, we need to track its region.
3730 incrementProfileCounter(expr);
3731 return EmitLValue(live);
3735 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3736 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3737 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3739 ConditionalEvaluation eval(*this);
3740 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3742 // Any temporaries created here are conditional.
3743 EmitBlock(lhsBlock);
3744 incrementProfileCounter(expr);
3746 Optional<LValue> lhs =
3747 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3750 if (lhs && !lhs->isSimple())
3751 return EmitUnsupportedLValue(expr, "conditional operator");
3753 lhsBlock = Builder.GetInsertBlock();
3755 Builder.CreateBr(contBlock);
3757 // Any temporaries created here are conditional.
3758 EmitBlock(rhsBlock);
3760 Optional<LValue> rhs =
3761 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3763 if (rhs && !rhs->isSimple())
3764 return EmitUnsupportedLValue(expr, "conditional operator");
3765 rhsBlock = Builder.GetInsertBlock();
3767 EmitBlock(contBlock);
3770 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3772 phi->addIncoming(lhs->getPointer(), lhsBlock);
3773 phi->addIncoming(rhs->getPointer(), rhsBlock);
3774 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3775 AlignmentSource alignSource =
3776 std::max(lhs->getBaseInfo().getAlignmentSource(),
3777 rhs->getBaseInfo().getAlignmentSource());
3778 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3779 rhs->getBaseInfo().getMayAlias();
3780 return MakeAddrLValue(result, expr->getType(),
3781 LValueBaseInfo(alignSource, MayAlias));
3783 assert((lhs || rhs) &&
3784 "both operands of glvalue conditional are throw-expressions?");
3785 return lhs ? *lhs : *rhs;
3789 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3790 /// type. If the cast is to a reference, we can have the usual lvalue result,
3791 /// otherwise if a cast is needed by the code generator in an lvalue context,
3792 /// then it must mean that we need the address of an aggregate in order to
3793 /// access one of its members. This can happen for all the reasons that casts
3794 /// are permitted with aggregate result, including noop aggregate casts, and
3795 /// cast from scalar to union.
3796 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3797 switch (E->getCastKind()) {
3800 case CK_ArrayToPointerDecay:
3801 case CK_FunctionToPointerDecay:
3802 case CK_NullToMemberPointer:
3803 case CK_NullToPointer:
3804 case CK_IntegralToPointer:
3805 case CK_PointerToIntegral:
3806 case CK_PointerToBoolean:
3807 case CK_VectorSplat:
3808 case CK_IntegralCast:
3809 case CK_BooleanToSignedIntegral:
3810 case CK_IntegralToBoolean:
3811 case CK_IntegralToFloating:
3812 case CK_FloatingToIntegral:
3813 case CK_FloatingToBoolean:
3814 case CK_FloatingCast:
3815 case CK_FloatingRealToComplex:
3816 case CK_FloatingComplexToReal:
3817 case CK_FloatingComplexToBoolean:
3818 case CK_FloatingComplexCast:
3819 case CK_FloatingComplexToIntegralComplex:
3820 case CK_IntegralRealToComplex:
3821 case CK_IntegralComplexToReal:
3822 case CK_IntegralComplexToBoolean:
3823 case CK_IntegralComplexCast:
3824 case CK_IntegralComplexToFloatingComplex:
3825 case CK_DerivedToBaseMemberPointer:
3826 case CK_BaseToDerivedMemberPointer:
3827 case CK_MemberPointerToBoolean:
3828 case CK_ReinterpretMemberPointer:
3829 case CK_AnyPointerToBlockPointerCast:
3830 case CK_ARCProduceObject:
3831 case CK_ARCConsumeObject:
3832 case CK_ARCReclaimReturnedObject:
3833 case CK_ARCExtendBlockObject:
3834 case CK_CopyAndAutoreleaseBlockObject:
3835 case CK_AddressSpaceConversion:
3836 case CK_IntToOCLSampler:
3837 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3840 llvm_unreachable("dependent cast kind in IR gen!");
3842 case CK_BuiltinFnToFnPtr:
3843 llvm_unreachable("builtin functions are handled elsewhere");
3845 // These are never l-values; just use the aggregate emission code.
3846 case CK_NonAtomicToAtomic:
3847 case CK_AtomicToNonAtomic:
3848 return EmitAggExprToLValue(E);
3851 LValue LV = EmitLValue(E->getSubExpr());
3852 Address V = LV.getAddress();
3853 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3854 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3857 case CK_ConstructorConversion:
3858 case CK_UserDefinedConversion:
3859 case CK_CPointerToObjCPointerCast:
3860 case CK_BlockPointerToObjCPointerCast:
3862 case CK_LValueToRValue:
3863 return EmitLValue(E->getSubExpr());
3865 case CK_UncheckedDerivedToBase:
3866 case CK_DerivedToBase: {
3867 const RecordType *DerivedClassTy =
3868 E->getSubExpr()->getType()->getAs<RecordType>();
3869 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3871 LValue LV = EmitLValue(E->getSubExpr());
3872 Address This = LV.getAddress();
3874 // Perform the derived-to-base conversion
3875 Address Base = GetAddressOfBaseClass(
3876 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3877 /*NullCheckValue=*/false, E->getExprLoc());
3879 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
3882 return EmitAggExprToLValue(E);
3883 case CK_BaseToDerived: {
3884 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3885 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3887 LValue LV = EmitLValue(E->getSubExpr());
3889 // Perform the base-to-derived conversion
3891 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3892 E->path_begin(), E->path_end(),
3893 /*NullCheckValue=*/false);
3895 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3896 // performed and the object is not of the derived type.
3897 if (sanitizePerformTypeCheck())
3898 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3899 Derived.getPointer(), E->getType());
3901 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3902 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3903 /*MayBeNull=*/false,
3904 CFITCK_DerivedCast, E->getLocStart());
3906 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
3908 case CK_LValueBitCast: {
3909 // This must be a reinterpret_cast (or c-style equivalent).
3910 const auto *CE = cast<ExplicitCastExpr>(E);
3912 CGM.EmitExplicitCastExprType(CE, this);
3913 LValue LV = EmitLValue(E->getSubExpr());
3914 Address V = Builder.CreateBitCast(LV.getAddress(),
3915 ConvertType(CE->getTypeAsWritten()));
3917 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3918 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3919 /*MayBeNull=*/false,
3920 CFITCK_UnrelatedCast, E->getLocStart());
3922 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
3924 case CK_ObjCObjectLValueCast: {
3925 LValue LV = EmitLValue(E->getSubExpr());
3926 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3927 ConvertType(E->getType()));
3928 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
3930 case CK_ZeroToOCLQueue:
3931 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3932 case CK_ZeroToOCLEvent:
3933 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3936 llvm_unreachable("Unhandled lvalue cast kind?");
3939 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3940 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3941 return getOpaqueLValueMapping(e);
3944 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3945 const FieldDecl *FD,
3946 SourceLocation Loc) {
3947 QualType FT = FD->getType();
3948 LValue FieldLV = EmitLValueForField(LV, FD);
3949 switch (getEvaluationKind(FT)) {
3951 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3953 return FieldLV.asAggregateRValue();
3955 // This routine is used to load fields one-by-one to perform a copy, so
3956 // don't load reference fields.
3957 if (FD->getType()->isReferenceType())
3958 return RValue::get(FieldLV.getPointer());
3959 return EmitLoadOfLValue(FieldLV, Loc);
3961 llvm_unreachable("bad evaluation kind");
3964 //===--------------------------------------------------------------------===//
3965 // Expression Emission
3966 //===--------------------------------------------------------------------===//
3968 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3969 ReturnValueSlot ReturnValue) {
3970 // Builtins never have block type.
3971 if (E->getCallee()->getType()->isBlockPointerType())
3972 return EmitBlockCallExpr(E, ReturnValue);
3974 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3975 return EmitCXXMemberCallExpr(CE, ReturnValue);
3977 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3978 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3980 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3981 if (const CXXMethodDecl *MD =
3982 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3983 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3985 CGCallee callee = EmitCallee(E->getCallee());
3987 if (callee.isBuiltin()) {
3988 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3992 if (callee.isPseudoDestructor()) {
3993 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3996 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3999 /// Emit a CallExpr without considering whether it might be a subclass.
4000 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4001 ReturnValueSlot ReturnValue) {
4002 CGCallee Callee = EmitCallee(E->getCallee());
4003 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4006 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4007 if (auto builtinID = FD->getBuiltinID()) {
4008 return CGCallee::forBuiltin(builtinID, FD);
4011 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4012 return CGCallee::forDirect(calleePtr, FD);
4015 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4016 E = E->IgnoreParens();
4018 // Look through function-to-pointer decay.
4019 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4020 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4021 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4022 return EmitCallee(ICE->getSubExpr());
4025 // Resolve direct calls.
4026 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4027 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4028 return EmitDirectCallee(*this, FD);
4030 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4031 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4032 EmitIgnoredExpr(ME->getBase());
4033 return EmitDirectCallee(*this, FD);
4036 // Look through template substitutions.
4037 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4038 return EmitCallee(NTTP->getReplacement());
4040 // Treat pseudo-destructor calls differently.
4041 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4042 return CGCallee::forPseudoDestructor(PDE);
4045 // Otherwise, we have an indirect reference.
4046 llvm::Value *calleePtr;
4047 QualType functionType;
4048 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4049 calleePtr = EmitScalarExpr(E);
4050 functionType = ptrType->getPointeeType();
4052 functionType = E->getType();
4053 calleePtr = EmitLValue(E).getPointer();
4055 assert(functionType->isFunctionType());
4056 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4057 E->getReferencedDeclOfCallee());
4058 CGCallee callee(calleeInfo, calleePtr);
4062 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4063 // Comma expressions just emit their LHS then their RHS as an l-value.
4064 if (E->getOpcode() == BO_Comma) {
4065 EmitIgnoredExpr(E->getLHS());
4066 EnsureInsertPoint();
4067 return EmitLValue(E->getRHS());
4070 if (E->getOpcode() == BO_PtrMemD ||
4071 E->getOpcode() == BO_PtrMemI)
4072 return EmitPointerToDataMemberBinaryExpr(E);
4074 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4076 // Note that in all of these cases, __block variables need the RHS
4077 // evaluated first just in case the variable gets moved by the RHS.
4079 switch (getEvaluationKind(E->getType())) {
4081 switch (E->getLHS()->getType().getObjCLifetime()) {
4082 case Qualifiers::OCL_Strong:
4083 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4085 case Qualifiers::OCL_Autoreleasing:
4086 return EmitARCStoreAutoreleasing(E).first;
4088 // No reason to do any of these differently.
4089 case Qualifiers::OCL_None:
4090 case Qualifiers::OCL_ExplicitNone:
4091 case Qualifiers::OCL_Weak:
4095 RValue RV = EmitAnyExpr(E->getRHS());
4096 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4098 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4099 EmitStoreThroughLValue(RV, LV);
4104 return EmitComplexAssignmentLValue(E);
4107 return EmitAggExprToLValue(E);
4109 llvm_unreachable("bad evaluation kind");
4112 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4113 RValue RV = EmitCallExpr(E);
4116 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4117 LValueBaseInfo(AlignmentSource::Decl, false));
4119 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4120 "Can't have a scalar return unless the return type is a "
4123 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4126 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4127 // FIXME: This shouldn't require another copy.
4128 return EmitAggExprToLValue(E);
4131 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4132 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4133 && "binding l-value to type which needs a temporary");
4134 AggValueSlot Slot = CreateAggTemp(E->getType());
4135 EmitCXXConstructExpr(E, Slot);
4136 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4137 LValueBaseInfo(AlignmentSource::Decl, false));
4141 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4142 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4145 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4146 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4147 ConvertType(E->getType()));
4150 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4151 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4152 LValueBaseInfo(AlignmentSource::Decl, false));
4156 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4157 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4158 Slot.setExternallyDestructed();
4159 EmitAggExpr(E->getSubExpr(), Slot);
4160 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4161 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4162 LValueBaseInfo(AlignmentSource::Decl, false));
4166 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4167 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4168 EmitLambdaExpr(E, Slot);
4169 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4170 LValueBaseInfo(AlignmentSource::Decl, false));
4173 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4174 RValue RV = EmitObjCMessageExpr(E);
4177 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4178 LValueBaseInfo(AlignmentSource::Decl, false));
4180 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4181 "Can't have a scalar return unless the return type is a "
4184 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4187 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4189 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4190 return MakeAddrLValue(V, E->getType(),
4191 LValueBaseInfo(AlignmentSource::Decl, false));
4194 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4195 const ObjCIvarDecl *Ivar) {
4196 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4199 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4200 llvm::Value *BaseValue,
4201 const ObjCIvarDecl *Ivar,
4202 unsigned CVRQualifiers) {
4203 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4204 Ivar, CVRQualifiers);
4207 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4208 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4209 llvm::Value *BaseValue = nullptr;
4210 const Expr *BaseExpr = E->getBase();
4211 Qualifiers BaseQuals;
4214 BaseValue = EmitScalarExpr(BaseExpr);
4215 ObjectTy = BaseExpr->getType()->getPointeeType();
4216 BaseQuals = ObjectTy.getQualifiers();
4218 LValue BaseLV = EmitLValue(BaseExpr);
4219 BaseValue = BaseLV.getPointer();
4220 ObjectTy = BaseExpr->getType();
4221 BaseQuals = ObjectTy.getQualifiers();
4225 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4226 BaseQuals.getCVRQualifiers());
4227 setObjCGCLValueClass(getContext(), E, LV);
4231 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4232 // Can only get l-value for message expression returning aggregate type
4233 RValue RV = EmitAnyExprToTemp(E);
4234 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4235 LValueBaseInfo(AlignmentSource::Decl, false));
4238 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4239 const CallExpr *E, ReturnValueSlot ReturnValue,
4240 llvm::Value *Chain) {
4241 // Get the actual function type. The callee type will always be a pointer to
4242 // function type or a block pointer type.
4243 assert(CalleeType->isFunctionPointerType() &&
4244 "Call must have function pointer type!");
4246 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4248 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4249 // We can only guarantee that a function is called from the correct
4250 // context/function based on the appropriate target attributes,
4251 // so only check in the case where we have both always_inline and target
4252 // since otherwise we could be making a conditional call after a check for
4253 // the proper cpu features (and it won't cause code generation issues due to
4254 // function based code generation).
4255 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4256 TargetDecl->hasAttr<TargetAttr>())
4257 checkTargetFeatures(E, FD);
4259 CalleeType = getContext().getCanonicalType(CalleeType);
4261 const auto *FnType =
4262 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4264 CGCallee Callee = OrigCallee;
4266 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4267 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4268 if (llvm::Constant *PrefixSig =
4269 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4270 SanitizerScope SanScope(this);
4271 llvm::Constant *FTRTTIConst =
4272 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4273 llvm::Type *PrefixStructTyElems[] = {
4274 PrefixSig->getType(),
4275 FTRTTIConst->getType()
4277 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4278 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4280 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4282 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4283 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4284 llvm::Value *CalleeSigPtr =
4285 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4286 llvm::Value *CalleeSig =
4287 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4288 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4290 llvm::BasicBlock *Cont = createBasicBlock("cont");
4291 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4292 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4294 EmitBlock(TypeCheck);
4295 llvm::Value *CalleeRTTIPtr =
4296 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4297 llvm::Value *CalleeRTTI =
4298 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4299 llvm::Value *CalleeRTTIMatch =
4300 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4301 llvm::Constant *StaticData[] = {
4302 EmitCheckSourceLocation(E->getLocStart()),
4303 EmitCheckTypeDescriptor(CalleeType)
4305 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4306 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4308 Builder.CreateBr(Cont);
4313 // If we are checking indirect calls and this call is indirect, check that the
4314 // function pointer is a member of the bit set for the function type.
4315 if (SanOpts.has(SanitizerKind::CFIICall) &&
4316 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4317 SanitizerScope SanScope(this);
4318 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4320 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4321 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4323 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4324 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4325 llvm::Value *TypeTest = Builder.CreateCall(
4326 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4328 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4329 llvm::Constant *StaticData[] = {
4330 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4331 EmitCheckSourceLocation(E->getLocStart()),
4332 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4334 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4335 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4336 CastedCallee, StaticData);
4338 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4339 SanitizerHandler::CFICheckFail, StaticData,
4340 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4346 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4347 CGM.getContext().VoidPtrTy);
4349 // C++17 requires that we evaluate arguments to a call using assignment syntax
4350 // right-to-left, and that we evaluate arguments to certain other operators
4351 // left-to-right. Note that we allow this to override the order dictated by
4352 // the calling convention on the MS ABI, which means that parameter
4353 // destruction order is not necessarily reverse construction order.
4354 // FIXME: Revisit this based on C++ committee response to unimplementability.
4355 EvaluationOrder Order = EvaluationOrder::Default;
4356 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4357 if (OCE->isAssignmentOp())
4358 Order = EvaluationOrder::ForceRightToLeft;
4360 switch (OCE->getOperator()) {
4362 case OO_GreaterGreater:
4367 Order = EvaluationOrder::ForceLeftToRight;
4375 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4376 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4378 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4379 Args, FnType, /*isChainCall=*/Chain);
4382 // If the expression that denotes the called function has a type
4383 // that does not include a prototype, [the default argument
4384 // promotions are performed]. If the number of arguments does not
4385 // equal the number of parameters, the behavior is undefined. If
4386 // the function is defined with a type that includes a prototype,
4387 // and either the prototype ends with an ellipsis (, ...) or the
4388 // types of the arguments after promotion are not compatible with
4389 // the types of the parameters, the behavior is undefined. If the
4390 // function is defined with a type that does not include a
4391 // prototype, and the types of the arguments after promotion are
4392 // not compatible with those of the parameters after promotion,
4393 // the behavior is undefined [except in some trivial cases].
4394 // That is, in the general case, we should assume that a call
4395 // through an unprototyped function type works like a *non-variadic*
4396 // call. The way we make this work is to cast to the exact type
4397 // of the promoted arguments.
4399 // Chain calls use this same code path to add the invisible chain parameter
4400 // to the function type.
4401 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4402 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4403 CalleeTy = CalleeTy->getPointerTo();
4405 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4406 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4407 Callee.setFunctionPointer(CalleePtr);
4410 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4413 LValue CodeGenFunction::
4414 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4415 Address BaseAddr = Address::invalid();
4416 if (E->getOpcode() == BO_PtrMemI) {
4417 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4419 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4422 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4424 const MemberPointerType *MPT
4425 = E->getRHS()->getType()->getAs<MemberPointerType>();
4427 LValueBaseInfo BaseInfo;
4428 Address MemberAddr =
4429 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
4431 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
4434 /// Given the address of a temporary variable, produce an r-value of
4436 RValue CodeGenFunction::convertTempToRValue(Address addr,
4438 SourceLocation loc) {
4439 LValue lvalue = MakeAddrLValue(addr, type,
4440 LValueBaseInfo(AlignmentSource::Decl, false));
4441 switch (getEvaluationKind(type)) {
4443 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4445 return lvalue.asAggregateRValue();
4447 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4449 llvm_unreachable("bad evaluation kind");
4452 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4453 assert(Val->getType()->isFPOrFPVectorTy());
4454 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4457 llvm::MDBuilder MDHelper(getLLVMContext());
4458 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4460 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4464 struct LValueOrRValue {
4470 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4471 const PseudoObjectExpr *E,
4473 AggValueSlot slot) {
4474 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4476 // Find the result expression, if any.
4477 const Expr *resultExpr = E->getResultExpr();
4478 LValueOrRValue result;
4480 for (PseudoObjectExpr::const_semantics_iterator
4481 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4482 const Expr *semantic = *i;
4484 // If this semantic expression is an opaque value, bind it
4485 // to the result of its source expression.
4486 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4488 // If this is the result expression, we may need to evaluate
4489 // directly into the slot.
4490 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4492 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4493 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4494 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4495 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
4496 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4498 opaqueData = OVMA::bind(CGF, ov, LV);
4499 result.RV = slot.asRValue();
4501 // Otherwise, emit as normal.
4503 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4505 // If this is the result, also evaluate the result now.
4506 if (ov == resultExpr) {
4508 result.LV = CGF.EmitLValue(ov);
4510 result.RV = CGF.EmitAnyExpr(ov, slot);
4514 opaques.push_back(opaqueData);
4516 // Otherwise, if the expression is the result, evaluate it
4517 // and remember the result.
4518 } else if (semantic == resultExpr) {
4520 result.LV = CGF.EmitLValue(semantic);
4522 result.RV = CGF.EmitAnyExpr(semantic, slot);
4524 // Otherwise, evaluate the expression in an ignored context.
4526 CGF.EmitIgnoredExpr(semantic);
4530 // Unbind all the opaques now.
4531 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4532 opaques[i].unbind(CGF);
4537 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4538 AggValueSlot slot) {
4539 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4542 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4543 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;