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, nullptr, Name, AllocaInsertPt);
77 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
78 /// default alignment of the corresponding LLVM type, which is *not*
79 /// guaranteed to be related in any way to the expected alignment of
80 /// an AST type that might have been lowered to Ty.
81 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
84 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
85 return CreateTempAlloca(Ty, Align, Name);
88 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
89 assert(isa<llvm::AllocaInst>(Var.getPointer()));
90 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
91 Store->setAlignment(Var.getAlignment().getQuantity());
92 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
93 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
96 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
97 CharUnits Align = getContext().getTypeAlignInChars(Ty);
98 return CreateTempAlloca(ConvertType(Ty), Align, Name);
101 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
102 // FIXME: Should we prefer the preferred type alignment here?
103 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
106 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
108 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
111 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
112 /// expression and compare the result against zero, returning an Int1Ty value.
113 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
114 PGO.setCurrentStmt(E);
115 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
116 llvm::Value *MemPtr = EmitScalarExpr(E);
117 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
120 QualType BoolTy = getContext().BoolTy;
121 SourceLocation Loc = E->getExprLoc();
122 if (!E->getType()->isAnyComplexType())
123 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
125 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
129 /// EmitIgnoredExpr - Emit code to compute the specified expression,
130 /// ignoring the result.
131 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
133 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
135 // Just emit it as an l-value and drop the result.
139 /// EmitAnyExpr - Emit code to compute the specified expression which
140 /// can have any type. The result is returned as an RValue struct.
141 /// If this is an aggregate expression, AggSlot indicates where the
142 /// result should be returned.
143 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
144 AggValueSlot aggSlot,
146 switch (getEvaluationKind(E->getType())) {
148 return RValue::get(EmitScalarExpr(E, ignoreResult));
150 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
152 if (!ignoreResult && aggSlot.isIgnored())
153 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
154 EmitAggExpr(E, aggSlot);
155 return aggSlot.asRValue();
157 llvm_unreachable("bad evaluation kind");
160 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
161 /// always be accessible even if no aggregate location is provided.
162 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
163 AggValueSlot AggSlot = AggValueSlot::ignored();
165 if (hasAggregateEvaluationKind(E->getType()))
166 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
167 return EmitAnyExpr(E, AggSlot);
170 /// EmitAnyExprToMem - Evaluate an expression into a given memory
172 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
176 // FIXME: This function should take an LValue as an argument.
177 switch (getEvaluationKind(E->getType())) {
179 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
183 case TEK_Aggregate: {
184 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
185 AggValueSlot::IsDestructed_t(IsInit),
186 AggValueSlot::DoesNotNeedGCBarriers,
187 AggValueSlot::IsAliased_t(!IsInit)));
192 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
193 LValue LV = MakeAddrLValue(Location, E->getType());
194 EmitStoreThroughLValue(RV, LV);
198 llvm_unreachable("bad evaluation kind");
202 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
203 const Expr *E, Address ReferenceTemporary) {
204 // Objective-C++ ARC:
205 // If we are binding a reference to a temporary that has ownership, we
206 // need to perform retain/release operations on the temporary.
208 // FIXME: This should be looking at E, not M.
209 if (auto Lifetime = M->getType().getObjCLifetime()) {
211 case Qualifiers::OCL_None:
212 case Qualifiers::OCL_ExplicitNone:
213 // Carry on to normal cleanup handling.
216 case Qualifiers::OCL_Autoreleasing:
217 // Nothing to do; cleaned up by an autorelease pool.
220 case Qualifiers::OCL_Strong:
221 case Qualifiers::OCL_Weak:
222 switch (StorageDuration Duration = M->getStorageDuration()) {
224 // Note: we intentionally do not register a cleanup to release
225 // the object on program termination.
229 // FIXME: We should probably register a cleanup in this case.
233 case SD_FullExpression:
234 CodeGenFunction::Destroyer *Destroy;
235 CleanupKind CleanupKind;
236 if (Lifetime == Qualifiers::OCL_Strong) {
237 const ValueDecl *VD = M->getExtendingDecl();
239 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
240 CleanupKind = CGF.getARCCleanupKind();
241 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
242 : &CodeGenFunction::destroyARCStrongImprecise;
244 // __weak objects always get EH cleanups; otherwise, exceptions
245 // could cause really nasty crashes instead of mere leaks.
246 CleanupKind = NormalAndEHCleanup;
247 Destroy = &CodeGenFunction::destroyARCWeak;
249 if (Duration == SD_FullExpression)
250 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
251 M->getType(), *Destroy,
252 CleanupKind & EHCleanup);
254 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
256 *Destroy, CleanupKind & EHCleanup);
260 llvm_unreachable("temporary cannot have dynamic storage duration");
262 llvm_unreachable("unknown storage duration");
266 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
267 if (const RecordType *RT =
268 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
269 // Get the destructor for the reference temporary.
270 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
271 if (!ClassDecl->hasTrivialDestructor())
272 ReferenceTemporaryDtor = ClassDecl->getDestructor();
275 if (!ReferenceTemporaryDtor)
278 // Call the destructor for the temporary.
279 switch (M->getStorageDuration()) {
282 llvm::Constant *CleanupFn;
283 llvm::Constant *CleanupArg;
284 if (E->getType()->isArrayType()) {
285 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
286 ReferenceTemporary, E->getType(),
287 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
288 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
289 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
291 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
292 StructorType::Complete);
293 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
295 CGF.CGM.getCXXABI().registerGlobalDtor(
296 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
300 case SD_FullExpression:
301 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
302 CodeGenFunction::destroyCXXObject,
303 CGF.getLangOpts().Exceptions);
307 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
308 ReferenceTemporary, E->getType(),
309 CodeGenFunction::destroyCXXObject,
310 CGF.getLangOpts().Exceptions);
314 llvm_unreachable("temporary cannot have dynamic storage duration");
319 createReferenceTemporary(CodeGenFunction &CGF,
320 const MaterializeTemporaryExpr *M, const Expr *Inner) {
321 switch (M->getStorageDuration()) {
322 case SD_FullExpression:
324 // If we have a constant temporary array or record try to promote it into a
325 // constant global under the same rules a normal constant would've been
326 // promoted. This is easier on the optimizer and generally emits fewer
328 QualType Ty = Inner->getType();
329 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
330 (Ty->isArrayType() || Ty->isRecordType()) &&
331 CGF.CGM.isTypeConstant(Ty, true))
332 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
333 auto *GV = new llvm::GlobalVariable(
334 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
335 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
336 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
337 GV->setAlignment(alignment.getQuantity());
338 // FIXME: Should we put the new global into a COMDAT?
339 return Address(GV, alignment);
341 return CGF.CreateMemTemp(Ty, "ref.tmp");
345 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
348 llvm_unreachable("temporary can't have dynamic storage duration");
350 llvm_unreachable("unknown storage duration");
353 LValue CodeGenFunction::
354 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
355 const Expr *E = M->GetTemporaryExpr();
357 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
358 // as that will cause the lifetime adjustment to be lost for ARC
359 auto ownership = M->getType().getObjCLifetime();
360 if (ownership != Qualifiers::OCL_None &&
361 ownership != Qualifiers::OCL_ExplicitNone) {
362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
369 // createReferenceTemporary will promote the temporary to a global with a
370 // constant initializer if it can. It can only do this to a value of
371 // ARC-manageable type if the value is global and therefore "immune" to
372 // ref-counting operations. Therefore we have no need to emit either a
373 // dynamic initialization or a cleanup and we can just return the address
375 if (Var->hasInitializer())
376 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
378 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
380 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
381 AlignmentSource::Decl);
383 switch (getEvaluationKind(E->getType())) {
384 default: llvm_unreachable("expected scalar or aggregate expression");
386 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
388 case TEK_Aggregate: {
389 EmitAggExpr(E, AggValueSlot::forAddr(Object,
390 E->getType().getQualifiers(),
391 AggValueSlot::IsDestructed,
392 AggValueSlot::DoesNotNeedGCBarriers,
393 AggValueSlot::IsNotAliased));
398 pushTemporaryCleanup(*this, M, E, Object);
402 SmallVector<const Expr *, 2> CommaLHSs;
403 SmallVector<SubobjectAdjustment, 2> Adjustments;
404 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
406 for (const auto &Ignored : CommaLHSs)
407 EmitIgnoredExpr(Ignored);
409 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
410 if (opaque->getType()->isRecordType()) {
411 assert(Adjustments.empty());
412 return EmitOpaqueValueLValue(opaque);
416 // Create and initialize the reference temporary.
417 Address Object = createReferenceTemporary(*this, M, E);
418 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
419 Object = Address(llvm::ConstantExpr::getBitCast(
420 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
421 Object.getAlignment());
422 // If the temporary is a global and has a constant initializer or is a
423 // constant temporary that we promoted to a global, we may have already
425 if (!Var->hasInitializer()) {
426 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
427 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
430 switch (M->getStorageDuration()) {
432 case SD_FullExpression:
433 if (auto *Size = EmitLifetimeStart(
434 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
435 Object.getPointer())) {
436 if (M->getStorageDuration() == SD_Automatic)
437 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
440 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
447 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
449 pushTemporaryCleanup(*this, M, E, Object);
451 // Perform derived-to-base casts and/or field accesses, to get from the
452 // temporary object we created (and, potentially, for which we extended
453 // the lifetime) to the subobject we're binding the reference to.
454 for (unsigned I = Adjustments.size(); I != 0; --I) {
455 SubobjectAdjustment &Adjustment = Adjustments[I-1];
456 switch (Adjustment.Kind) {
457 case SubobjectAdjustment::DerivedToBaseAdjustment:
459 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
460 Adjustment.DerivedToBase.BasePath->path_begin(),
461 Adjustment.DerivedToBase.BasePath->path_end(),
462 /*NullCheckValue=*/ false, E->getExprLoc());
465 case SubobjectAdjustment::FieldAdjustment: {
466 LValue LV = MakeAddrLValue(Object, E->getType(),
467 AlignmentSource::Decl);
468 LV = EmitLValueForField(LV, Adjustment.Field);
469 assert(LV.isSimple() &&
470 "materialized temporary field is not a simple lvalue");
471 Object = LV.getAddress();
475 case SubobjectAdjustment::MemberPointerAdjustment: {
476 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
477 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
484 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
488 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
489 // Emit the expression as an lvalue.
490 LValue LV = EmitLValue(E);
491 assert(LV.isSimple());
492 llvm::Value *Value = LV.getPointer();
494 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
495 // C++11 [dcl.ref]p5 (as amended by core issue 453):
496 // If a glvalue to which a reference is directly bound designates neither
497 // an existing object or function of an appropriate type nor a region of
498 // storage of suitable size and alignment to contain an object of the
499 // reference's type, the behavior is undefined.
500 QualType Ty = E->getType();
501 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
504 return RValue::get(Value);
508 /// getAccessedFieldNo - Given an encoded value and a result number, return the
509 /// input field number being accessed.
510 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
511 const llvm::Constant *Elts) {
512 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
516 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
517 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
519 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
520 llvm::Value *K47 = Builder.getInt64(47);
521 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
522 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
523 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
524 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
525 return Builder.CreateMul(B1, KMul);
528 bool CodeGenFunction::sanitizePerformTypeCheck() const {
529 return SanOpts.has(SanitizerKind::Null) |
530 SanOpts.has(SanitizerKind::Alignment) |
531 SanOpts.has(SanitizerKind::ObjectSize) |
532 SanOpts.has(SanitizerKind::Vptr);
535 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
536 llvm::Value *Ptr, QualType Ty,
537 CharUnits Alignment, bool SkipNullCheck) {
538 if (!sanitizePerformTypeCheck())
541 // Don't check pointers outside the default address space. The null check
542 // isn't correct, the object-size check isn't supported by LLVM, and we can't
543 // communicate the addresses to the runtime handler for the vptr check.
544 if (Ptr->getType()->getPointerAddressSpace())
547 SanitizerScope SanScope(this);
549 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
550 llvm::BasicBlock *Done = nullptr;
552 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
553 TCK == TCK_UpcastToVirtualBase;
554 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
556 // The glvalue must not be an empty glvalue.
557 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
559 if (AllowNullPointers) {
560 // When performing pointer casts, it's OK if the value is null.
561 // Skip the remaining checks in that case.
562 Done = createBasicBlock("null");
563 llvm::BasicBlock *Rest = createBasicBlock("not.null");
564 Builder.CreateCondBr(IsNonNull, Rest, Done);
567 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
571 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
572 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
574 // The glvalue must refer to a large enough storage region.
575 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
577 // FIXME: Get object address space
578 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
579 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
580 llvm::Value *Min = Builder.getFalse();
581 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
582 llvm::Value *LargeEnough =
583 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
584 llvm::ConstantInt::get(IntPtrTy, Size));
585 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
588 uint64_t AlignVal = 0;
590 if (SanOpts.has(SanitizerKind::Alignment)) {
591 AlignVal = Alignment.getQuantity();
592 if (!Ty->isIncompleteType() && !AlignVal)
593 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
595 // The glvalue must be suitably aligned.
598 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
599 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
600 llvm::Value *Aligned =
601 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
602 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
606 if (Checks.size() > 0) {
607 // Make sure we're not losing information. Alignment needs to be a power of
609 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
610 llvm::Constant *StaticData[] = {
611 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
612 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
613 llvm::ConstantInt::get(Int8Ty, TCK)};
614 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
617 // If possible, check that the vptr indicates that there is a subobject of
618 // type Ty at offset zero within this object.
620 // C++11 [basic.life]p5,6:
621 // [For storage which does not refer to an object within its lifetime]
622 // The program has undefined behavior if:
623 // -- the [pointer or glvalue] is used to access a non-static data member
624 // or call a non-static member function
625 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
626 if (SanOpts.has(SanitizerKind::Vptr) &&
627 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
628 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
629 TCK == TCK_UpcastToVirtualBase) &&
630 RD && RD->hasDefinition() && RD->isDynamicClass()) {
631 // Compute a hash of the mangled name of the type.
633 // FIXME: This is not guaranteed to be deterministic! Move to a
634 // fingerprinting mechanism once LLVM provides one. For the time
635 // being the implementation happens to be deterministic.
636 SmallString<64> MangledName;
637 llvm::raw_svector_ostream Out(MangledName);
638 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
641 // Blacklist based on the mangled type.
642 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
644 llvm::hash_code TypeHash = hash_value(Out.str());
646 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
647 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
648 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
649 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
650 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
651 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
653 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
654 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
656 // Look the hash up in our cache.
657 const int CacheSize = 128;
658 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
659 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
660 "__ubsan_vptr_type_cache");
661 llvm::Value *Slot = Builder.CreateAnd(Hash,
662 llvm::ConstantInt::get(IntPtrTy,
664 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
665 llvm::Value *CacheVal =
666 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
669 // If the hash isn't in the cache, call a runtime handler to perform the
670 // hard work of checking whether the vptr is for an object of the right
671 // type. This will either fill in the cache and return, or produce a
673 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
674 llvm::Constant *StaticData[] = {
675 EmitCheckSourceLocation(Loc),
676 EmitCheckTypeDescriptor(Ty),
677 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
678 llvm::ConstantInt::get(Int8Ty, TCK)
680 llvm::Value *DynamicData[] = { Ptr, Hash };
681 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
682 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
688 Builder.CreateBr(Done);
693 /// Determine whether this expression refers to a flexible array member in a
694 /// struct. We disable array bounds checks for such members.
695 static bool isFlexibleArrayMemberExpr(const Expr *E) {
696 // For compatibility with existing code, we treat arrays of length 0 or
697 // 1 as flexible array members.
698 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
699 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
700 if (CAT->getSize().ugt(1))
702 } else if (!isa<IncompleteArrayType>(AT))
705 E = E->IgnoreParens();
707 // A flexible array member must be the last member in the class.
708 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
709 // FIXME: If the base type of the member expr is not FD->getParent(),
710 // this should not be treated as a flexible array member access.
711 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
712 RecordDecl::field_iterator FI(
713 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
714 return ++FI == FD->getParent()->field_end();
716 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
717 return IRE->getDecl()->getNextIvar() == nullptr;
723 /// If Base is known to point to the start of an array, return the length of
724 /// that array. Return 0 if the length cannot be determined.
725 static llvm::Value *getArrayIndexingBound(
726 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
727 // For the vector indexing extension, the bound is the number of elements.
728 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
729 IndexedType = Base->getType();
730 return CGF.Builder.getInt32(VT->getNumElements());
733 Base = Base->IgnoreParens();
735 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
736 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
737 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
738 IndexedType = CE->getSubExpr()->getType();
739 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
740 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
741 return CGF.Builder.getInt(CAT->getSize());
742 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
743 return CGF.getVLASize(VAT).first;
750 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
751 llvm::Value *Index, QualType IndexType,
753 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
754 "should not be called unless adding bounds checks");
755 SanitizerScope SanScope(this);
757 QualType IndexedType;
758 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
762 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
763 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
764 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
766 llvm::Constant *StaticData[] = {
767 EmitCheckSourceLocation(E->getExprLoc()),
768 EmitCheckTypeDescriptor(IndexedType),
769 EmitCheckTypeDescriptor(IndexType)
771 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
772 : Builder.CreateICmpULE(IndexVal, BoundVal);
773 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
774 SanitizerHandler::OutOfBounds, StaticData, Index);
778 CodeGenFunction::ComplexPairTy CodeGenFunction::
779 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
780 bool isInc, bool isPre) {
781 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
783 llvm::Value *NextVal;
784 if (isa<llvm::IntegerType>(InVal.first->getType())) {
785 uint64_t AmountVal = isInc ? 1 : -1;
786 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
788 // Add the inc/dec to the real part.
789 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
791 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
792 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
795 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
797 // Add the inc/dec to the real part.
798 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
801 ComplexPairTy IncVal(NextVal, InVal.second);
803 // Store the updated result through the lvalue.
804 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
806 // If this is a postinc, return the value read from memory, otherwise use the
808 return isPre ? IncVal : InVal;
811 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
812 CodeGenFunction *CGF) {
813 // Bind VLAs in the cast type.
814 if (CGF && E->getType()->isVariablyModifiedType())
815 CGF->EmitVariablyModifiedType(E->getType());
817 if (CGDebugInfo *DI = getModuleDebugInfo())
818 DI->EmitExplicitCastType(E->getType());
821 //===----------------------------------------------------------------------===//
822 // LValue Expression Emission
823 //===----------------------------------------------------------------------===//
825 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
826 /// derive a more accurate bound on the alignment of the pointer.
827 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
828 AlignmentSource *Source) {
829 // We allow this with ObjC object pointers because of fragile ABIs.
830 assert(E->getType()->isPointerType() ||
831 E->getType()->isObjCObjectPointerType());
832 E = E->IgnoreParens();
835 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
836 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
837 CGM.EmitExplicitCastExprType(ECE, this);
839 switch (CE->getCastKind()) {
840 // Non-converting casts (but not C's implicit conversion from void*).
843 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
844 if (PtrTy->getPointeeType()->isVoidType())
847 AlignmentSource InnerSource;
848 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
849 if (Source) *Source = InnerSource;
851 // If this is an explicit bitcast, and the source l-value is
852 // opaque, honor the alignment of the casted-to type.
853 if (isa<ExplicitCastExpr>(CE) &&
854 InnerSource != AlignmentSource::Decl) {
855 Addr = Address(Addr.getPointer(),
856 getNaturalPointeeTypeAlignment(E->getType(), Source));
859 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
860 CE->getCastKind() == CK_BitCast) {
861 if (auto PT = E->getType()->getAs<PointerType>())
862 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
864 CodeGenFunction::CFITCK_UnrelatedCast,
868 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
872 // Array-to-pointer decay.
873 case CK_ArrayToPointerDecay:
874 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
876 // Derived-to-base conversions.
877 case CK_UncheckedDerivedToBase:
878 case CK_DerivedToBase: {
879 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
880 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
881 return GetAddressOfBaseClass(Addr, Derived,
882 CE->path_begin(), CE->path_end(),
883 ShouldNullCheckClassCastValue(CE),
887 // TODO: Is there any reason to treat base-to-derived conversions
895 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
896 if (UO->getOpcode() == UO_AddrOf) {
897 LValue LV = EmitLValue(UO->getSubExpr());
898 if (Source) *Source = LV.getAlignmentSource();
899 return LV.getAddress();
903 // TODO: conditional operators, comma.
905 // Otherwise, use the alignment of the type.
906 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
907 return Address(EmitScalarExpr(E), Align);
910 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
911 if (Ty->isVoidType())
912 return RValue::get(nullptr);
914 switch (getEvaluationKind(Ty)) {
917 ConvertType(Ty->castAs<ComplexType>()->getElementType());
918 llvm::Value *U = llvm::UndefValue::get(EltTy);
919 return RValue::getComplex(std::make_pair(U, U));
922 // If this is a use of an undefined aggregate type, the aggregate must have an
923 // identifiable address. Just because the contents of the value are undefined
924 // doesn't mean that the address can't be taken and compared.
925 case TEK_Aggregate: {
926 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
927 return RValue::getAggregate(DestPtr);
931 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
933 llvm_unreachable("bad evaluation kind");
936 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
938 ErrorUnsupported(E, Name);
939 return GetUndefRValue(E->getType());
942 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
944 ErrorUnsupported(E, Name);
945 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
946 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
950 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
952 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
953 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
956 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
957 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
958 E->getType(), LV.getAlignment());
962 /// EmitLValue - Emit code to compute a designator that specifies the location
963 /// of the expression.
965 /// This can return one of two things: a simple address or a bitfield reference.
966 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
967 /// an LLVM pointer type.
969 /// If this returns a bitfield reference, nothing about the pointee type of the
970 /// LLVM value is known: For example, it may not be a pointer to an integer.
972 /// If this returns a normal address, and if the lvalue's C type is fixed size,
973 /// this method guarantees that the returned pointer type will point to an LLVM
974 /// type of the same size of the lvalue's type. If the lvalue has a variable
975 /// length type, this is not possible.
977 LValue CodeGenFunction::EmitLValue(const Expr *E) {
978 ApplyDebugLocation DL(*this, E);
979 switch (E->getStmtClass()) {
980 default: return EmitUnsupportedLValue(E, "l-value expression");
982 case Expr::ObjCPropertyRefExprClass:
983 llvm_unreachable("cannot emit a property reference directly");
985 case Expr::ObjCSelectorExprClass:
986 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
987 case Expr::ObjCIsaExprClass:
988 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
989 case Expr::BinaryOperatorClass:
990 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
991 case Expr::CompoundAssignOperatorClass: {
992 QualType Ty = E->getType();
993 if (const AtomicType *AT = Ty->getAs<AtomicType>())
994 Ty = AT->getValueType();
995 if (!Ty->isAnyComplexType())
996 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
997 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
999 case Expr::CallExprClass:
1000 case Expr::CXXMemberCallExprClass:
1001 case Expr::CXXOperatorCallExprClass:
1002 case Expr::UserDefinedLiteralClass:
1003 return EmitCallExprLValue(cast<CallExpr>(E));
1004 case Expr::VAArgExprClass:
1005 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1006 case Expr::DeclRefExprClass:
1007 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1008 case Expr::ParenExprClass:
1009 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1010 case Expr::GenericSelectionExprClass:
1011 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1012 case Expr::PredefinedExprClass:
1013 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1014 case Expr::StringLiteralClass:
1015 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1016 case Expr::ObjCEncodeExprClass:
1017 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1018 case Expr::PseudoObjectExprClass:
1019 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1020 case Expr::InitListExprClass:
1021 return EmitInitListLValue(cast<InitListExpr>(E));
1022 case Expr::CXXTemporaryObjectExprClass:
1023 case Expr::CXXConstructExprClass:
1024 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1025 case Expr::CXXBindTemporaryExprClass:
1026 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1027 case Expr::CXXUuidofExprClass:
1028 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1029 case Expr::LambdaExprClass:
1030 return EmitLambdaLValue(cast<LambdaExpr>(E));
1032 case Expr::ExprWithCleanupsClass: {
1033 const auto *cleanups = cast<ExprWithCleanups>(E);
1034 enterFullExpression(cleanups);
1035 RunCleanupsScope Scope(*this);
1036 return EmitLValue(cleanups->getSubExpr());
1039 case Expr::CXXDefaultArgExprClass:
1040 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1041 case Expr::CXXDefaultInitExprClass: {
1042 CXXDefaultInitExprScope Scope(*this);
1043 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1045 case Expr::CXXTypeidExprClass:
1046 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1048 case Expr::ObjCMessageExprClass:
1049 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1050 case Expr::ObjCIvarRefExprClass:
1051 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1052 case Expr::StmtExprClass:
1053 return EmitStmtExprLValue(cast<StmtExpr>(E));
1054 case Expr::UnaryOperatorClass:
1055 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1056 case Expr::ArraySubscriptExprClass:
1057 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1058 case Expr::OMPArraySectionExprClass:
1059 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1060 case Expr::ExtVectorElementExprClass:
1061 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1062 case Expr::MemberExprClass:
1063 return EmitMemberExpr(cast<MemberExpr>(E));
1064 case Expr::CompoundLiteralExprClass:
1065 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1066 case Expr::ConditionalOperatorClass:
1067 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1068 case Expr::BinaryConditionalOperatorClass:
1069 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1070 case Expr::ChooseExprClass:
1071 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1072 case Expr::OpaqueValueExprClass:
1073 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1074 case Expr::SubstNonTypeTemplateParmExprClass:
1075 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1076 case Expr::ImplicitCastExprClass:
1077 case Expr::CStyleCastExprClass:
1078 case Expr::CXXFunctionalCastExprClass:
1079 case Expr::CXXStaticCastExprClass:
1080 case Expr::CXXDynamicCastExprClass:
1081 case Expr::CXXReinterpretCastExprClass:
1082 case Expr::CXXConstCastExprClass:
1083 case Expr::ObjCBridgedCastExprClass:
1084 return EmitCastLValue(cast<CastExpr>(E));
1086 case Expr::MaterializeTemporaryExprClass:
1087 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1091 /// Given an object of the given canonical type, can we safely copy a
1092 /// value out of it based on its initializer?
1093 static bool isConstantEmittableObjectType(QualType type) {
1094 assert(type.isCanonical());
1095 assert(!type->isReferenceType());
1097 // Must be const-qualified but non-volatile.
1098 Qualifiers qs = type.getLocalQualifiers();
1099 if (!qs.hasConst() || qs.hasVolatile()) return false;
1101 // Otherwise, all object types satisfy this except C++ classes with
1102 // mutable subobjects or non-trivial copy/destroy behavior.
1103 if (const auto *RT = dyn_cast<RecordType>(type))
1104 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1105 if (RD->hasMutableFields() || !RD->isTrivial())
1111 /// Can we constant-emit a load of a reference to a variable of the
1112 /// given type? This is different from predicates like
1113 /// Decl::isUsableInConstantExpressions because we do want it to apply
1114 /// in situations that don't necessarily satisfy the language's rules
1115 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1116 /// to do this with const float variables even if those variables
1117 /// aren't marked 'constexpr'.
1118 enum ConstantEmissionKind {
1120 CEK_AsReferenceOnly,
1121 CEK_AsValueOrReference,
1124 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1125 type = type.getCanonicalType();
1126 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1127 if (isConstantEmittableObjectType(ref->getPointeeType()))
1128 return CEK_AsValueOrReference;
1129 return CEK_AsReferenceOnly;
1131 if (isConstantEmittableObjectType(type))
1132 return CEK_AsValueOnly;
1136 /// Try to emit a reference to the given value without producing it as
1137 /// an l-value. This is actually more than an optimization: we can't
1138 /// produce an l-value for variables that we never actually captured
1139 /// in a block or lambda, which means const int variables or constexpr
1140 /// literals or similar.
1141 CodeGenFunction::ConstantEmission
1142 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1143 ValueDecl *value = refExpr->getDecl();
1145 // The value needs to be an enum constant or a constant variable.
1146 ConstantEmissionKind CEK;
1147 if (isa<ParmVarDecl>(value)) {
1149 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1150 CEK = checkVarTypeForConstantEmission(var->getType());
1151 } else if (isa<EnumConstantDecl>(value)) {
1152 CEK = CEK_AsValueOnly;
1156 if (CEK == CEK_None) return ConstantEmission();
1158 Expr::EvalResult result;
1159 bool resultIsReference;
1160 QualType resultType;
1162 // It's best to evaluate all the way as an r-value if that's permitted.
1163 if (CEK != CEK_AsReferenceOnly &&
1164 refExpr->EvaluateAsRValue(result, getContext())) {
1165 resultIsReference = false;
1166 resultType = refExpr->getType();
1168 // Otherwise, try to evaluate as an l-value.
1169 } else if (CEK != CEK_AsValueOnly &&
1170 refExpr->EvaluateAsLValue(result, getContext())) {
1171 resultIsReference = true;
1172 resultType = value->getType();
1176 return ConstantEmission();
1179 // In any case, if the initializer has side-effects, abandon ship.
1180 if (result.HasSideEffects)
1181 return ConstantEmission();
1183 // Emit as a constant.
1184 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1186 // Make sure we emit a debug reference to the global variable.
1187 // This should probably fire even for
1188 if (isa<VarDecl>(value)) {
1189 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1190 EmitDeclRefExprDbgValue(refExpr, result.Val);
1192 assert(isa<EnumConstantDecl>(value));
1193 EmitDeclRefExprDbgValue(refExpr, result.Val);
1196 // If we emitted a reference constant, we need to dereference that.
1197 if (resultIsReference)
1198 return ConstantEmission::forReference(C);
1200 return ConstantEmission::forValue(C);
1203 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1204 SourceLocation Loc) {
1205 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1206 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1207 lvalue.getTBAAInfo(),
1208 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1209 lvalue.isNontemporal());
1212 static bool hasBooleanRepresentation(QualType Ty) {
1213 if (Ty->isBooleanType())
1216 if (const EnumType *ET = Ty->getAs<EnumType>())
1217 return ET->getDecl()->getIntegerType()->isBooleanType();
1219 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1220 return hasBooleanRepresentation(AT->getValueType());
1225 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1226 llvm::APInt &Min, llvm::APInt &End,
1227 bool StrictEnums, bool IsBool) {
1228 const EnumType *ET = Ty->getAs<EnumType>();
1229 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1230 ET && !ET->getDecl()->isFixed();
1231 if (!IsBool && !IsRegularCPlusPlusEnum)
1235 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1236 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1238 const EnumDecl *ED = ET->getDecl();
1239 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1240 unsigned Bitwidth = LTy->getScalarSizeInBits();
1241 unsigned NumNegativeBits = ED->getNumNegativeBits();
1242 unsigned NumPositiveBits = ED->getNumPositiveBits();
1244 if (NumNegativeBits) {
1245 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1246 assert(NumBits <= Bitwidth);
1247 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1250 assert(NumPositiveBits <= Bitwidth);
1251 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1252 Min = llvm::APInt(Bitwidth, 0);
1258 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1259 llvm::APInt Min, End;
1260 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1261 hasBooleanRepresentation(Ty)))
1264 llvm::MDBuilder MDHelper(getLLVMContext());
1265 return MDHelper.createRange(Min, End);
1268 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1271 AlignmentSource AlignSource,
1272 llvm::MDNode *TBAAInfo,
1273 QualType TBAABaseType,
1274 uint64_t TBAAOffset,
1275 bool isNontemporal) {
1276 // For better performance, handle vector loads differently.
1277 if (Ty->isVectorType()) {
1278 const llvm::Type *EltTy = Addr.getElementType();
1280 const auto *VTy = cast<llvm::VectorType>(EltTy);
1282 // Handle vectors of size 3 like size 4 for better performance.
1283 if (VTy->getNumElements() == 3) {
1285 // Bitcast to vec4 type.
1286 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1288 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1290 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1292 // Shuffle vector to get vec3.
1293 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1294 {0, 1, 2}, "extractVec");
1295 return EmitFromMemory(V, Ty);
1299 // Atomic operations have to be done on integral types.
1300 LValue AtomicLValue =
1301 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1302 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1303 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1306 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1307 if (isNontemporal) {
1308 llvm::MDNode *Node = llvm::MDNode::get(
1309 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1310 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1313 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1316 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1317 false /*ConvertTypeToTag*/);
1320 bool IsBool = hasBooleanRepresentation(Ty) ||
1321 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1322 bool NeedsBoolCheck = SanOpts.has(SanitizerKind::Bool) && IsBool;
1323 bool NeedsEnumCheck =
1324 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1325 if (NeedsBoolCheck || NeedsEnumCheck) {
1326 SanitizerScope SanScope(this);
1327 llvm::APInt Min, End;
1328 if (getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) {
1332 Check = Builder.CreateICmpULE(
1333 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1335 llvm::Value *Upper = Builder.CreateICmpSLE(
1336 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1337 llvm::Value *Lower = Builder.CreateICmpSGE(
1338 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1339 Check = Builder.CreateAnd(Upper, Lower);
1341 llvm::Constant *StaticArgs[] = {
1342 EmitCheckSourceLocation(Loc),
1343 EmitCheckTypeDescriptor(Ty)
1345 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1346 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1347 StaticArgs, EmitCheckValue(Load));
1349 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1350 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1351 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1353 return EmitFromMemory(Load, Ty);
1356 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1357 // Bool has a different representation in memory than in registers.
1358 if (hasBooleanRepresentation(Ty)) {
1359 // This should really always be an i1, but sometimes it's already
1360 // an i8, and it's awkward to track those cases down.
1361 if (Value->getType()->isIntegerTy(1))
1362 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1363 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1364 "wrong value rep of bool");
1370 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1371 // Bool has a different representation in memory than in registers.
1372 if (hasBooleanRepresentation(Ty)) {
1373 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1374 "wrong value rep of bool");
1375 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1381 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1382 bool Volatile, QualType Ty,
1383 AlignmentSource AlignSource,
1384 llvm::MDNode *TBAAInfo,
1385 bool isInit, QualType TBAABaseType,
1386 uint64_t TBAAOffset,
1387 bool isNontemporal) {
1389 // Handle vectors differently to get better performance.
1390 if (Ty->isVectorType()) {
1391 llvm::Type *SrcTy = Value->getType();
1392 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1393 // Handle vec3 special.
1394 if (VecTy->getNumElements() == 3) {
1395 // Our source is a vec3, do a shuffle vector to make it a vec4.
1396 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1397 Builder.getInt32(2),
1398 llvm::UndefValue::get(Builder.getInt32Ty())};
1399 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1400 Value = Builder.CreateShuffleVector(Value,
1401 llvm::UndefValue::get(VecTy),
1402 MaskV, "extractVec");
1403 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1405 if (Addr.getElementType() != SrcTy) {
1406 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1410 Value = EmitToMemory(Value, Ty);
1412 LValue AtomicLValue =
1413 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1414 if (Ty->isAtomicType() ||
1415 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1416 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1420 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1421 if (isNontemporal) {
1422 llvm::MDNode *Node =
1423 llvm::MDNode::get(Store->getContext(),
1424 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1425 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1428 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1431 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1432 false /*ConvertTypeToTag*/);
1436 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1438 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1439 lvalue.getType(), lvalue.getAlignmentSource(),
1440 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1441 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1444 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1445 /// method emits the address of the lvalue, then loads the result as an rvalue,
1446 /// returning the rvalue.
1447 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1448 if (LV.isObjCWeak()) {
1449 // load of a __weak object.
1450 Address AddrWeakObj = LV.getAddress();
1451 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1454 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1455 // In MRC mode, we do a load+autorelease.
1456 if (!getLangOpts().ObjCAutoRefCount) {
1457 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1460 // In ARC mode, we load retained and then consume the value.
1461 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1462 Object = EmitObjCConsumeObject(LV.getType(), Object);
1463 return RValue::get(Object);
1466 if (LV.isSimple()) {
1467 assert(!LV.getType()->isFunctionType());
1469 // Everything needs a load.
1470 return RValue::get(EmitLoadOfScalar(LV, Loc));
1473 if (LV.isVectorElt()) {
1474 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1475 LV.isVolatileQualified());
1476 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1480 // If this is a reference to a subset of the elements of a vector, either
1481 // shuffle the input or extract/insert them as appropriate.
1482 if (LV.isExtVectorElt())
1483 return EmitLoadOfExtVectorElementLValue(LV);
1485 // Global Register variables always invoke intrinsics
1486 if (LV.isGlobalReg())
1487 return EmitLoadOfGlobalRegLValue(LV);
1489 assert(LV.isBitField() && "Unknown LValue type!");
1490 return EmitLoadOfBitfieldLValue(LV);
1493 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1494 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1496 // Get the output type.
1497 llvm::Type *ResLTy = ConvertType(LV.getType());
1499 Address Ptr = LV.getBitFieldAddress();
1500 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1502 if (Info.IsSigned) {
1503 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1504 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1506 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1507 if (Info.Offset + HighBits)
1508 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1511 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1512 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1513 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1517 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1519 return RValue::get(Val);
1522 // If this is a reference to a subset of the elements of a vector, create an
1523 // appropriate shufflevector.
1524 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1525 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1526 LV.isVolatileQualified());
1528 const llvm::Constant *Elts = LV.getExtVectorElts();
1530 // If the result of the expression is a non-vector type, we must be extracting
1531 // a single element. Just codegen as an extractelement.
1532 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1534 unsigned InIdx = getAccessedFieldNo(0, Elts);
1535 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1536 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1539 // Always use shuffle vector to try to retain the original program structure
1540 unsigned NumResultElts = ExprVT->getNumElements();
1542 SmallVector<llvm::Constant*, 4> Mask;
1543 for (unsigned i = 0; i != NumResultElts; ++i)
1544 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1546 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1547 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1549 return RValue::get(Vec);
1552 /// @brief Generates lvalue for partial ext_vector access.
1553 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1554 Address VectorAddress = LV.getExtVectorAddress();
1555 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1556 QualType EQT = ExprVT->getElementType();
1557 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1559 Address CastToPointerElement =
1560 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1561 "conv.ptr.element");
1563 const llvm::Constant *Elts = LV.getExtVectorElts();
1564 unsigned ix = getAccessedFieldNo(0, Elts);
1566 Address VectorBasePtrPlusIx =
1567 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1568 getContext().getTypeSizeInChars(EQT),
1571 return VectorBasePtrPlusIx;
1574 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1575 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1576 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1577 "Bad type for register variable");
1578 llvm::MDNode *RegName = cast<llvm::MDNode>(
1579 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1581 // We accept integer and pointer types only
1582 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1583 llvm::Type *Ty = OrigTy;
1584 if (OrigTy->isPointerTy())
1585 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1586 llvm::Type *Types[] = { Ty };
1588 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1589 llvm::Value *Call = Builder.CreateCall(
1590 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1591 if (OrigTy->isPointerTy())
1592 Call = Builder.CreateIntToPtr(Call, OrigTy);
1593 return RValue::get(Call);
1597 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1598 /// lvalue, where both are guaranteed to the have the same type, and that type
1600 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1602 if (!Dst.isSimple()) {
1603 if (Dst.isVectorElt()) {
1604 // Read/modify/write the vector, inserting the new element.
1605 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1606 Dst.isVolatileQualified());
1607 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1608 Dst.getVectorIdx(), "vecins");
1609 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1610 Dst.isVolatileQualified());
1614 // If this is an update of extended vector elements, insert them as
1616 if (Dst.isExtVectorElt())
1617 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1619 if (Dst.isGlobalReg())
1620 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1622 assert(Dst.isBitField() && "Unknown LValue type");
1623 return EmitStoreThroughBitfieldLValue(Src, Dst);
1626 // There's special magic for assigning into an ARC-qualified l-value.
1627 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1629 case Qualifiers::OCL_None:
1630 llvm_unreachable("present but none");
1632 case Qualifiers::OCL_ExplicitNone:
1636 case Qualifiers::OCL_Strong:
1638 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1641 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1644 case Qualifiers::OCL_Weak:
1646 // Initialize and then skip the primitive store.
1647 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1649 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1652 case Qualifiers::OCL_Autoreleasing:
1653 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1654 Src.getScalarVal()));
1655 // fall into the normal path
1660 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1661 // load of a __weak object.
1662 Address LvalueDst = Dst.getAddress();
1663 llvm::Value *src = Src.getScalarVal();
1664 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1668 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1669 // load of a __strong object.
1670 Address LvalueDst = Dst.getAddress();
1671 llvm::Value *src = Src.getScalarVal();
1672 if (Dst.isObjCIvar()) {
1673 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1674 llvm::Type *ResultType = IntPtrTy;
1675 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1676 llvm::Value *RHS = dst.getPointer();
1677 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1679 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1680 "sub.ptr.lhs.cast");
1681 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1682 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1684 } else if (Dst.isGlobalObjCRef()) {
1685 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1686 Dst.isThreadLocalRef());
1689 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1693 assert(Src.isScalar() && "Can't emit an agg store with this method");
1694 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1697 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1698 llvm::Value **Result) {
1699 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1700 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1701 Address Ptr = Dst.getBitFieldAddress();
1703 // Get the source value, truncated to the width of the bit-field.
1704 llvm::Value *SrcVal = Src.getScalarVal();
1706 // Cast the source to the storage type and shift it into place.
1707 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1708 /*IsSigned=*/false);
1709 llvm::Value *MaskedVal = SrcVal;
1711 // See if there are other bits in the bitfield's storage we'll need to load
1712 // and mask together with source before storing.
1713 if (Info.StorageSize != Info.Size) {
1714 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1716 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1718 // Mask the source value as needed.
1719 if (!hasBooleanRepresentation(Dst.getType()))
1720 SrcVal = Builder.CreateAnd(SrcVal,
1721 llvm::APInt::getLowBitsSet(Info.StorageSize,
1726 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1728 // Mask out the original value.
1729 Val = Builder.CreateAnd(Val,
1730 ~llvm::APInt::getBitsSet(Info.StorageSize,
1732 Info.Offset + Info.Size),
1735 // Or together the unchanged values and the source value.
1736 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1738 assert(Info.Offset == 0);
1741 // Write the new value back out.
1742 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1744 // Return the new value of the bit-field, if requested.
1746 llvm::Value *ResultVal = MaskedVal;
1748 // Sign extend the value if needed.
1749 if (Info.IsSigned) {
1750 assert(Info.Size <= Info.StorageSize);
1751 unsigned HighBits = Info.StorageSize - Info.Size;
1753 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1754 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1758 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1760 *Result = EmitFromMemory(ResultVal, Dst.getType());
1764 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1766 // This access turns into a read/modify/write of the vector. Load the input
1768 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1769 Dst.isVolatileQualified());
1770 const llvm::Constant *Elts = Dst.getExtVectorElts();
1772 llvm::Value *SrcVal = Src.getScalarVal();
1774 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1775 unsigned NumSrcElts = VTy->getNumElements();
1776 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1777 if (NumDstElts == NumSrcElts) {
1778 // Use shuffle vector is the src and destination are the same number of
1779 // elements and restore the vector mask since it is on the side it will be
1781 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1782 for (unsigned i = 0; i != NumSrcElts; ++i)
1783 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1785 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1786 Vec = Builder.CreateShuffleVector(SrcVal,
1787 llvm::UndefValue::get(Vec->getType()),
1789 } else if (NumDstElts > NumSrcElts) {
1790 // Extended the source vector to the same length and then shuffle it
1791 // into the destination.
1792 // FIXME: since we're shuffling with undef, can we just use the indices
1793 // into that? This could be simpler.
1794 SmallVector<llvm::Constant*, 4> ExtMask;
1795 for (unsigned i = 0; i != NumSrcElts; ++i)
1796 ExtMask.push_back(Builder.getInt32(i));
1797 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1798 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1799 llvm::Value *ExtSrcVal =
1800 Builder.CreateShuffleVector(SrcVal,
1801 llvm::UndefValue::get(SrcVal->getType()),
1804 SmallVector<llvm::Constant*, 4> Mask;
1805 for (unsigned i = 0; i != NumDstElts; ++i)
1806 Mask.push_back(Builder.getInt32(i));
1808 // When the vector size is odd and .odd or .hi is used, the last element
1809 // of the Elts constant array will be one past the size of the vector.
1810 // Ignore the last element here, if it is greater than the mask size.
1811 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1814 // modify when what gets shuffled in
1815 for (unsigned i = 0; i != NumSrcElts; ++i)
1816 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1817 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1818 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1820 // We should never shorten the vector
1821 llvm_unreachable("unexpected shorten vector length");
1824 // If the Src is a scalar (not a vector) it must be updating one element.
1825 unsigned InIdx = getAccessedFieldNo(0, Elts);
1826 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1827 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1830 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1831 Dst.isVolatileQualified());
1834 /// @brief Store of global named registers are always calls to intrinsics.
1835 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1836 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1837 "Bad type for register variable");
1838 llvm::MDNode *RegName = cast<llvm::MDNode>(
1839 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1840 assert(RegName && "Register LValue is not metadata");
1842 // We accept integer and pointer types only
1843 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1844 llvm::Type *Ty = OrigTy;
1845 if (OrigTy->isPointerTy())
1846 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1847 llvm::Type *Types[] = { Ty };
1849 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1850 llvm::Value *Value = Src.getScalarVal();
1851 if (OrigTy->isPointerTy())
1852 Value = Builder.CreatePtrToInt(Value, Ty);
1854 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1857 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1858 // generating write-barries API. It is currently a global, ivar,
1860 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1862 bool IsMemberAccess=false) {
1863 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1866 if (isa<ObjCIvarRefExpr>(E)) {
1867 QualType ExpTy = E->getType();
1868 if (IsMemberAccess && ExpTy->isPointerType()) {
1869 // If ivar is a structure pointer, assigning to field of
1870 // this struct follows gcc's behavior and makes it a non-ivar
1871 // writer-barrier conservatively.
1872 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1873 if (ExpTy->isRecordType()) {
1874 LV.setObjCIvar(false);
1878 LV.setObjCIvar(true);
1879 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1880 LV.setBaseIvarExp(Exp->getBase());
1881 LV.setObjCArray(E->getType()->isArrayType());
1885 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1886 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1887 if (VD->hasGlobalStorage()) {
1888 LV.setGlobalObjCRef(true);
1889 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1892 LV.setObjCArray(E->getType()->isArrayType());
1896 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1897 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1901 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1902 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1903 if (LV.isObjCIvar()) {
1904 // If cast is to a structure pointer, follow gcc's behavior and make it
1905 // a non-ivar write-barrier.
1906 QualType ExpTy = E->getType();
1907 if (ExpTy->isPointerType())
1908 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1909 if (ExpTy->isRecordType())
1910 LV.setObjCIvar(false);
1915 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1916 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1920 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1921 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1925 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1926 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1930 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1931 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1935 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1936 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1937 if (LV.isObjCIvar() && !LV.isObjCArray())
1938 // Using array syntax to assigning to what an ivar points to is not
1939 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1940 LV.setObjCIvar(false);
1941 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1942 // Using array syntax to assigning to what global points to is not
1943 // same as assigning to the global itself. {id *G;} G[i] = 0;
1944 LV.setGlobalObjCRef(false);
1948 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
1949 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1950 // We don't know if member is an 'ivar', but this flag is looked at
1951 // only in the context of LV.isObjCIvar().
1952 LV.setObjCArray(E->getType()->isArrayType());
1957 static llvm::Value *
1958 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1959 llvm::Value *V, llvm::Type *IRType,
1960 StringRef Name = StringRef()) {
1961 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1962 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1965 static LValue EmitThreadPrivateVarDeclLValue(
1966 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1967 llvm::Type *RealVarTy, SourceLocation Loc) {
1968 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1969 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1970 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1973 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1974 const ReferenceType *RefTy,
1975 AlignmentSource *Source) {
1976 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1977 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1978 Source, /*forPointee*/ true));
1982 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1983 const ReferenceType *RefTy) {
1984 AlignmentSource Source;
1985 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1986 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
1989 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1990 const PointerType *PtrTy,
1991 AlignmentSource *Source) {
1992 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1993 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1994 /*forPointeeType=*/true));
1997 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1998 const PointerType *PtrTy) {
1999 AlignmentSource Source;
2000 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2001 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2004 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2005 const Expr *E, const VarDecl *VD) {
2006 QualType T = E->getType();
2008 // If it's thread_local, emit a call to its wrapper function instead.
2009 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2010 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2011 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2013 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2014 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2015 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2016 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2017 Address Addr(V, Alignment);
2019 // Emit reference to the private copy of the variable if it is an OpenMP
2020 // threadprivate variable.
2021 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2022 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2024 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2025 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2027 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2029 setObjCGCLValueClass(CGF.getContext(), E, LV);
2033 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2034 const FunctionDecl *FD) {
2035 if (FD->hasAttr<WeakRefAttr>()) {
2036 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2037 return aliasee.getPointer();
2040 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2041 if (!FD->hasPrototype()) {
2042 if (const FunctionProtoType *Proto =
2043 FD->getType()->getAs<FunctionProtoType>()) {
2044 // Ugly case: for a K&R-style definition, the type of the definition
2045 // isn't the same as the type of a use. Correct for this with a
2047 QualType NoProtoType =
2048 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2049 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2050 V = llvm::ConstantExpr::getBitCast(V,
2051 CGM.getTypes().ConvertType(NoProtoType));
2057 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2058 const Expr *E, const FunctionDecl *FD) {
2059 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2060 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2061 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2064 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2065 llvm::Value *ThisValue) {
2066 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2067 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2068 return CGF.EmitLValueForField(LV, FD);
2071 /// Named Registers are named metadata pointing to the register name
2072 /// which will be read from/written to as an argument to the intrinsic
2073 /// @llvm.read/write_register.
2074 /// So far, only the name is being passed down, but other options such as
2075 /// register type, allocation type or even optimization options could be
2076 /// passed down via the metadata node.
2077 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2078 SmallString<64> Name("llvm.named.register.");
2079 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2080 assert(Asm->getLabel().size() < 64-Name.size() &&
2081 "Register name too big");
2082 Name.append(Asm->getLabel());
2083 llvm::NamedMDNode *M =
2084 CGM.getModule().getOrInsertNamedMetadata(Name);
2085 if (M->getNumOperands() == 0) {
2086 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2088 llvm::Metadata *Ops[] = {Str};
2089 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2092 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2095 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2096 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2099 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2100 const NamedDecl *ND = E->getDecl();
2101 QualType T = E->getType();
2103 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2104 // Global Named registers access via intrinsics only
2105 if (VD->getStorageClass() == SC_Register &&
2106 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2107 return EmitGlobalNamedRegister(VD, CGM);
2109 // A DeclRefExpr for a reference initialized by a constant expression can
2110 // appear without being odr-used. Directly emit the constant initializer.
2111 const Expr *Init = VD->getAnyInitializer(VD);
2112 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2113 VD->isUsableInConstantExpressions(getContext()) &&
2114 VD->checkInitIsICE() &&
2115 // Do not emit if it is private OpenMP variable.
2116 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2117 LocalDeclMap.count(VD))) {
2118 llvm::Constant *Val =
2119 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2120 assert(Val && "failed to emit reference constant expression");
2121 // FIXME: Eventually we will want to emit vector element references.
2123 // Should we be using the alignment of the constant pointer we emitted?
2124 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2127 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2130 // Check for captured variables.
2131 if (E->refersToEnclosingVariableOrCapture()) {
2132 if (auto *FD = LambdaCaptureFields.lookup(VD))
2133 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2134 else if (CapturedStmtInfo) {
2135 auto I = LocalDeclMap.find(VD);
2136 if (I != LocalDeclMap.end()) {
2137 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2138 return EmitLoadOfReferenceLValue(I->second, RefTy);
2139 return MakeAddrLValue(I->second, T);
2142 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2143 CapturedStmtInfo->getContextValue());
2144 return MakeAddrLValue(
2145 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2146 CapLVal.getType(), AlignmentSource::Decl);
2149 assert(isa<BlockDecl>(CurCodeDecl));
2150 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2151 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2155 // FIXME: We should be able to assert this for FunctionDecls as well!
2156 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2157 // those with a valid source location.
2158 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2159 !E->getLocation().isValid()) &&
2160 "Should not use decl without marking it used!");
2162 if (ND->hasAttr<WeakRefAttr>()) {
2163 const auto *VD = cast<ValueDecl>(ND);
2164 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2165 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2168 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2169 // Check if this is a global variable.
2170 if (VD->hasLinkage() || VD->isStaticDataMember())
2171 return EmitGlobalVarDeclLValue(*this, E, VD);
2173 Address addr = Address::invalid();
2175 // The variable should generally be present in the local decl map.
2176 auto iter = LocalDeclMap.find(VD);
2177 if (iter != LocalDeclMap.end()) {
2178 addr = iter->second;
2180 // Otherwise, it might be static local we haven't emitted yet for
2181 // some reason; most likely, because it's in an outer function.
2182 } else if (VD->isStaticLocal()) {
2183 addr = Address(CGM.getOrCreateStaticVarDecl(
2184 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2185 getContext().getDeclAlign(VD));
2187 // No other cases for now.
2189 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2193 // Check for OpenMP threadprivate variables.
2194 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2195 return EmitThreadPrivateVarDeclLValue(
2196 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2200 // Drill into block byref variables.
2201 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2203 addr = emitBlockByrefAddress(addr, VD);
2206 // Drill into reference types.
2208 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2209 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2211 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2214 bool isLocalStorage = VD->hasLocalStorage();
2216 bool NonGCable = isLocalStorage &&
2217 !VD->getType()->isReferenceType() &&
2220 LV.getQuals().removeObjCGCAttr();
2224 bool isImpreciseLifetime =
2225 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2226 if (isImpreciseLifetime)
2227 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2228 setObjCGCLValueClass(getContext(), E, LV);
2232 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2233 return EmitFunctionDeclLValue(*this, E, FD);
2235 // FIXME: While we're emitting a binding from an enclosing scope, all other
2236 // DeclRefExprs we see should be implicitly treated as if they also refer to
2237 // an enclosing scope.
2238 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2239 return EmitLValue(BD->getBinding());
2241 llvm_unreachable("Unhandled DeclRefExpr");
2244 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2245 // __extension__ doesn't affect lvalue-ness.
2246 if (E->getOpcode() == UO_Extension)
2247 return EmitLValue(E->getSubExpr());
2249 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2250 switch (E->getOpcode()) {
2251 default: llvm_unreachable("Unknown unary operator lvalue!");
2253 QualType T = E->getSubExpr()->getType()->getPointeeType();
2254 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2256 AlignmentSource AlignSource;
2257 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2258 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2259 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2261 // We should not generate __weak write barrier on indirect reference
2262 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2263 // But, we continue to generate __strong write barrier on indirect write
2264 // into a pointer to object.
2265 if (getLangOpts().ObjC1 &&
2266 getLangOpts().getGC() != LangOptions::NonGC &&
2268 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2273 LValue LV = EmitLValue(E->getSubExpr());
2274 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2276 // __real is valid on scalars. This is a faster way of testing that.
2277 // __imag can only produce an rvalue on scalars.
2278 if (E->getOpcode() == UO_Real &&
2279 !LV.getAddress().getElementType()->isStructTy()) {
2280 assert(E->getSubExpr()->getType()->isArithmeticType());
2284 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2287 (E->getOpcode() == UO_Real
2288 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2289 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2290 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2291 ElemLV.getQuals().addQualifiers(LV.getQuals());
2296 LValue LV = EmitLValue(E->getSubExpr());
2297 bool isInc = E->getOpcode() == UO_PreInc;
2299 if (E->getType()->isAnyComplexType())
2300 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2302 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2308 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2309 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2310 E->getType(), AlignmentSource::Decl);
2313 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2314 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2315 E->getType(), AlignmentSource::Decl);
2318 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2319 auto SL = E->getFunctionName();
2320 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2321 StringRef FnName = CurFn->getName();
2322 if (FnName.startswith("\01"))
2323 FnName = FnName.substr(1);
2324 StringRef NameItems[] = {
2325 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2326 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2327 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2328 std::string Name = SL->getString();
2329 if (!Name.empty()) {
2330 unsigned Discriminator =
2331 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2333 Name += "_" + Twine(Discriminator + 1).str();
2334 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2335 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2337 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2338 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2341 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2342 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2345 /// Emit a type description suitable for use by a runtime sanitizer library. The
2346 /// format of a type descriptor is
2349 /// { i16 TypeKind, i16 TypeInfo }
2352 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2353 /// integer, 1 for a floating point value, and -1 for anything else.
2354 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2355 // Only emit each type's descriptor once.
2356 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2359 uint16_t TypeKind = -1;
2360 uint16_t TypeInfo = 0;
2362 if (T->isIntegerType()) {
2364 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2365 (T->isSignedIntegerType() ? 1 : 0);
2366 } else if (T->isFloatingType()) {
2368 TypeInfo = getContext().getTypeSize(T);
2371 // Format the type name as if for a diagnostic, including quotes and
2372 // optionally an 'aka'.
2373 SmallString<32> Buffer;
2374 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2375 (intptr_t)T.getAsOpaquePtr(),
2376 StringRef(), StringRef(), None, Buffer,
2379 llvm::Constant *Components[] = {
2380 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2381 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2383 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2385 auto *GV = new llvm::GlobalVariable(
2386 CGM.getModule(), Descriptor->getType(),
2387 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2388 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2389 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2391 // Remember the descriptor for this type.
2392 CGM.setTypeDescriptorInMap(T, GV);
2397 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2398 llvm::Type *TargetTy = IntPtrTy;
2400 // Floating-point types which fit into intptr_t are bitcast to integers
2401 // and then passed directly (after zero-extension, if necessary).
2402 if (V->getType()->isFloatingPointTy()) {
2403 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2404 if (Bits <= TargetTy->getIntegerBitWidth())
2405 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2409 // Integers which fit in intptr_t are zero-extended and passed directly.
2410 if (V->getType()->isIntegerTy() &&
2411 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2412 return Builder.CreateZExt(V, TargetTy);
2414 // Pointers are passed directly, everything else is passed by address.
2415 if (!V->getType()->isPointerTy()) {
2416 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2417 Builder.CreateStore(V, Ptr);
2418 V = Ptr.getPointer();
2420 return Builder.CreatePtrToInt(V, TargetTy);
2423 /// \brief Emit a representation of a SourceLocation for passing to a handler
2424 /// in a sanitizer runtime library. The format for this data is:
2426 /// struct SourceLocation {
2427 /// const char *Filename;
2428 /// int32_t Line, Column;
2431 /// For an invalid SourceLocation, the Filename pointer is null.
2432 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2433 llvm::Constant *Filename;
2436 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2437 if (PLoc.isValid()) {
2438 StringRef FilenameString = PLoc.getFilename();
2440 int PathComponentsToStrip =
2441 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2442 if (PathComponentsToStrip < 0) {
2443 assert(PathComponentsToStrip != INT_MIN);
2444 int PathComponentsToKeep = -PathComponentsToStrip;
2445 auto I = llvm::sys::path::rbegin(FilenameString);
2446 auto E = llvm::sys::path::rend(FilenameString);
2447 while (I != E && --PathComponentsToKeep)
2450 FilenameString = FilenameString.substr(I - E);
2451 } else if (PathComponentsToStrip > 0) {
2452 auto I = llvm::sys::path::begin(FilenameString);
2453 auto E = llvm::sys::path::end(FilenameString);
2454 while (I != E && PathComponentsToStrip--)
2459 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2461 FilenameString = llvm::sys::path::filename(FilenameString);
2464 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2465 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2466 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2467 Filename = FilenameGV.getPointer();
2468 Line = PLoc.getLine();
2469 Column = PLoc.getColumn();
2471 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2475 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2476 Builder.getInt32(Column)};
2478 return llvm::ConstantStruct::getAnon(Data);
2482 /// \brief Specify under what conditions this check can be recovered
2483 enum class CheckRecoverableKind {
2484 /// Always terminate program execution if this check fails.
2486 /// Check supports recovering, runtime has both fatal (noreturn) and
2487 /// non-fatal handlers for this check.
2489 /// Runtime conditionally aborts, always need to support recovery.
2494 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2495 assert(llvm::countPopulation(Kind) == 1);
2497 case SanitizerKind::Vptr:
2498 return CheckRecoverableKind::AlwaysRecoverable;
2499 case SanitizerKind::Return:
2500 case SanitizerKind::Unreachable:
2501 return CheckRecoverableKind::Unrecoverable;
2503 return CheckRecoverableKind::Recoverable;
2508 struct SanitizerHandlerInfo {
2509 char const *const Name;
2514 const SanitizerHandlerInfo SanitizerHandlers[] = {
2515 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2516 LIST_SANITIZER_CHECKS
2517 #undef SANITIZER_CHECK
2520 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2521 llvm::FunctionType *FnType,
2522 ArrayRef<llvm::Value *> FnArgs,
2523 SanitizerHandler CheckHandler,
2524 CheckRecoverableKind RecoverKind, bool IsFatal,
2525 llvm::BasicBlock *ContBB) {
2526 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2527 bool NeedsAbortSuffix =
2528 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2529 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2530 const StringRef CheckName = CheckInfo.Name;
2531 std::string FnName =
2532 ("__ubsan_handle_" + CheckName +
2533 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2534 (NeedsAbortSuffix ? "_abort" : ""))
2537 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2539 llvm::AttrBuilder B;
2541 B.addAttribute(llvm::Attribute::NoReturn)
2542 .addAttribute(llvm::Attribute::NoUnwind);
2544 B.addAttribute(llvm::Attribute::UWTable);
2546 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2548 llvm::AttributeSet::get(CGF.getLLVMContext(),
2549 llvm::AttributeSet::FunctionIndex, B),
2551 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2553 HandlerCall->setDoesNotReturn();
2554 CGF.Builder.CreateUnreachable();
2556 CGF.Builder.CreateBr(ContBB);
2560 void CodeGenFunction::EmitCheck(
2561 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2562 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2563 ArrayRef<llvm::Value *> DynamicArgs) {
2564 assert(IsSanitizerScope);
2565 assert(Checked.size() > 0);
2566 assert(CheckHandler >= 0 &&
2567 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2568 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2570 llvm::Value *FatalCond = nullptr;
2571 llvm::Value *RecoverableCond = nullptr;
2572 llvm::Value *TrapCond = nullptr;
2573 for (int i = 0, n = Checked.size(); i < n; ++i) {
2574 llvm::Value *Check = Checked[i].first;
2575 // -fsanitize-trap= overrides -fsanitize-recover=.
2576 llvm::Value *&Cond =
2577 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2579 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2582 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2586 EmitTrapCheck(TrapCond);
2587 if (!FatalCond && !RecoverableCond)
2590 llvm::Value *JointCond;
2591 if (FatalCond && RecoverableCond)
2592 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2594 JointCond = FatalCond ? FatalCond : RecoverableCond;
2597 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2598 assert(SanOpts.has(Checked[0].second));
2600 for (int i = 1, n = Checked.size(); i < n; ++i) {
2601 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2602 "All recoverable kinds in a single check must be same!");
2603 assert(SanOpts.has(Checked[i].second));
2607 llvm::BasicBlock *Cont = createBasicBlock("cont");
2608 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2609 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2610 // Give hint that we very much don't expect to execute the handler
2611 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2612 llvm::MDBuilder MDHelper(getLLVMContext());
2613 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2614 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2615 EmitBlock(Handlers);
2617 // Handler functions take an i8* pointing to the (handler-specific) static
2618 // information block, followed by a sequence of intptr_t arguments
2619 // representing operand values.
2620 SmallVector<llvm::Value *, 4> Args;
2621 SmallVector<llvm::Type *, 4> ArgTypes;
2622 Args.reserve(DynamicArgs.size() + 1);
2623 ArgTypes.reserve(DynamicArgs.size() + 1);
2625 // Emit handler arguments and create handler function type.
2626 if (!StaticArgs.empty()) {
2627 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2629 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2630 llvm::GlobalVariable::PrivateLinkage, Info);
2631 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2632 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2633 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2634 ArgTypes.push_back(Int8PtrTy);
2637 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2638 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2639 ArgTypes.push_back(IntPtrTy);
2642 llvm::FunctionType *FnType =
2643 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2645 if (!FatalCond || !RecoverableCond) {
2646 // Simple case: we need to generate a single handler call, either
2647 // fatal, or non-fatal.
2648 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2649 (FatalCond != nullptr), Cont);
2651 // Emit two handler calls: first one for set of unrecoverable checks,
2652 // another one for recoverable.
2653 llvm::BasicBlock *NonFatalHandlerBB =
2654 createBasicBlock("non_fatal." + CheckName);
2655 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2656 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2657 EmitBlock(FatalHandlerBB);
2658 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2660 EmitBlock(NonFatalHandlerBB);
2661 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2668 void CodeGenFunction::EmitCfiSlowPathCheck(
2669 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2670 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2671 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2673 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2674 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2676 llvm::MDBuilder MDHelper(getLLVMContext());
2677 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2678 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2682 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2684 llvm::CallInst *CheckCall;
2686 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2688 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2689 llvm::GlobalVariable::PrivateLinkage, Info);
2690 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2691 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2693 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2694 "__cfi_slowpath_diag",
2695 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2697 CheckCall = Builder.CreateCall(
2699 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2701 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2703 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2704 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2707 CheckCall->setDoesNotThrow();
2712 // This function is basically a switch over the CFI failure kind, which is
2713 // extracted from CFICheckFailData (1st function argument). Each case is either
2714 // llvm.trap or a call to one of the two runtime handlers, based on
2715 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2716 // failure kind) traps, but this should really never happen. CFICheckFailData
2717 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2718 // check kind; in this case __cfi_check_fail traps as well.
2719 void CodeGenFunction::EmitCfiCheckFail() {
2720 SanitizerScope SanScope(this);
2721 FunctionArgList Args;
2722 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2723 getContext().VoidPtrTy);
2724 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2725 getContext().VoidPtrTy);
2726 Args.push_back(&ArgData);
2727 Args.push_back(&ArgAddr);
2729 const CGFunctionInfo &FI =
2730 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2732 llvm::Function *F = llvm::Function::Create(
2733 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2734 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2735 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2737 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2741 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2742 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2744 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2745 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2747 // Data == nullptr means the calling module has trap behaviour for this check.
2748 llvm::Value *DataIsNotNullPtr =
2749 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2750 EmitTrapCheck(DataIsNotNullPtr);
2752 llvm::StructType *SourceLocationTy =
2753 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2754 llvm::StructType *CfiCheckFailDataTy =
2755 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2757 llvm::Value *V = Builder.CreateConstGEP2_32(
2759 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2761 Address CheckKindAddr(V, getIntAlign());
2762 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2764 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2765 CGM.getLLVMContext(),
2766 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2767 llvm::Value *ValidVtable = Builder.CreateZExt(
2768 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2769 {Addr, AllVtables}),
2772 const std::pair<int, SanitizerMask> CheckKinds[] = {
2773 {CFITCK_VCall, SanitizerKind::CFIVCall},
2774 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2775 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2776 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2777 {CFITCK_ICall, SanitizerKind::CFIICall}};
2779 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2780 for (auto CheckKindMaskPair : CheckKinds) {
2781 int Kind = CheckKindMaskPair.first;
2782 SanitizerMask Mask = CheckKindMaskPair.second;
2784 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2785 if (CGM.getLangOpts().Sanitize.has(Mask))
2786 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2787 {Data, Addr, ValidVtable});
2789 EmitTrapCheck(Cond);
2793 // The only reference to this function will be created during LTO link.
2794 // Make sure it survives until then.
2795 CGM.addUsedGlobal(F);
2798 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2799 llvm::BasicBlock *Cont = createBasicBlock("cont");
2801 // If we're optimizing, collapse all calls to trap down to just one per
2802 // function to save on code size.
2803 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2804 TrapBB = createBasicBlock("trap");
2805 Builder.CreateCondBr(Checked, Cont, TrapBB);
2807 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2808 TrapCall->setDoesNotReturn();
2809 TrapCall->setDoesNotThrow();
2810 Builder.CreateUnreachable();
2812 Builder.CreateCondBr(Checked, Cont, TrapBB);
2818 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2819 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2821 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2822 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2823 CGM.getCodeGenOpts().TrapFuncName);
2824 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2830 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2831 AlignmentSource *AlignSource) {
2832 assert(E->getType()->isArrayType() &&
2833 "Array to pointer decay must have array source type!");
2835 // Expressions of array type can't be bitfields or vector elements.
2836 LValue LV = EmitLValue(E);
2837 Address Addr = LV.getAddress();
2838 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2840 // If the array type was an incomplete type, we need to make sure
2841 // the decay ends up being the right type.
2842 llvm::Type *NewTy = ConvertType(E->getType());
2843 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2845 // Note that VLA pointers are always decayed, so we don't need to do
2847 if (!E->getType()->isVariableArrayType()) {
2848 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2849 "Expected pointer to array");
2850 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2853 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2854 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2857 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2858 /// array to pointer, return the array subexpression.
2859 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2860 // If this isn't just an array->pointer decay, bail out.
2861 const auto *CE = dyn_cast<CastExpr>(E);
2862 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2865 // If this is a decay from variable width array, bail out.
2866 const Expr *SubExpr = CE->getSubExpr();
2867 if (SubExpr->getType()->isVariableArrayType())
2873 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2875 ArrayRef<llvm::Value*> indices,
2877 const llvm::Twine &name = "arrayidx") {
2879 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2881 return CGF.Builder.CreateGEP(ptr, indices, name);
2885 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2887 CharUnits eltSize) {
2888 // If we have a constant index, we can use the exact offset of the
2889 // element we're accessing.
2890 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2891 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2892 return arrayAlign.alignmentAtOffset(offset);
2894 // Otherwise, use the worst-case alignment for any element.
2896 return arrayAlign.alignmentOfArrayElement(eltSize);
2900 static QualType getFixedSizeElementType(const ASTContext &ctx,
2901 const VariableArrayType *vla) {
2904 eltType = vla->getElementType();
2905 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2909 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2910 ArrayRef<llvm::Value*> indices,
2911 QualType eltType, bool inbounds,
2912 const llvm::Twine &name = "arrayidx") {
2913 // All the indices except that last must be zero.
2915 for (auto idx : indices.drop_back())
2916 assert(isa<llvm::ConstantInt>(idx) &&
2917 cast<llvm::ConstantInt>(idx)->isZero());
2920 // Determine the element size of the statically-sized base. This is
2921 // the thing that the indices are expressed in terms of.
2922 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2923 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2926 // We can use that to compute the best alignment of the element.
2927 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2928 CharUnits eltAlign =
2929 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2931 llvm::Value *eltPtr =
2932 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2933 return Address(eltPtr, eltAlign);
2936 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2938 // The index must always be an integer, which is not an aggregate. Emit it
2939 // in lexical order (this complexity is, sadly, required by C++17).
2940 llvm::Value *IdxPre =
2941 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
2942 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
2944 if (E->getLHS() != E->getIdx()) {
2945 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2946 Idx = EmitScalarExpr(E->getIdx());
2949 QualType IdxTy = E->getIdx()->getType();
2950 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2952 if (SanOpts.has(SanitizerKind::ArrayBounds))
2953 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2955 // Extend or truncate the index type to 32 or 64-bits.
2956 if (Promote && Idx->getType() != IntPtrTy)
2957 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2963 // If the base is a vector type, then we are forming a vector element lvalue
2964 // with this subscript.
2965 if (E->getBase()->getType()->isVectorType() &&
2966 !isa<ExtVectorElementExpr>(E->getBase())) {
2967 // Emit the vector as an lvalue to get its address.
2968 LValue LHS = EmitLValue(E->getBase());
2969 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
2970 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2971 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2972 E->getBase()->getType(),
2973 LHS.getAlignmentSource());
2976 // All the other cases basically behave like simple offsetting.
2978 // Handle the extvector case we ignored above.
2979 if (isa<ExtVectorElementExpr>(E->getBase())) {
2980 LValue LV = EmitLValue(E->getBase());
2981 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2982 Address Addr = EmitExtVectorElementLValue(LV);
2984 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2985 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2986 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
2989 AlignmentSource AlignSource;
2990 Address Addr = Address::invalid();
2991 if (const VariableArrayType *vla =
2992 getContext().getAsVariableArrayType(E->getType())) {
2993 // The base must be a pointer, which is not an aggregate. Emit
2994 // it. It needs to be emitted first in case it's what captures
2996 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2997 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2999 // The element count here is the total number of non-VLA elements.
3000 llvm::Value *numElements = getVLASize(vla).first;
3002 // Effectively, the multiply by the VLA size is part of the GEP.
3003 // GEP indexes are signed, and scaling an index isn't permitted to
3004 // signed-overflow, so we use the same semantics for our explicit
3005 // multiply. We suppress this if overflow is not undefined behavior.
3006 if (getLangOpts().isSignedOverflowDefined()) {
3007 Idx = Builder.CreateMul(Idx, numElements);
3009 Idx = Builder.CreateNSWMul(Idx, numElements);
3012 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3013 !getLangOpts().isSignedOverflowDefined());
3015 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3016 // Indexing over an interface, as in "NSString *P; P[4];"
3018 // Emit the base pointer.
3019 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3020 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3022 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3023 llvm::Value *InterfaceSizeVal =
3024 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3026 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3028 // We don't necessarily build correct LLVM struct types for ObjC
3029 // interfaces, so we can't rely on GEP to do this scaling
3030 // correctly, so we need to cast to i8*. FIXME: is this actually
3031 // true? A lot of other things in the fragile ABI would break...
3032 llvm::Type *OrigBaseTy = Addr.getType();
3033 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3036 CharUnits EltAlign =
3037 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3038 llvm::Value *EltPtr =
3039 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3040 Addr = Address(EltPtr, EltAlign);
3043 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3044 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3045 // If this is A[i] where A is an array, the frontend will have decayed the
3046 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3047 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3048 // "gep x, i" here. Emit one "gep A, 0, i".
3049 assert(Array->getType()->isArrayType() &&
3050 "Array to pointer decay must have array source type!");
3052 // For simple multidimensional array indexing, set the 'accessed' flag for
3053 // better bounds-checking of the base expression.
3054 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3055 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3057 ArrayLV = EmitLValue(Array);
3058 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3060 // Propagate the alignment from the array itself to the result.
3061 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3062 {CGM.getSize(CharUnits::Zero()), Idx},
3064 !getLangOpts().isSignedOverflowDefined());
3065 AlignSource = ArrayLV.getAlignmentSource();
3067 // The base must be a pointer; emit it with an estimate of its alignment.
3068 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3069 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3070 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3071 !getLangOpts().isSignedOverflowDefined());
3074 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3076 // TODO: Preserve/extend path TBAA metadata?
3078 if (getLangOpts().ObjC1 &&
3079 getLangOpts().getGC() != LangOptions::NonGC) {
3080 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3081 setObjCGCLValueClass(getContext(), E, LV);
3086 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3087 AlignmentSource &AlignSource,
3088 QualType BaseTy, QualType ElTy,
3089 bool IsLowerBound) {
3091 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3092 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3093 if (BaseTy->isArrayType()) {
3094 Address Addr = BaseLVal.getAddress();
3095 AlignSource = BaseLVal.getAlignmentSource();
3097 // If the array type was an incomplete type, we need to make sure
3098 // the decay ends up being the right type.
3099 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3100 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3102 // Note that VLA pointers are always decayed, so we don't need to do
3104 if (!BaseTy->isVariableArrayType()) {
3105 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3106 "Expected pointer to array");
3107 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3111 return CGF.Builder.CreateElementBitCast(Addr,
3112 CGF.ConvertTypeForMem(ElTy));
3114 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3115 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3117 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3120 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3121 bool IsLowerBound) {
3124 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3125 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3127 BaseTy = E->getBase()->getType();
3128 QualType ResultExprTy;
3129 if (auto *AT = getContext().getAsArrayType(BaseTy))
3130 ResultExprTy = AT->getElementType();
3132 ResultExprTy = BaseTy->getPointeeType();
3133 llvm::Value *Idx = nullptr;
3134 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3135 // Requesting lower bound or upper bound, but without provided length and
3136 // without ':' symbol for the default length -> length = 1.
3137 // Idx = LowerBound ?: 0;
3138 if (auto *LowerBound = E->getLowerBound()) {
3139 Idx = Builder.CreateIntCast(
3140 EmitScalarExpr(LowerBound), IntPtrTy,
3141 LowerBound->getType()->hasSignedIntegerRepresentation());
3143 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3145 // Try to emit length or lower bound as constant. If this is possible, 1
3146 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3147 // IR (LB + Len) - 1.
3148 auto &C = CGM.getContext();
3149 auto *Length = E->getLength();
3150 llvm::APSInt ConstLength;
3152 // Idx = LowerBound + Length - 1;
3153 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3154 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3157 auto *LowerBound = E->getLowerBound();
3158 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3159 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3160 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3161 LowerBound = nullptr;
3165 else if (!LowerBound)
3168 if (Length || LowerBound) {
3169 auto *LowerBoundVal =
3171 ? Builder.CreateIntCast(
3172 EmitScalarExpr(LowerBound), IntPtrTy,
3173 LowerBound->getType()->hasSignedIntegerRepresentation())
3174 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3177 ? Builder.CreateIntCast(
3178 EmitScalarExpr(Length), IntPtrTy,
3179 Length->getType()->hasSignedIntegerRepresentation())
3180 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3181 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3183 !getLangOpts().isSignedOverflowDefined());
3184 if (Length && LowerBound) {
3185 Idx = Builder.CreateSub(
3186 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3187 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3190 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3192 // Idx = ArraySize - 1;
3193 QualType ArrayTy = BaseTy->isPointerType()
3194 ? E->getBase()->IgnoreParenImpCasts()->getType()
3196 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3197 Length = VAT->getSizeExpr();
3198 if (Length->isIntegerConstantExpr(ConstLength, C))
3201 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3202 ConstLength = CAT->getSize();
3205 auto *LengthVal = Builder.CreateIntCast(
3206 EmitScalarExpr(Length), IntPtrTy,
3207 Length->getType()->hasSignedIntegerRepresentation());
3208 Idx = Builder.CreateSub(
3209 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3210 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3212 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3214 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3220 Address EltPtr = Address::invalid();
3221 AlignmentSource AlignSource;
3222 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3223 // The base must be a pointer, which is not an aggregate. Emit
3224 // it. It needs to be emitted first in case it's what captures
3227 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3228 VLA->getElementType(), IsLowerBound);
3229 // The element count here is the total number of non-VLA elements.
3230 llvm::Value *NumElements = getVLASize(VLA).first;
3232 // Effectively, the multiply by the VLA size is part of the GEP.
3233 // GEP indexes are signed, and scaling an index isn't permitted to
3234 // signed-overflow, so we use the same semantics for our explicit
3235 // multiply. We suppress this if overflow is not undefined behavior.
3236 if (getLangOpts().isSignedOverflowDefined())
3237 Idx = Builder.CreateMul(Idx, NumElements);
3239 Idx = Builder.CreateNSWMul(Idx, NumElements);
3240 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3241 !getLangOpts().isSignedOverflowDefined());
3242 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3243 // If this is A[i] where A is an array, the frontend will have decayed the
3244 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3245 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3246 // "gep x, i" here. Emit one "gep A, 0, i".
3247 assert(Array->getType()->isArrayType() &&
3248 "Array to pointer decay must have array source type!");
3250 // For simple multidimensional array indexing, set the 'accessed' flag for
3251 // better bounds-checking of the base expression.
3252 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3253 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3255 ArrayLV = EmitLValue(Array);
3257 // Propagate the alignment from the array itself to the result.
3258 EltPtr = emitArraySubscriptGEP(
3259 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3260 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3261 AlignSource = ArrayLV.getAlignmentSource();
3263 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3264 BaseTy, ResultExprTy, IsLowerBound);
3265 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3266 !getLangOpts().isSignedOverflowDefined());
3269 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3272 LValue CodeGenFunction::
3273 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3274 // Emit the base vector as an l-value.
3277 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3279 // If it is a pointer to a vector, emit the address and form an lvalue with
3281 AlignmentSource AlignSource;
3282 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3283 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3284 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3285 Base.getQuals().removeObjCGCAttr();
3286 } else if (E->getBase()->isGLValue()) {
3287 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3288 // emit the base as an lvalue.
3289 assert(E->getBase()->getType()->isVectorType());
3290 Base = EmitLValue(E->getBase());
3292 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3293 assert(E->getBase()->getType()->isVectorType() &&
3294 "Result must be a vector");
3295 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3297 // Store the vector to memory (because LValue wants an address).
3298 Address VecMem = CreateMemTemp(E->getBase()->getType());
3299 Builder.CreateStore(Vec, VecMem);
3300 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3301 AlignmentSource::Decl);
3305 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3307 // Encode the element access list into a vector of unsigned indices.
3308 SmallVector<uint32_t, 4> Indices;
3309 E->getEncodedElementAccess(Indices);
3311 if (Base.isSimple()) {
3312 llvm::Constant *CV =
3313 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3314 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3315 Base.getAlignmentSource());
3317 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3319 llvm::Constant *BaseElts = Base.getExtVectorElts();
3320 SmallVector<llvm::Constant *, 4> CElts;
3322 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3323 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3324 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3325 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3326 Base.getAlignmentSource());
3329 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3330 Expr *BaseExpr = E->getBase();
3332 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3335 AlignmentSource AlignSource;
3336 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3337 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3338 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3339 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3341 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3343 NamedDecl *ND = E->getMemberDecl();
3344 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3345 LValue LV = EmitLValueForField(BaseLV, Field);
3346 setObjCGCLValueClass(getContext(), E, LV);
3350 if (auto *VD = dyn_cast<VarDecl>(ND))
3351 return EmitGlobalVarDeclLValue(*this, E, VD);
3353 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3354 return EmitFunctionDeclLValue(*this, E, FD);
3356 llvm_unreachable("Unhandled member declaration!");
3359 /// Given that we are currently emitting a lambda, emit an l-value for
3360 /// one of its members.
3361 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3362 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3363 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3364 QualType LambdaTagType =
3365 getContext().getTagDeclType(Field->getParent());
3366 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3367 return EmitLValueForField(LambdaLV, Field);
3370 /// Drill down to the storage of a field without walking into
3371 /// reference types.
3373 /// The resulting address doesn't necessarily have the right type.
3374 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3375 const FieldDecl *field) {
3376 const RecordDecl *rec = field->getParent();
3379 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3382 // Adjust the alignment down to the given offset.
3383 // As a special case, if the LLVM field index is 0, we know that this
3385 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3386 .getFieldOffset(field->getFieldIndex()) == 0) &&
3387 "LLVM field at index zero had non-zero offset?");
3389 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3390 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3391 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3394 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3397 LValue CodeGenFunction::EmitLValueForField(LValue base,
3398 const FieldDecl *field) {
3399 AlignmentSource fieldAlignSource =
3400 getFieldAlignmentSource(base.getAlignmentSource());
3402 if (field->isBitField()) {
3403 const CGRecordLayout &RL =
3404 CGM.getTypes().getCGRecordLayout(field->getParent());
3405 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3406 Address Addr = base.getAddress();
3407 unsigned Idx = RL.getLLVMFieldNo(field);
3409 // For structs, we GEP to the field that the record layout suggests.
3410 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3412 // Get the access type.
3413 llvm::Type *FieldIntTy =
3414 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3415 if (Addr.getElementType() != FieldIntTy)
3416 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3418 QualType fieldType =
3419 field->getType().withCVRQualifiers(base.getVRQualifiers());
3420 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3423 const RecordDecl *rec = field->getParent();
3424 QualType type = field->getType();
3426 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3428 Address addr = base.getAddress();
3429 unsigned cvr = base.getVRQualifiers();
3430 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3431 if (rec->isUnion()) {
3432 // For unions, there is no pointer adjustment.
3433 assert(!type->isReferenceType() && "union has reference member");
3434 // TODO: handle path-aware TBAA for union.
3437 // For structs, we GEP to the field that the record layout suggests.
3438 addr = emitAddrOfFieldStorage(*this, addr, field);
3440 // If this is a reference field, load the reference right now.
3441 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3442 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3443 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3445 // Loading the reference will disable path-aware TBAA.
3447 if (CGM.shouldUseTBAA()) {
3450 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3452 tbaa = CGM.getTBAAInfo(type);
3454 CGM.DecorateInstructionWithTBAA(load, tbaa);
3458 type = refType->getPointeeType();
3460 CharUnits alignment =
3461 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3462 addr = Address(load, alignment);
3464 // Qualifiers on the struct don't apply to the referencee, and
3465 // we'll pick up CVR from the actual type later, so reset these
3466 // additional qualifiers now.
3471 // Make sure that the address is pointing to the right type. This is critical
3472 // for both unions and structs. A union needs a bitcast, a struct element
3473 // will need a bitcast if the LLVM type laid out doesn't match the desired
3475 addr = Builder.CreateElementBitCast(addr,
3476 CGM.getTypes().ConvertTypeForMem(type),
3479 if (field->hasAttr<AnnotateAttr>())
3480 addr = EmitFieldAnnotations(field, addr);
3482 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3483 LV.getQuals().addCVRQualifiers(cvr);
3485 const ASTRecordLayout &Layout =
3486 getContext().getASTRecordLayout(field->getParent());
3487 // Set the base type to be the base type of the base LValue and
3488 // update offset to be relative to the base type.
3489 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3490 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3491 Layout.getFieldOffset(field->getFieldIndex()) /
3492 getContext().getCharWidth());
3495 // __weak attribute on a field is ignored.
3496 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3497 LV.getQuals().removeObjCGCAttr();
3499 // Fields of may_alias structs act like 'char' for TBAA purposes.
3500 // FIXME: this should get propagated down through anonymous structs
3502 if (mayAlias && LV.getTBAAInfo())
3503 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3509 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3510 const FieldDecl *Field) {
3511 QualType FieldType = Field->getType();
3513 if (!FieldType->isReferenceType())
3514 return EmitLValueForField(Base, Field);
3516 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3518 // Make sure that the address is pointing to the right type.
3519 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3520 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3522 // TODO: access-path TBAA?
3523 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3524 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3527 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3528 if (E->isFileScope()) {
3529 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3530 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3532 if (E->getType()->isVariablyModifiedType())
3533 // make sure to emit the VLA size.
3534 EmitVariablyModifiedType(E->getType());
3536 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3537 const Expr *InitExpr = E->getInitializer();
3538 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3540 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3546 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3547 if (!E->isGLValue())
3548 // Initializing an aggregate temporary in C++11: T{...}.
3549 return EmitAggExprToLValue(E);
3551 // An lvalue initializer list must be initializing a reference.
3552 assert(E->isTransparent() && "non-transparent glvalue init list");
3553 return EmitLValue(E->getInit(0));
3556 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3557 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3558 /// LValue is returned and the current block has been terminated.
3559 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3560 const Expr *Operand) {
3561 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3562 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3566 return CGF.EmitLValue(Operand);
3569 LValue CodeGenFunction::
3570 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3571 if (!expr->isGLValue()) {
3572 // ?: here should be an aggregate.
3573 assert(hasAggregateEvaluationKind(expr->getType()) &&
3574 "Unexpected conditional operator!");
3575 return EmitAggExprToLValue(expr);
3578 OpaqueValueMapping binding(*this, expr);
3580 const Expr *condExpr = expr->getCond();
3582 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3583 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3584 if (!CondExprBool) std::swap(live, dead);
3586 if (!ContainsLabel(dead)) {
3587 // If the true case is live, we need to track its region.
3589 incrementProfileCounter(expr);
3590 return EmitLValue(live);
3594 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3595 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3596 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3598 ConditionalEvaluation eval(*this);
3599 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3601 // Any temporaries created here are conditional.
3602 EmitBlock(lhsBlock);
3603 incrementProfileCounter(expr);
3605 Optional<LValue> lhs =
3606 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3609 if (lhs && !lhs->isSimple())
3610 return EmitUnsupportedLValue(expr, "conditional operator");
3612 lhsBlock = Builder.GetInsertBlock();
3614 Builder.CreateBr(contBlock);
3616 // Any temporaries created here are conditional.
3617 EmitBlock(rhsBlock);
3619 Optional<LValue> rhs =
3620 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3622 if (rhs && !rhs->isSimple())
3623 return EmitUnsupportedLValue(expr, "conditional operator");
3624 rhsBlock = Builder.GetInsertBlock();
3626 EmitBlock(contBlock);
3629 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3631 phi->addIncoming(lhs->getPointer(), lhsBlock);
3632 phi->addIncoming(rhs->getPointer(), rhsBlock);
3633 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3634 AlignmentSource alignSource =
3635 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3636 return MakeAddrLValue(result, expr->getType(), alignSource);
3638 assert((lhs || rhs) &&
3639 "both operands of glvalue conditional are throw-expressions?");
3640 return lhs ? *lhs : *rhs;
3644 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3645 /// type. If the cast is to a reference, we can have the usual lvalue result,
3646 /// otherwise if a cast is needed by the code generator in an lvalue context,
3647 /// then it must mean that we need the address of an aggregate in order to
3648 /// access one of its members. This can happen for all the reasons that casts
3649 /// are permitted with aggregate result, including noop aggregate casts, and
3650 /// cast from scalar to union.
3651 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3652 switch (E->getCastKind()) {
3655 case CK_ArrayToPointerDecay:
3656 case CK_FunctionToPointerDecay:
3657 case CK_NullToMemberPointer:
3658 case CK_NullToPointer:
3659 case CK_IntegralToPointer:
3660 case CK_PointerToIntegral:
3661 case CK_PointerToBoolean:
3662 case CK_VectorSplat:
3663 case CK_IntegralCast:
3664 case CK_BooleanToSignedIntegral:
3665 case CK_IntegralToBoolean:
3666 case CK_IntegralToFloating:
3667 case CK_FloatingToIntegral:
3668 case CK_FloatingToBoolean:
3669 case CK_FloatingCast:
3670 case CK_FloatingRealToComplex:
3671 case CK_FloatingComplexToReal:
3672 case CK_FloatingComplexToBoolean:
3673 case CK_FloatingComplexCast:
3674 case CK_FloatingComplexToIntegralComplex:
3675 case CK_IntegralRealToComplex:
3676 case CK_IntegralComplexToReal:
3677 case CK_IntegralComplexToBoolean:
3678 case CK_IntegralComplexCast:
3679 case CK_IntegralComplexToFloatingComplex:
3680 case CK_DerivedToBaseMemberPointer:
3681 case CK_BaseToDerivedMemberPointer:
3682 case CK_MemberPointerToBoolean:
3683 case CK_ReinterpretMemberPointer:
3684 case CK_AnyPointerToBlockPointerCast:
3685 case CK_ARCProduceObject:
3686 case CK_ARCConsumeObject:
3687 case CK_ARCReclaimReturnedObject:
3688 case CK_ARCExtendBlockObject:
3689 case CK_CopyAndAutoreleaseBlockObject:
3690 case CK_AddressSpaceConversion:
3691 case CK_IntToOCLSampler:
3692 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3695 llvm_unreachable("dependent cast kind in IR gen!");
3697 case CK_BuiltinFnToFnPtr:
3698 llvm_unreachable("builtin functions are handled elsewhere");
3700 // These are never l-values; just use the aggregate emission code.
3701 case CK_NonAtomicToAtomic:
3702 case CK_AtomicToNonAtomic:
3703 return EmitAggExprToLValue(E);
3706 LValue LV = EmitLValue(E->getSubExpr());
3707 Address V = LV.getAddress();
3708 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3709 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3712 case CK_ConstructorConversion:
3713 case CK_UserDefinedConversion:
3714 case CK_CPointerToObjCPointerCast:
3715 case CK_BlockPointerToObjCPointerCast:
3717 case CK_LValueToRValue:
3718 return EmitLValue(E->getSubExpr());
3720 case CK_UncheckedDerivedToBase:
3721 case CK_DerivedToBase: {
3722 const RecordType *DerivedClassTy =
3723 E->getSubExpr()->getType()->getAs<RecordType>();
3724 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3726 LValue LV = EmitLValue(E->getSubExpr());
3727 Address This = LV.getAddress();
3729 // Perform the derived-to-base conversion
3730 Address Base = GetAddressOfBaseClass(
3731 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3732 /*NullCheckValue=*/false, E->getExprLoc());
3734 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3737 return EmitAggExprToLValue(E);
3738 case CK_BaseToDerived: {
3739 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3740 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3742 LValue LV = EmitLValue(E->getSubExpr());
3744 // Perform the base-to-derived conversion
3746 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3747 E->path_begin(), E->path_end(),
3748 /*NullCheckValue=*/false);
3750 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3751 // performed and the object is not of the derived type.
3752 if (sanitizePerformTypeCheck())
3753 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3754 Derived.getPointer(), E->getType());
3756 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3757 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3758 /*MayBeNull=*/false,
3759 CFITCK_DerivedCast, E->getLocStart());
3761 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3763 case CK_LValueBitCast: {
3764 // This must be a reinterpret_cast (or c-style equivalent).
3765 const auto *CE = cast<ExplicitCastExpr>(E);
3767 CGM.EmitExplicitCastExprType(CE, this);
3768 LValue LV = EmitLValue(E->getSubExpr());
3769 Address V = Builder.CreateBitCast(LV.getAddress(),
3770 ConvertType(CE->getTypeAsWritten()));
3772 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3773 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3774 /*MayBeNull=*/false,
3775 CFITCK_UnrelatedCast, E->getLocStart());
3777 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3779 case CK_ObjCObjectLValueCast: {
3780 LValue LV = EmitLValue(E->getSubExpr());
3781 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3782 ConvertType(E->getType()));
3783 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3785 case CK_ZeroToOCLQueue:
3786 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3787 case CK_ZeroToOCLEvent:
3788 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3791 llvm_unreachable("Unhandled lvalue cast kind?");
3794 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3795 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3796 return getOpaqueLValueMapping(e);
3799 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3800 const FieldDecl *FD,
3801 SourceLocation Loc) {
3802 QualType FT = FD->getType();
3803 LValue FieldLV = EmitLValueForField(LV, FD);
3804 switch (getEvaluationKind(FT)) {
3806 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3808 return FieldLV.asAggregateRValue();
3810 // This routine is used to load fields one-by-one to perform a copy, so
3811 // don't load reference fields.
3812 if (FD->getType()->isReferenceType())
3813 return RValue::get(FieldLV.getPointer());
3814 return EmitLoadOfLValue(FieldLV, Loc);
3816 llvm_unreachable("bad evaluation kind");
3819 //===--------------------------------------------------------------------===//
3820 // Expression Emission
3821 //===--------------------------------------------------------------------===//
3823 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3824 ReturnValueSlot ReturnValue) {
3825 // Builtins never have block type.
3826 if (E->getCallee()->getType()->isBlockPointerType())
3827 return EmitBlockCallExpr(E, ReturnValue);
3829 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3830 return EmitCXXMemberCallExpr(CE, ReturnValue);
3832 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3833 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3835 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3836 if (const CXXMethodDecl *MD =
3837 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3838 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3840 CGCallee callee = EmitCallee(E->getCallee());
3842 if (callee.isBuiltin()) {
3843 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3847 if (callee.isPseudoDestructor()) {
3848 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3851 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3854 /// Emit a CallExpr without considering whether it might be a subclass.
3855 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3856 ReturnValueSlot ReturnValue) {
3857 CGCallee Callee = EmitCallee(E->getCallee());
3858 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3861 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3862 if (auto builtinID = FD->getBuiltinID()) {
3863 return CGCallee::forBuiltin(builtinID, FD);
3866 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3867 return CGCallee::forDirect(calleePtr, FD);
3870 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3871 E = E->IgnoreParens();
3873 // Look through function-to-pointer decay.
3874 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3875 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3876 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3877 return EmitCallee(ICE->getSubExpr());
3880 // Resolve direct calls.
3881 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3882 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3883 return EmitDirectCallee(*this, FD);
3885 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3886 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3887 EmitIgnoredExpr(ME->getBase());
3888 return EmitDirectCallee(*this, FD);
3891 // Look through template substitutions.
3892 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3893 return EmitCallee(NTTP->getReplacement());
3895 // Treat pseudo-destructor calls differently.
3896 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3897 return CGCallee::forPseudoDestructor(PDE);
3900 // Otherwise, we have an indirect reference.
3901 llvm::Value *calleePtr;
3902 QualType functionType;
3903 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3904 calleePtr = EmitScalarExpr(E);
3905 functionType = ptrType->getPointeeType();
3907 functionType = E->getType();
3908 calleePtr = EmitLValue(E).getPointer();
3910 assert(functionType->isFunctionType());
3911 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3912 E->getReferencedDeclOfCallee());
3913 CGCallee callee(calleeInfo, calleePtr);
3917 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3918 // Comma expressions just emit their LHS then their RHS as an l-value.
3919 if (E->getOpcode() == BO_Comma) {
3920 EmitIgnoredExpr(E->getLHS());
3921 EnsureInsertPoint();
3922 return EmitLValue(E->getRHS());
3925 if (E->getOpcode() == BO_PtrMemD ||
3926 E->getOpcode() == BO_PtrMemI)
3927 return EmitPointerToDataMemberBinaryExpr(E);
3929 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
3931 // Note that in all of these cases, __block variables need the RHS
3932 // evaluated first just in case the variable gets moved by the RHS.
3934 switch (getEvaluationKind(E->getType())) {
3936 switch (E->getLHS()->getType().getObjCLifetime()) {
3937 case Qualifiers::OCL_Strong:
3938 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3940 case Qualifiers::OCL_Autoreleasing:
3941 return EmitARCStoreAutoreleasing(E).first;
3943 // No reason to do any of these differently.
3944 case Qualifiers::OCL_None:
3945 case Qualifiers::OCL_ExplicitNone:
3946 case Qualifiers::OCL_Weak:
3950 RValue RV = EmitAnyExpr(E->getRHS());
3951 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
3952 EmitStoreThroughLValue(RV, LV);
3957 return EmitComplexAssignmentLValue(E);
3960 return EmitAggExprToLValue(E);
3962 llvm_unreachable("bad evaluation kind");
3965 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
3966 RValue RV = EmitCallExpr(E);
3969 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3970 AlignmentSource::Decl);
3972 assert(E->getCallReturnType(getContext())->isReferenceType() &&
3973 "Can't have a scalar return unless the return type is a "
3976 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
3979 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3980 // FIXME: This shouldn't require another copy.
3981 return EmitAggExprToLValue(E);
3984 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
3985 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3986 && "binding l-value to type which needs a temporary");
3987 AggValueSlot Slot = CreateAggTemp(E->getType());
3988 EmitCXXConstructExpr(E, Slot);
3989 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3990 AlignmentSource::Decl);
3994 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
3995 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
3998 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3999 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4000 ConvertType(E->getType()));
4003 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4004 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4005 AlignmentSource::Decl);
4009 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4010 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4011 Slot.setExternallyDestructed();
4012 EmitAggExpr(E->getSubExpr(), Slot);
4013 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4014 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4015 AlignmentSource::Decl);
4019 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4020 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4021 EmitLambdaExpr(E, Slot);
4022 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4023 AlignmentSource::Decl);
4026 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4027 RValue RV = EmitObjCMessageExpr(E);
4030 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4031 AlignmentSource::Decl);
4033 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4034 "Can't have a scalar return unless the return type is a "
4037 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4040 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4042 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4043 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4046 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4047 const ObjCIvarDecl *Ivar) {
4048 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4051 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4052 llvm::Value *BaseValue,
4053 const ObjCIvarDecl *Ivar,
4054 unsigned CVRQualifiers) {
4055 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4056 Ivar, CVRQualifiers);
4059 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4060 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4061 llvm::Value *BaseValue = nullptr;
4062 const Expr *BaseExpr = E->getBase();
4063 Qualifiers BaseQuals;
4066 BaseValue = EmitScalarExpr(BaseExpr);
4067 ObjectTy = BaseExpr->getType()->getPointeeType();
4068 BaseQuals = ObjectTy.getQualifiers();
4070 LValue BaseLV = EmitLValue(BaseExpr);
4071 BaseValue = BaseLV.getPointer();
4072 ObjectTy = BaseExpr->getType();
4073 BaseQuals = ObjectTy.getQualifiers();
4077 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4078 BaseQuals.getCVRQualifiers());
4079 setObjCGCLValueClass(getContext(), E, LV);
4083 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4084 // Can only get l-value for message expression returning aggregate type
4085 RValue RV = EmitAnyExprToTemp(E);
4086 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4087 AlignmentSource::Decl);
4090 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4091 const CallExpr *E, ReturnValueSlot ReturnValue,
4092 llvm::Value *Chain) {
4093 // Get the actual function type. The callee type will always be a pointer to
4094 // function type or a block pointer type.
4095 assert(CalleeType->isFunctionPointerType() &&
4096 "Call must have function pointer type!");
4098 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4100 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4101 // We can only guarantee that a function is called from the correct
4102 // context/function based on the appropriate target attributes,
4103 // so only check in the case where we have both always_inline and target
4104 // since otherwise we could be making a conditional call after a check for
4105 // the proper cpu features (and it won't cause code generation issues due to
4106 // function based code generation).
4107 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4108 TargetDecl->hasAttr<TargetAttr>())
4109 checkTargetFeatures(E, FD);
4111 CalleeType = getContext().getCanonicalType(CalleeType);
4113 const auto *FnType =
4114 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4116 CGCallee Callee = OrigCallee;
4118 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4119 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4120 if (llvm::Constant *PrefixSig =
4121 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4122 SanitizerScope SanScope(this);
4123 llvm::Constant *FTRTTIConst =
4124 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4125 llvm::Type *PrefixStructTyElems[] = {
4126 PrefixSig->getType(),
4127 FTRTTIConst->getType()
4129 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4130 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4132 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4134 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4135 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4136 llvm::Value *CalleeSigPtr =
4137 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4138 llvm::Value *CalleeSig =
4139 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4140 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4142 llvm::BasicBlock *Cont = createBasicBlock("cont");
4143 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4144 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4146 EmitBlock(TypeCheck);
4147 llvm::Value *CalleeRTTIPtr =
4148 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4149 llvm::Value *CalleeRTTI =
4150 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4151 llvm::Value *CalleeRTTIMatch =
4152 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4153 llvm::Constant *StaticData[] = {
4154 EmitCheckSourceLocation(E->getLocStart()),
4155 EmitCheckTypeDescriptor(CalleeType)
4157 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4158 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4160 Builder.CreateBr(Cont);
4165 // If we are checking indirect calls and this call is indirect, check that the
4166 // function pointer is a member of the bit set for the function type.
4167 if (SanOpts.has(SanitizerKind::CFIICall) &&
4168 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4169 SanitizerScope SanScope(this);
4170 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4172 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4173 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4175 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4176 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4177 llvm::Value *TypeTest = Builder.CreateCall(
4178 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4180 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4181 llvm::Constant *StaticData[] = {
4182 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4183 EmitCheckSourceLocation(E->getLocStart()),
4184 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4186 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4187 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4188 CastedCallee, StaticData);
4190 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4191 SanitizerHandler::CFICheckFail, StaticData,
4192 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4198 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4199 CGM.getContext().VoidPtrTy);
4201 // C++17 requires that we evaluate arguments to a call using assignment syntax
4202 // right-to-left, and that we evaluate arguments to certain other operators
4203 // left-to-right. Note that we allow this to override the order dictated by
4204 // the calling convention on the MS ABI, which means that parameter
4205 // destruction order is not necessarily reverse construction order.
4206 // FIXME: Revisit this based on C++ committee response to unimplementability.
4207 EvaluationOrder Order = EvaluationOrder::Default;
4208 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4209 if (OCE->isAssignmentOp())
4210 Order = EvaluationOrder::ForceRightToLeft;
4212 switch (OCE->getOperator()) {
4214 case OO_GreaterGreater:
4219 Order = EvaluationOrder::ForceLeftToRight;
4227 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4228 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4230 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4231 Args, FnType, /*isChainCall=*/Chain);
4234 // If the expression that denotes the called function has a type
4235 // that does not include a prototype, [the default argument
4236 // promotions are performed]. If the number of arguments does not
4237 // equal the number of parameters, the behavior is undefined. If
4238 // the function is defined with a type that includes a prototype,
4239 // and either the prototype ends with an ellipsis (, ...) or the
4240 // types of the arguments after promotion are not compatible with
4241 // the types of the parameters, the behavior is undefined. If the
4242 // function is defined with a type that does not include a
4243 // prototype, and the types of the arguments after promotion are
4244 // not compatible with those of the parameters after promotion,
4245 // the behavior is undefined [except in some trivial cases].
4246 // That is, in the general case, we should assume that a call
4247 // through an unprototyped function type works like a *non-variadic*
4248 // call. The way we make this work is to cast to the exact type
4249 // of the promoted arguments.
4251 // Chain calls use this same code path to add the invisible chain parameter
4252 // to the function type.
4253 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4254 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4255 CalleeTy = CalleeTy->getPointerTo();
4257 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4258 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4259 Callee.setFunctionPointer(CalleePtr);
4262 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4265 LValue CodeGenFunction::
4266 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4267 Address BaseAddr = Address::invalid();
4268 if (E->getOpcode() == BO_PtrMemI) {
4269 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4271 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4274 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4276 const MemberPointerType *MPT
4277 = E->getRHS()->getType()->getAs<MemberPointerType>();
4279 AlignmentSource AlignSource;
4280 Address MemberAddr =
4281 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4284 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4287 /// Given the address of a temporary variable, produce an r-value of
4289 RValue CodeGenFunction::convertTempToRValue(Address addr,
4291 SourceLocation loc) {
4292 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4293 switch (getEvaluationKind(type)) {
4295 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4297 return lvalue.asAggregateRValue();
4299 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4301 llvm_unreachable("bad evaluation kind");
4304 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4305 assert(Val->getType()->isFPOrFPVectorTy());
4306 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4309 llvm::MDBuilder MDHelper(getLLVMContext());
4310 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4312 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4316 struct LValueOrRValue {
4322 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4323 const PseudoObjectExpr *E,
4325 AggValueSlot slot) {
4326 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4328 // Find the result expression, if any.
4329 const Expr *resultExpr = E->getResultExpr();
4330 LValueOrRValue result;
4332 for (PseudoObjectExpr::const_semantics_iterator
4333 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4334 const Expr *semantic = *i;
4336 // If this semantic expression is an opaque value, bind it
4337 // to the result of its source expression.
4338 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4340 // If this is the result expression, we may need to evaluate
4341 // directly into the slot.
4342 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4344 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4345 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4346 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4348 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4349 AlignmentSource::Decl);
4350 opaqueData = OVMA::bind(CGF, ov, LV);
4351 result.RV = slot.asRValue();
4353 // Otherwise, emit as normal.
4355 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4357 // If this is the result, also evaluate the result now.
4358 if (ov == resultExpr) {
4360 result.LV = CGF.EmitLValue(ov);
4362 result.RV = CGF.EmitAnyExpr(ov, slot);
4366 opaques.push_back(opaqueData);
4368 // Otherwise, if the expression is the result, evaluate it
4369 // and remember the result.
4370 } else if (semantic == resultExpr) {
4372 result.LV = CGF.EmitLValue(semantic);
4374 result.RV = CGF.EmitAnyExpr(semantic, slot);
4376 // Otherwise, evaluate the expression in an ignored context.
4378 CGF.EmitIgnoredExpr(semantic);
4382 // Unbind all the opaques now.
4383 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4384 opaques[i].unbind(CGF);
4389 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4390 AggValueSlot slot) {
4391 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4394 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4395 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;