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/Frontend/CodeGenOptions.h"
28 #include "llvm/ADT/Hashing.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/Support/ConvertUTF.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Transforms/Utils/SanitizerStats.h"
39 using namespace clang;
40 using namespace CodeGen;
42 //===--------------------------------------------------------------------===//
43 // Miscellaneous Helper Methods
44 //===--------------------------------------------------------------------===//
46 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
47 unsigned addressSpace =
48 cast<llvm::PointerType>(value->getType())->getAddressSpace();
50 llvm::PointerType *destType = Int8PtrTy;
52 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
54 if (value->getType() == destType) return value;
55 return Builder.CreateBitCast(value, destType);
58 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
60 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
62 auto Alloca = CreateTempAlloca(Ty, Name);
63 Alloca->setAlignment(Align.getQuantity());
64 return Address(Alloca, Align);
67 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
69 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
71 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
74 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
75 /// default alignment of the corresponding LLVM type, which is *not*
76 /// guaranteed to be related in any way to the expected alignment of
77 /// an AST type that might have been lowered to Ty.
78 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
81 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
82 return CreateTempAlloca(Ty, Align, Name);
85 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
86 assert(isa<llvm::AllocaInst>(Var.getPointer()));
87 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
88 Store->setAlignment(Var.getAlignment().getQuantity());
89 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
90 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
93 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
94 CharUnits Align = getContext().getTypeAlignInChars(Ty);
95 return CreateTempAlloca(ConvertType(Ty), Align, Name);
98 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
99 // FIXME: Should we prefer the preferred type alignment here?
100 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
103 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
105 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
108 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
109 /// expression and compare the result against zero, returning an Int1Ty value.
110 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
111 PGO.setCurrentStmt(E);
112 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
113 llvm::Value *MemPtr = EmitScalarExpr(E);
114 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
117 QualType BoolTy = getContext().BoolTy;
118 SourceLocation Loc = E->getExprLoc();
119 if (!E->getType()->isAnyComplexType())
120 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
122 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
126 /// EmitIgnoredExpr - Emit code to compute the specified expression,
127 /// ignoring the result.
128 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
130 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
132 // Just emit it as an l-value and drop the result.
136 /// EmitAnyExpr - Emit code to compute the specified expression which
137 /// can have any type. The result is returned as an RValue struct.
138 /// If this is an aggregate expression, AggSlot indicates where the
139 /// result should be returned.
140 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
141 AggValueSlot aggSlot,
143 switch (getEvaluationKind(E->getType())) {
145 return RValue::get(EmitScalarExpr(E, ignoreResult));
147 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
149 if (!ignoreResult && aggSlot.isIgnored())
150 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
151 EmitAggExpr(E, aggSlot);
152 return aggSlot.asRValue();
154 llvm_unreachable("bad evaluation kind");
157 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
158 /// always be accessible even if no aggregate location is provided.
159 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
160 AggValueSlot AggSlot = AggValueSlot::ignored();
162 if (hasAggregateEvaluationKind(E->getType()))
163 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
164 return EmitAnyExpr(E, AggSlot);
167 /// EmitAnyExprToMem - Evaluate an expression into a given memory
169 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
173 // FIXME: This function should take an LValue as an argument.
174 switch (getEvaluationKind(E->getType())) {
176 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
180 case TEK_Aggregate: {
181 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
182 AggValueSlot::IsDestructed_t(IsInit),
183 AggValueSlot::DoesNotNeedGCBarriers,
184 AggValueSlot::IsAliased_t(!IsInit)));
189 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
190 LValue LV = MakeAddrLValue(Location, E->getType());
191 EmitStoreThroughLValue(RV, LV);
195 llvm_unreachable("bad evaluation kind");
199 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
200 const Expr *E, Address ReferenceTemporary) {
201 // Objective-C++ ARC:
202 // If we are binding a reference to a temporary that has ownership, we
203 // need to perform retain/release operations on the temporary.
205 // FIXME: This should be looking at E, not M.
206 if (auto Lifetime = M->getType().getObjCLifetime()) {
208 case Qualifiers::OCL_None:
209 case Qualifiers::OCL_ExplicitNone:
210 // Carry on to normal cleanup handling.
213 case Qualifiers::OCL_Autoreleasing:
214 // Nothing to do; cleaned up by an autorelease pool.
217 case Qualifiers::OCL_Strong:
218 case Qualifiers::OCL_Weak:
219 switch (StorageDuration Duration = M->getStorageDuration()) {
221 // Note: we intentionally do not register a cleanup to release
222 // the object on program termination.
226 // FIXME: We should probably register a cleanup in this case.
230 case SD_FullExpression:
231 CodeGenFunction::Destroyer *Destroy;
232 CleanupKind CleanupKind;
233 if (Lifetime == Qualifiers::OCL_Strong) {
234 const ValueDecl *VD = M->getExtendingDecl();
236 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
237 CleanupKind = CGF.getARCCleanupKind();
238 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
239 : &CodeGenFunction::destroyARCStrongImprecise;
241 // __weak objects always get EH cleanups; otherwise, exceptions
242 // could cause really nasty crashes instead of mere leaks.
243 CleanupKind = NormalAndEHCleanup;
244 Destroy = &CodeGenFunction::destroyARCWeak;
246 if (Duration == SD_FullExpression)
247 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
248 M->getType(), *Destroy,
249 CleanupKind & EHCleanup);
251 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
253 *Destroy, CleanupKind & EHCleanup);
257 llvm_unreachable("temporary cannot have dynamic storage duration");
259 llvm_unreachable("unknown storage duration");
263 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
264 if (const RecordType *RT =
265 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
266 // Get the destructor for the reference temporary.
267 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
268 if (!ClassDecl->hasTrivialDestructor())
269 ReferenceTemporaryDtor = ClassDecl->getDestructor();
272 if (!ReferenceTemporaryDtor)
275 // Call the destructor for the temporary.
276 switch (M->getStorageDuration()) {
279 llvm::Constant *CleanupFn;
280 llvm::Constant *CleanupArg;
281 if (E->getType()->isArrayType()) {
282 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
283 ReferenceTemporary, E->getType(),
284 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
285 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
286 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
288 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
289 StructorType::Complete);
290 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
292 CGF.CGM.getCXXABI().registerGlobalDtor(
293 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
297 case SD_FullExpression:
298 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
299 CodeGenFunction::destroyCXXObject,
300 CGF.getLangOpts().Exceptions);
304 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
305 ReferenceTemporary, E->getType(),
306 CodeGenFunction::destroyCXXObject,
307 CGF.getLangOpts().Exceptions);
311 llvm_unreachable("temporary cannot have dynamic storage duration");
316 createReferenceTemporary(CodeGenFunction &CGF,
317 const MaterializeTemporaryExpr *M, const Expr *Inner) {
318 switch (M->getStorageDuration()) {
319 case SD_FullExpression:
321 // If we have a constant temporary array or record try to promote it into a
322 // constant global under the same rules a normal constant would've been
323 // promoted. This is easier on the optimizer and generally emits fewer
325 QualType Ty = Inner->getType();
326 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
327 (Ty->isArrayType() || Ty->isRecordType()) &&
328 CGF.CGM.isTypeConstant(Ty, true))
329 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
330 auto *GV = new llvm::GlobalVariable(
331 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
332 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
333 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
334 GV->setAlignment(alignment.getQuantity());
335 // FIXME: Should we put the new global into a COMDAT?
336 return Address(GV, alignment);
338 return CGF.CreateMemTemp(Ty, "ref.tmp");
342 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
345 llvm_unreachable("temporary can't have dynamic storage duration");
347 llvm_unreachable("unknown storage duration");
350 LValue CodeGenFunction::
351 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
352 const Expr *E = M->GetTemporaryExpr();
354 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
355 // as that will cause the lifetime adjustment to be lost for ARC
356 auto ownership = M->getType().getObjCLifetime();
357 if (ownership != Qualifiers::OCL_None &&
358 ownership != Qualifiers::OCL_ExplicitNone) {
359 Address Object = createReferenceTemporary(*this, M, E);
360 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
361 Object = Address(llvm::ConstantExpr::getBitCast(Var,
362 ConvertTypeForMem(E->getType())
363 ->getPointerTo(Object.getAddressSpace())),
364 Object.getAlignment());
366 // createReferenceTemporary will promote the temporary to a global with a
367 // constant initializer if it can. It can only do this to a value of
368 // ARC-manageable type if the value is global and therefore "immune" to
369 // ref-counting operations. Therefore we have no need to emit either a
370 // dynamic initialization or a cleanup and we can just return the address
372 if (Var->hasInitializer())
373 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
375 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
377 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
378 AlignmentSource::Decl);
380 switch (getEvaluationKind(E->getType())) {
381 default: llvm_unreachable("expected scalar or aggregate expression");
383 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
385 case TEK_Aggregate: {
386 EmitAggExpr(E, AggValueSlot::forAddr(Object,
387 E->getType().getQualifiers(),
388 AggValueSlot::IsDestructed,
389 AggValueSlot::DoesNotNeedGCBarriers,
390 AggValueSlot::IsNotAliased));
395 pushTemporaryCleanup(*this, M, E, Object);
399 SmallVector<const Expr *, 2> CommaLHSs;
400 SmallVector<SubobjectAdjustment, 2> Adjustments;
401 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
403 for (const auto &Ignored : CommaLHSs)
404 EmitIgnoredExpr(Ignored);
406 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
407 if (opaque->getType()->isRecordType()) {
408 assert(Adjustments.empty());
409 return EmitOpaqueValueLValue(opaque);
413 // Create and initialize the reference temporary.
414 Address Object = createReferenceTemporary(*this, M, E);
415 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
416 Object = Address(llvm::ConstantExpr::getBitCast(
417 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
418 Object.getAlignment());
419 // If the temporary is a global and has a constant initializer or is a
420 // constant temporary that we promoted to a global, we may have already
422 if (!Var->hasInitializer()) {
423 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
424 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
427 switch (M->getStorageDuration()) {
429 case SD_FullExpression:
430 if (auto *Size = EmitLifetimeStart(
431 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
432 Object.getPointer())) {
433 if (M->getStorageDuration() == SD_Automatic)
434 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
437 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
444 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
446 pushTemporaryCleanup(*this, M, E, Object);
448 // Perform derived-to-base casts and/or field accesses, to get from the
449 // temporary object we created (and, potentially, for which we extended
450 // the lifetime) to the subobject we're binding the reference to.
451 for (unsigned I = Adjustments.size(); I != 0; --I) {
452 SubobjectAdjustment &Adjustment = Adjustments[I-1];
453 switch (Adjustment.Kind) {
454 case SubobjectAdjustment::DerivedToBaseAdjustment:
456 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
457 Adjustment.DerivedToBase.BasePath->path_begin(),
458 Adjustment.DerivedToBase.BasePath->path_end(),
459 /*NullCheckValue=*/ false, E->getExprLoc());
462 case SubobjectAdjustment::FieldAdjustment: {
463 LValue LV = MakeAddrLValue(Object, E->getType(),
464 AlignmentSource::Decl);
465 LV = EmitLValueForField(LV, Adjustment.Field);
466 assert(LV.isSimple() &&
467 "materialized temporary field is not a simple lvalue");
468 Object = LV.getAddress();
472 case SubobjectAdjustment::MemberPointerAdjustment: {
473 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
474 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
481 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
485 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
486 // Emit the expression as an lvalue.
487 LValue LV = EmitLValue(E);
488 assert(LV.isSimple());
489 llvm::Value *Value = LV.getPointer();
491 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
492 // C++11 [dcl.ref]p5 (as amended by core issue 453):
493 // If a glvalue to which a reference is directly bound designates neither
494 // an existing object or function of an appropriate type nor a region of
495 // storage of suitable size and alignment to contain an object of the
496 // reference's type, the behavior is undefined.
497 QualType Ty = E->getType();
498 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
501 return RValue::get(Value);
505 /// getAccessedFieldNo - Given an encoded value and a result number, return the
506 /// input field number being accessed.
507 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
508 const llvm::Constant *Elts) {
509 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
513 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
514 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
516 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
517 llvm::Value *K47 = Builder.getInt64(47);
518 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
519 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
520 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
521 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
522 return Builder.CreateMul(B1, KMul);
525 bool CodeGenFunction::sanitizePerformTypeCheck() const {
526 return SanOpts.has(SanitizerKind::Null) |
527 SanOpts.has(SanitizerKind::Alignment) |
528 SanOpts.has(SanitizerKind::ObjectSize) |
529 SanOpts.has(SanitizerKind::Vptr);
532 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
533 llvm::Value *Ptr, QualType Ty,
534 CharUnits Alignment, bool SkipNullCheck) {
535 if (!sanitizePerformTypeCheck())
538 // Don't check pointers outside the default address space. The null check
539 // isn't correct, the object-size check isn't supported by LLVM, and we can't
540 // communicate the addresses to the runtime handler for the vptr check.
541 if (Ptr->getType()->getPointerAddressSpace())
544 SanitizerScope SanScope(this);
546 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
547 llvm::BasicBlock *Done = nullptr;
549 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
550 TCK == TCK_UpcastToVirtualBase;
551 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
553 // The glvalue must not be an empty glvalue.
554 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
556 if (AllowNullPointers) {
557 // When performing pointer casts, it's OK if the value is null.
558 // Skip the remaining checks in that case.
559 Done = createBasicBlock("null");
560 llvm::BasicBlock *Rest = createBasicBlock("not.null");
561 Builder.CreateCondBr(IsNonNull, Rest, Done);
564 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
568 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
569 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
571 // The glvalue must refer to a large enough storage region.
572 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
574 // FIXME: Get object address space
575 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
576 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
577 llvm::Value *Min = Builder.getFalse();
578 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
579 llvm::Value *LargeEnough =
580 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
581 llvm::ConstantInt::get(IntPtrTy, Size));
582 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
585 uint64_t AlignVal = 0;
587 if (SanOpts.has(SanitizerKind::Alignment)) {
588 AlignVal = Alignment.getQuantity();
589 if (!Ty->isIncompleteType() && !AlignVal)
590 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
592 // The glvalue must be suitably aligned.
595 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
596 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
597 llvm::Value *Aligned =
598 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
599 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
603 if (Checks.size() > 0) {
604 llvm::Constant *StaticData[] = {
605 EmitCheckSourceLocation(Loc),
606 EmitCheckTypeDescriptor(Ty),
607 llvm::ConstantInt::get(SizeTy, AlignVal),
608 llvm::ConstantInt::get(Int8Ty, TCK)
610 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
613 // If possible, check that the vptr indicates that there is a subobject of
614 // type Ty at offset zero within this object.
616 // C++11 [basic.life]p5,6:
617 // [For storage which does not refer to an object within its lifetime]
618 // The program has undefined behavior if:
619 // -- the [pointer or glvalue] is used to access a non-static data member
620 // or call a non-static member function
621 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
622 if (SanOpts.has(SanitizerKind::Vptr) &&
623 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
624 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
625 TCK == TCK_UpcastToVirtualBase) &&
626 RD && RD->hasDefinition() && RD->isDynamicClass()) {
627 // Compute a hash of the mangled name of the type.
629 // FIXME: This is not guaranteed to be deterministic! Move to a
630 // fingerprinting mechanism once LLVM provides one. For the time
631 // being the implementation happens to be deterministic.
632 SmallString<64> MangledName;
633 llvm::raw_svector_ostream Out(MangledName);
634 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
637 // Blacklist based on the mangled type.
638 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
640 llvm::hash_code TypeHash = hash_value(Out.str());
642 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
643 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
644 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
645 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
646 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
647 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
649 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
650 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
652 // Look the hash up in our cache.
653 const int CacheSize = 128;
654 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
655 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
656 "__ubsan_vptr_type_cache");
657 llvm::Value *Slot = Builder.CreateAnd(Hash,
658 llvm::ConstantInt::get(IntPtrTy,
660 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
661 llvm::Value *CacheVal =
662 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
665 // If the hash isn't in the cache, call a runtime handler to perform the
666 // hard work of checking whether the vptr is for an object of the right
667 // type. This will either fill in the cache and return, or produce a
669 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
670 llvm::Constant *StaticData[] = {
671 EmitCheckSourceLocation(Loc),
672 EmitCheckTypeDescriptor(Ty),
673 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
674 llvm::ConstantInt::get(Int8Ty, TCK)
676 llvm::Value *DynamicData[] = { Ptr, Hash };
677 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
678 "dynamic_type_cache_miss", StaticData, DynamicData);
683 Builder.CreateBr(Done);
688 /// Determine whether this expression refers to a flexible array member in a
689 /// struct. We disable array bounds checks for such members.
690 static bool isFlexibleArrayMemberExpr(const Expr *E) {
691 // For compatibility with existing code, we treat arrays of length 0 or
692 // 1 as flexible array members.
693 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
694 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
695 if (CAT->getSize().ugt(1))
697 } else if (!isa<IncompleteArrayType>(AT))
700 E = E->IgnoreParens();
702 // A flexible array member must be the last member in the class.
703 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
704 // FIXME: If the base type of the member expr is not FD->getParent(),
705 // this should not be treated as a flexible array member access.
706 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
707 RecordDecl::field_iterator FI(
708 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
709 return ++FI == FD->getParent()->field_end();
711 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
712 return IRE->getDecl()->getNextIvar() == nullptr;
718 /// If Base is known to point to the start of an array, return the length of
719 /// that array. Return 0 if the length cannot be determined.
720 static llvm::Value *getArrayIndexingBound(
721 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
722 // For the vector indexing extension, the bound is the number of elements.
723 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
724 IndexedType = Base->getType();
725 return CGF.Builder.getInt32(VT->getNumElements());
728 Base = Base->IgnoreParens();
730 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
731 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
732 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
733 IndexedType = CE->getSubExpr()->getType();
734 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
735 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
736 return CGF.Builder.getInt(CAT->getSize());
737 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
738 return CGF.getVLASize(VAT).first;
745 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
746 llvm::Value *Index, QualType IndexType,
748 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
749 "should not be called unless adding bounds checks");
750 SanitizerScope SanScope(this);
752 QualType IndexedType;
753 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
757 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
758 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
759 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
761 llvm::Constant *StaticData[] = {
762 EmitCheckSourceLocation(E->getExprLoc()),
763 EmitCheckTypeDescriptor(IndexedType),
764 EmitCheckTypeDescriptor(IndexType)
766 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
767 : Builder.CreateICmpULE(IndexVal, BoundVal);
768 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
773 CodeGenFunction::ComplexPairTy CodeGenFunction::
774 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
775 bool isInc, bool isPre) {
776 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
778 llvm::Value *NextVal;
779 if (isa<llvm::IntegerType>(InVal.first->getType())) {
780 uint64_t AmountVal = isInc ? 1 : -1;
781 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
783 // Add the inc/dec to the real part.
784 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
786 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
787 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
790 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
792 // Add the inc/dec to the real part.
793 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
796 ComplexPairTy IncVal(NextVal, InVal.second);
798 // Store the updated result through the lvalue.
799 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
801 // If this is a postinc, return the value read from memory, otherwise use the
803 return isPre ? IncVal : InVal;
806 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
807 CodeGenFunction *CGF) {
808 // Bind VLAs in the cast type.
809 if (CGF && E->getType()->isVariablyModifiedType())
810 CGF->EmitVariablyModifiedType(E->getType());
812 if (CGDebugInfo *DI = getModuleDebugInfo())
813 DI->EmitExplicitCastType(E->getType());
816 //===----------------------------------------------------------------------===//
817 // LValue Expression Emission
818 //===----------------------------------------------------------------------===//
820 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
821 /// derive a more accurate bound on the alignment of the pointer.
822 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
823 AlignmentSource *Source) {
824 // We allow this with ObjC object pointers because of fragile ABIs.
825 assert(E->getType()->isPointerType() ||
826 E->getType()->isObjCObjectPointerType());
827 E = E->IgnoreParens();
830 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
831 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
832 CGM.EmitExplicitCastExprType(ECE, this);
834 switch (CE->getCastKind()) {
835 // Non-converting casts (but not C's implicit conversion from void*).
838 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
839 if (PtrTy->getPointeeType()->isVoidType())
842 AlignmentSource InnerSource;
843 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
844 if (Source) *Source = InnerSource;
846 // If this is an explicit bitcast, and the source l-value is
847 // opaque, honor the alignment of the casted-to type.
848 if (isa<ExplicitCastExpr>(CE) &&
849 InnerSource != AlignmentSource::Decl) {
850 Addr = Address(Addr.getPointer(),
851 getNaturalPointeeTypeAlignment(E->getType(), Source));
854 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
855 CE->getCastKind() == CK_BitCast) {
856 if (auto PT = E->getType()->getAs<PointerType>())
857 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
859 CodeGenFunction::CFITCK_UnrelatedCast,
863 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
867 // Array-to-pointer decay.
868 case CK_ArrayToPointerDecay:
869 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
871 // Derived-to-base conversions.
872 case CK_UncheckedDerivedToBase:
873 case CK_DerivedToBase: {
874 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
875 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
876 return GetAddressOfBaseClass(Addr, Derived,
877 CE->path_begin(), CE->path_end(),
878 ShouldNullCheckClassCastValue(CE),
882 // TODO: Is there any reason to treat base-to-derived conversions
890 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
891 if (UO->getOpcode() == UO_AddrOf) {
892 LValue LV = EmitLValue(UO->getSubExpr());
893 if (Source) *Source = LV.getAlignmentSource();
894 return LV.getAddress();
898 // TODO: conditional operators, comma.
900 // Otherwise, use the alignment of the type.
901 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
902 return Address(EmitScalarExpr(E), Align);
905 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
906 if (Ty->isVoidType())
907 return RValue::get(nullptr);
909 switch (getEvaluationKind(Ty)) {
912 ConvertType(Ty->castAs<ComplexType>()->getElementType());
913 llvm::Value *U = llvm::UndefValue::get(EltTy);
914 return RValue::getComplex(std::make_pair(U, U));
917 // If this is a use of an undefined aggregate type, the aggregate must have an
918 // identifiable address. Just because the contents of the value are undefined
919 // doesn't mean that the address can't be taken and compared.
920 case TEK_Aggregate: {
921 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
922 return RValue::getAggregate(DestPtr);
926 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
928 llvm_unreachable("bad evaluation kind");
931 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
933 ErrorUnsupported(E, Name);
934 return GetUndefRValue(E->getType());
937 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
939 ErrorUnsupported(E, Name);
940 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
941 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
945 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
947 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
948 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
951 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
952 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
953 E->getType(), LV.getAlignment());
957 /// EmitLValue - Emit code to compute a designator that specifies the location
958 /// of the expression.
960 /// This can return one of two things: a simple address or a bitfield reference.
961 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
962 /// an LLVM pointer type.
964 /// If this returns a bitfield reference, nothing about the pointee type of the
965 /// LLVM value is known: For example, it may not be a pointer to an integer.
967 /// If this returns a normal address, and if the lvalue's C type is fixed size,
968 /// this method guarantees that the returned pointer type will point to an LLVM
969 /// type of the same size of the lvalue's type. If the lvalue has a variable
970 /// length type, this is not possible.
972 LValue CodeGenFunction::EmitLValue(const Expr *E) {
973 ApplyDebugLocation DL(*this, E);
974 switch (E->getStmtClass()) {
975 default: return EmitUnsupportedLValue(E, "l-value expression");
977 case Expr::ObjCPropertyRefExprClass:
978 llvm_unreachable("cannot emit a property reference directly");
980 case Expr::ObjCSelectorExprClass:
981 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
982 case Expr::ObjCIsaExprClass:
983 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
984 case Expr::BinaryOperatorClass:
985 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
986 case Expr::CompoundAssignOperatorClass: {
987 QualType Ty = E->getType();
988 if (const AtomicType *AT = Ty->getAs<AtomicType>())
989 Ty = AT->getValueType();
990 if (!Ty->isAnyComplexType())
991 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
992 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
994 case Expr::CallExprClass:
995 case Expr::CXXMemberCallExprClass:
996 case Expr::CXXOperatorCallExprClass:
997 case Expr::UserDefinedLiteralClass:
998 return EmitCallExprLValue(cast<CallExpr>(E));
999 case Expr::VAArgExprClass:
1000 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1001 case Expr::DeclRefExprClass:
1002 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1003 case Expr::ParenExprClass:
1004 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1005 case Expr::GenericSelectionExprClass:
1006 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1007 case Expr::PredefinedExprClass:
1008 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1009 case Expr::StringLiteralClass:
1010 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1011 case Expr::ObjCEncodeExprClass:
1012 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1013 case Expr::PseudoObjectExprClass:
1014 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1015 case Expr::InitListExprClass:
1016 return EmitInitListLValue(cast<InitListExpr>(E));
1017 case Expr::CXXTemporaryObjectExprClass:
1018 case Expr::CXXConstructExprClass:
1019 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1020 case Expr::CXXBindTemporaryExprClass:
1021 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1022 case Expr::CXXUuidofExprClass:
1023 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1024 case Expr::LambdaExprClass:
1025 return EmitLambdaLValue(cast<LambdaExpr>(E));
1027 case Expr::ExprWithCleanupsClass: {
1028 const auto *cleanups = cast<ExprWithCleanups>(E);
1029 enterFullExpression(cleanups);
1030 RunCleanupsScope Scope(*this);
1031 return EmitLValue(cleanups->getSubExpr());
1034 case Expr::CXXDefaultArgExprClass:
1035 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1036 case Expr::CXXDefaultInitExprClass: {
1037 CXXDefaultInitExprScope Scope(*this);
1038 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1040 case Expr::CXXTypeidExprClass:
1041 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1043 case Expr::ObjCMessageExprClass:
1044 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1045 case Expr::ObjCIvarRefExprClass:
1046 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1047 case Expr::StmtExprClass:
1048 return EmitStmtExprLValue(cast<StmtExpr>(E));
1049 case Expr::UnaryOperatorClass:
1050 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1051 case Expr::ArraySubscriptExprClass:
1052 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1053 case Expr::OMPArraySectionExprClass:
1054 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1055 case Expr::ExtVectorElementExprClass:
1056 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1057 case Expr::MemberExprClass:
1058 return EmitMemberExpr(cast<MemberExpr>(E));
1059 case Expr::CompoundLiteralExprClass:
1060 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1061 case Expr::ConditionalOperatorClass:
1062 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1063 case Expr::BinaryConditionalOperatorClass:
1064 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1065 case Expr::ChooseExprClass:
1066 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1067 case Expr::OpaqueValueExprClass:
1068 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1069 case Expr::SubstNonTypeTemplateParmExprClass:
1070 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1071 case Expr::ImplicitCastExprClass:
1072 case Expr::CStyleCastExprClass:
1073 case Expr::CXXFunctionalCastExprClass:
1074 case Expr::CXXStaticCastExprClass:
1075 case Expr::CXXDynamicCastExprClass:
1076 case Expr::CXXReinterpretCastExprClass:
1077 case Expr::CXXConstCastExprClass:
1078 case Expr::ObjCBridgedCastExprClass:
1079 return EmitCastLValue(cast<CastExpr>(E));
1081 case Expr::MaterializeTemporaryExprClass:
1082 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1086 /// Given an object of the given canonical type, can we safely copy a
1087 /// value out of it based on its initializer?
1088 static bool isConstantEmittableObjectType(QualType type) {
1089 assert(type.isCanonical());
1090 assert(!type->isReferenceType());
1092 // Must be const-qualified but non-volatile.
1093 Qualifiers qs = type.getLocalQualifiers();
1094 if (!qs.hasConst() || qs.hasVolatile()) return false;
1096 // Otherwise, all object types satisfy this except C++ classes with
1097 // mutable subobjects or non-trivial copy/destroy behavior.
1098 if (const auto *RT = dyn_cast<RecordType>(type))
1099 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1100 if (RD->hasMutableFields() || !RD->isTrivial())
1106 /// Can we constant-emit a load of a reference to a variable of the
1107 /// given type? This is different from predicates like
1108 /// Decl::isUsableInConstantExpressions because we do want it to apply
1109 /// in situations that don't necessarily satisfy the language's rules
1110 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1111 /// to do this with const float variables even if those variables
1112 /// aren't marked 'constexpr'.
1113 enum ConstantEmissionKind {
1115 CEK_AsReferenceOnly,
1116 CEK_AsValueOrReference,
1119 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1120 type = type.getCanonicalType();
1121 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1122 if (isConstantEmittableObjectType(ref->getPointeeType()))
1123 return CEK_AsValueOrReference;
1124 return CEK_AsReferenceOnly;
1126 if (isConstantEmittableObjectType(type))
1127 return CEK_AsValueOnly;
1131 /// Try to emit a reference to the given value without producing it as
1132 /// an l-value. This is actually more than an optimization: we can't
1133 /// produce an l-value for variables that we never actually captured
1134 /// in a block or lambda, which means const int variables or constexpr
1135 /// literals or similar.
1136 CodeGenFunction::ConstantEmission
1137 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1138 ValueDecl *value = refExpr->getDecl();
1140 // The value needs to be an enum constant or a constant variable.
1141 ConstantEmissionKind CEK;
1142 if (isa<ParmVarDecl>(value)) {
1144 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1145 CEK = checkVarTypeForConstantEmission(var->getType());
1146 } else if (isa<EnumConstantDecl>(value)) {
1147 CEK = CEK_AsValueOnly;
1151 if (CEK == CEK_None) return ConstantEmission();
1153 Expr::EvalResult result;
1154 bool resultIsReference;
1155 QualType resultType;
1157 // It's best to evaluate all the way as an r-value if that's permitted.
1158 if (CEK != CEK_AsReferenceOnly &&
1159 refExpr->EvaluateAsRValue(result, getContext())) {
1160 resultIsReference = false;
1161 resultType = refExpr->getType();
1163 // Otherwise, try to evaluate as an l-value.
1164 } else if (CEK != CEK_AsValueOnly &&
1165 refExpr->EvaluateAsLValue(result, getContext())) {
1166 resultIsReference = true;
1167 resultType = value->getType();
1171 return ConstantEmission();
1174 // In any case, if the initializer has side-effects, abandon ship.
1175 if (result.HasSideEffects)
1176 return ConstantEmission();
1178 // Emit as a constant.
1179 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1181 // Make sure we emit a debug reference to the global variable.
1182 // This should probably fire even for
1183 if (isa<VarDecl>(value)) {
1184 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1185 EmitDeclRefExprDbgValue(refExpr, result.Val);
1187 assert(isa<EnumConstantDecl>(value));
1188 EmitDeclRefExprDbgValue(refExpr, result.Val);
1191 // If we emitted a reference constant, we need to dereference that.
1192 if (resultIsReference)
1193 return ConstantEmission::forReference(C);
1195 return ConstantEmission::forValue(C);
1198 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1199 SourceLocation Loc) {
1200 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1201 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1202 lvalue.getTBAAInfo(),
1203 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1204 lvalue.isNontemporal());
1207 static bool hasBooleanRepresentation(QualType Ty) {
1208 if (Ty->isBooleanType())
1211 if (const EnumType *ET = Ty->getAs<EnumType>())
1212 return ET->getDecl()->getIntegerType()->isBooleanType();
1214 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1215 return hasBooleanRepresentation(AT->getValueType());
1220 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1221 llvm::APInt &Min, llvm::APInt &End,
1223 const EnumType *ET = Ty->getAs<EnumType>();
1224 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1225 ET && !ET->getDecl()->isFixed();
1226 bool IsBool = hasBooleanRepresentation(Ty);
1227 if (!IsBool && !IsRegularCPlusPlusEnum)
1231 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1232 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1234 const EnumDecl *ED = ET->getDecl();
1235 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1236 unsigned Bitwidth = LTy->getScalarSizeInBits();
1237 unsigned NumNegativeBits = ED->getNumNegativeBits();
1238 unsigned NumPositiveBits = ED->getNumPositiveBits();
1240 if (NumNegativeBits) {
1241 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1242 assert(NumBits <= Bitwidth);
1243 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1246 assert(NumPositiveBits <= Bitwidth);
1247 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1248 Min = llvm::APInt(Bitwidth, 0);
1254 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1255 llvm::APInt Min, End;
1256 if (!getRangeForType(*this, Ty, Min, End,
1257 CGM.getCodeGenOpts().StrictEnums))
1260 llvm::MDBuilder MDHelper(getLLVMContext());
1261 return MDHelper.createRange(Min, End);
1264 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1267 AlignmentSource AlignSource,
1268 llvm::MDNode *TBAAInfo,
1269 QualType TBAABaseType,
1270 uint64_t TBAAOffset,
1271 bool isNontemporal) {
1272 // For better performance, handle vector loads differently.
1273 if (Ty->isVectorType()) {
1274 const llvm::Type *EltTy = Addr.getElementType();
1276 const auto *VTy = cast<llvm::VectorType>(EltTy);
1278 // Handle vectors of size 3 like size 4 for better performance.
1279 if (VTy->getNumElements() == 3) {
1281 // Bitcast to vec4 type.
1282 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1284 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1286 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1288 // Shuffle vector to get vec3.
1289 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1290 {0, 1, 2}, "extractVec");
1291 return EmitFromMemory(V, Ty);
1295 // Atomic operations have to be done on integral types.
1296 LValue AtomicLValue =
1297 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1298 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1299 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1302 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1303 if (isNontemporal) {
1304 llvm::MDNode *Node = llvm::MDNode::get(
1305 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1306 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1309 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1312 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1313 false /*ConvertTypeToTag*/);
1316 bool NeedsBoolCheck =
1317 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1318 bool NeedsEnumCheck =
1319 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1320 if (NeedsBoolCheck || NeedsEnumCheck) {
1321 SanitizerScope SanScope(this);
1322 llvm::APInt Min, End;
1323 if (getRangeForType(*this, Ty, Min, End, true)) {
1327 Check = Builder.CreateICmpULE(
1328 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1330 llvm::Value *Upper = Builder.CreateICmpSLE(
1331 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1332 llvm::Value *Lower = Builder.CreateICmpSGE(
1333 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1334 Check = Builder.CreateAnd(Upper, Lower);
1336 llvm::Constant *StaticArgs[] = {
1337 EmitCheckSourceLocation(Loc),
1338 EmitCheckTypeDescriptor(Ty)
1340 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1341 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1342 EmitCheckValue(Load));
1344 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1345 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1346 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1348 return EmitFromMemory(Load, Ty);
1351 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1352 // Bool has a different representation in memory than in registers.
1353 if (hasBooleanRepresentation(Ty)) {
1354 // This should really always be an i1, but sometimes it's already
1355 // an i8, and it's awkward to track those cases down.
1356 if (Value->getType()->isIntegerTy(1))
1357 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1358 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1359 "wrong value rep of bool");
1365 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1366 // Bool has a different representation in memory than in registers.
1367 if (hasBooleanRepresentation(Ty)) {
1368 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1369 "wrong value rep of bool");
1370 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1376 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1377 bool Volatile, QualType Ty,
1378 AlignmentSource AlignSource,
1379 llvm::MDNode *TBAAInfo,
1380 bool isInit, QualType TBAABaseType,
1381 uint64_t TBAAOffset,
1382 bool isNontemporal) {
1384 // Handle vectors differently to get better performance.
1385 if (Ty->isVectorType()) {
1386 llvm::Type *SrcTy = Value->getType();
1387 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1388 // Handle vec3 special.
1389 if (VecTy->getNumElements() == 3) {
1390 // Our source is a vec3, do a shuffle vector to make it a vec4.
1391 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1392 Builder.getInt32(2),
1393 llvm::UndefValue::get(Builder.getInt32Ty())};
1394 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1395 Value = Builder.CreateShuffleVector(Value,
1396 llvm::UndefValue::get(VecTy),
1397 MaskV, "extractVec");
1398 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1400 if (Addr.getElementType() != SrcTy) {
1401 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1405 Value = EmitToMemory(Value, Ty);
1407 LValue AtomicLValue =
1408 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1409 if (Ty->isAtomicType() ||
1410 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1411 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1415 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1416 if (isNontemporal) {
1417 llvm::MDNode *Node =
1418 llvm::MDNode::get(Store->getContext(),
1419 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1420 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1423 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1426 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1427 false /*ConvertTypeToTag*/);
1431 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1433 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1434 lvalue.getType(), lvalue.getAlignmentSource(),
1435 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1436 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1439 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1440 /// method emits the address of the lvalue, then loads the result as an rvalue,
1441 /// returning the rvalue.
1442 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1443 if (LV.isObjCWeak()) {
1444 // load of a __weak object.
1445 Address AddrWeakObj = LV.getAddress();
1446 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1449 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1450 // In MRC mode, we do a load+autorelease.
1451 if (!getLangOpts().ObjCAutoRefCount) {
1452 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1455 // In ARC mode, we load retained and then consume the value.
1456 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1457 Object = EmitObjCConsumeObject(LV.getType(), Object);
1458 return RValue::get(Object);
1461 if (LV.isSimple()) {
1462 assert(!LV.getType()->isFunctionType());
1464 // Everything needs a load.
1465 return RValue::get(EmitLoadOfScalar(LV, Loc));
1468 if (LV.isVectorElt()) {
1469 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1470 LV.isVolatileQualified());
1471 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1475 // If this is a reference to a subset of the elements of a vector, either
1476 // shuffle the input or extract/insert them as appropriate.
1477 if (LV.isExtVectorElt())
1478 return EmitLoadOfExtVectorElementLValue(LV);
1480 // Global Register variables always invoke intrinsics
1481 if (LV.isGlobalReg())
1482 return EmitLoadOfGlobalRegLValue(LV);
1484 assert(LV.isBitField() && "Unknown LValue type!");
1485 return EmitLoadOfBitfieldLValue(LV);
1488 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1489 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1491 // Get the output type.
1492 llvm::Type *ResLTy = ConvertType(LV.getType());
1494 Address Ptr = LV.getBitFieldAddress();
1495 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1497 if (Info.IsSigned) {
1498 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1499 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1501 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1502 if (Info.Offset + HighBits)
1503 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1506 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1507 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1508 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1512 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1514 return RValue::get(Val);
1517 // If this is a reference to a subset of the elements of a vector, create an
1518 // appropriate shufflevector.
1519 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1520 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1521 LV.isVolatileQualified());
1523 const llvm::Constant *Elts = LV.getExtVectorElts();
1525 // If the result of the expression is a non-vector type, we must be extracting
1526 // a single element. Just codegen as an extractelement.
1527 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1529 unsigned InIdx = getAccessedFieldNo(0, Elts);
1530 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1531 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1534 // Always use shuffle vector to try to retain the original program structure
1535 unsigned NumResultElts = ExprVT->getNumElements();
1537 SmallVector<llvm::Constant*, 4> Mask;
1538 for (unsigned i = 0; i != NumResultElts; ++i)
1539 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1541 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1542 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1544 return RValue::get(Vec);
1547 /// @brief Generates lvalue for partial ext_vector access.
1548 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1549 Address VectorAddress = LV.getExtVectorAddress();
1550 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1551 QualType EQT = ExprVT->getElementType();
1552 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1554 Address CastToPointerElement =
1555 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1556 "conv.ptr.element");
1558 const llvm::Constant *Elts = LV.getExtVectorElts();
1559 unsigned ix = getAccessedFieldNo(0, Elts);
1561 Address VectorBasePtrPlusIx =
1562 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1563 getContext().getTypeSizeInChars(EQT),
1566 return VectorBasePtrPlusIx;
1569 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1570 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1571 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1572 "Bad type for register variable");
1573 llvm::MDNode *RegName = cast<llvm::MDNode>(
1574 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1576 // We accept integer and pointer types only
1577 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1578 llvm::Type *Ty = OrigTy;
1579 if (OrigTy->isPointerTy())
1580 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1581 llvm::Type *Types[] = { Ty };
1583 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1584 llvm::Value *Call = Builder.CreateCall(
1585 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1586 if (OrigTy->isPointerTy())
1587 Call = Builder.CreateIntToPtr(Call, OrigTy);
1588 return RValue::get(Call);
1592 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1593 /// lvalue, where both are guaranteed to the have the same type, and that type
1595 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1597 if (!Dst.isSimple()) {
1598 if (Dst.isVectorElt()) {
1599 // Read/modify/write the vector, inserting the new element.
1600 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1601 Dst.isVolatileQualified());
1602 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1603 Dst.getVectorIdx(), "vecins");
1604 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1605 Dst.isVolatileQualified());
1609 // If this is an update of extended vector elements, insert them as
1611 if (Dst.isExtVectorElt())
1612 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1614 if (Dst.isGlobalReg())
1615 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1617 assert(Dst.isBitField() && "Unknown LValue type");
1618 return EmitStoreThroughBitfieldLValue(Src, Dst);
1621 // There's special magic for assigning into an ARC-qualified l-value.
1622 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1624 case Qualifiers::OCL_None:
1625 llvm_unreachable("present but none");
1627 case Qualifiers::OCL_ExplicitNone:
1631 case Qualifiers::OCL_Strong:
1633 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1636 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1639 case Qualifiers::OCL_Weak:
1641 // Initialize and then skip the primitive store.
1642 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1644 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1647 case Qualifiers::OCL_Autoreleasing:
1648 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1649 Src.getScalarVal()));
1650 // fall into the normal path
1655 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1656 // load of a __weak object.
1657 Address LvalueDst = Dst.getAddress();
1658 llvm::Value *src = Src.getScalarVal();
1659 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1663 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1664 // load of a __strong object.
1665 Address LvalueDst = Dst.getAddress();
1666 llvm::Value *src = Src.getScalarVal();
1667 if (Dst.isObjCIvar()) {
1668 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1669 llvm::Type *ResultType = IntPtrTy;
1670 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1671 llvm::Value *RHS = dst.getPointer();
1672 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1674 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1675 "sub.ptr.lhs.cast");
1676 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1677 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1679 } else if (Dst.isGlobalObjCRef()) {
1680 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1681 Dst.isThreadLocalRef());
1684 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1688 assert(Src.isScalar() && "Can't emit an agg store with this method");
1689 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1692 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1693 llvm::Value **Result) {
1694 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1695 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1696 Address Ptr = Dst.getBitFieldAddress();
1698 // Get the source value, truncated to the width of the bit-field.
1699 llvm::Value *SrcVal = Src.getScalarVal();
1701 // Cast the source to the storage type and shift it into place.
1702 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1703 /*IsSigned=*/false);
1704 llvm::Value *MaskedVal = SrcVal;
1706 // See if there are other bits in the bitfield's storage we'll need to load
1707 // and mask together with source before storing.
1708 if (Info.StorageSize != Info.Size) {
1709 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1711 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1713 // Mask the source value as needed.
1714 if (!hasBooleanRepresentation(Dst.getType()))
1715 SrcVal = Builder.CreateAnd(SrcVal,
1716 llvm::APInt::getLowBitsSet(Info.StorageSize,
1721 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1723 // Mask out the original value.
1724 Val = Builder.CreateAnd(Val,
1725 ~llvm::APInt::getBitsSet(Info.StorageSize,
1727 Info.Offset + Info.Size),
1730 // Or together the unchanged values and the source value.
1731 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1733 assert(Info.Offset == 0);
1736 // Write the new value back out.
1737 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1739 // Return the new value of the bit-field, if requested.
1741 llvm::Value *ResultVal = MaskedVal;
1743 // Sign extend the value if needed.
1744 if (Info.IsSigned) {
1745 assert(Info.Size <= Info.StorageSize);
1746 unsigned HighBits = Info.StorageSize - Info.Size;
1748 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1749 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1753 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1755 *Result = EmitFromMemory(ResultVal, Dst.getType());
1759 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1761 // This access turns into a read/modify/write of the vector. Load the input
1763 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1764 Dst.isVolatileQualified());
1765 const llvm::Constant *Elts = Dst.getExtVectorElts();
1767 llvm::Value *SrcVal = Src.getScalarVal();
1769 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1770 unsigned NumSrcElts = VTy->getNumElements();
1771 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1772 if (NumDstElts == NumSrcElts) {
1773 // Use shuffle vector is the src and destination are the same number of
1774 // elements and restore the vector mask since it is on the side it will be
1776 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1777 for (unsigned i = 0; i != NumSrcElts; ++i)
1778 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1780 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1781 Vec = Builder.CreateShuffleVector(SrcVal,
1782 llvm::UndefValue::get(Vec->getType()),
1784 } else if (NumDstElts > NumSrcElts) {
1785 // Extended the source vector to the same length and then shuffle it
1786 // into the destination.
1787 // FIXME: since we're shuffling with undef, can we just use the indices
1788 // into that? This could be simpler.
1789 SmallVector<llvm::Constant*, 4> ExtMask;
1790 for (unsigned i = 0; i != NumSrcElts; ++i)
1791 ExtMask.push_back(Builder.getInt32(i));
1792 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1793 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1794 llvm::Value *ExtSrcVal =
1795 Builder.CreateShuffleVector(SrcVal,
1796 llvm::UndefValue::get(SrcVal->getType()),
1799 SmallVector<llvm::Constant*, 4> Mask;
1800 for (unsigned i = 0; i != NumDstElts; ++i)
1801 Mask.push_back(Builder.getInt32(i));
1803 // When the vector size is odd and .odd or .hi is used, the last element
1804 // of the Elts constant array will be one past the size of the vector.
1805 // Ignore the last element here, if it is greater than the mask size.
1806 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1809 // modify when what gets shuffled in
1810 for (unsigned i = 0; i != NumSrcElts; ++i)
1811 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1812 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1813 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1815 // We should never shorten the vector
1816 llvm_unreachable("unexpected shorten vector length");
1819 // If the Src is a scalar (not a vector) it must be updating one element.
1820 unsigned InIdx = getAccessedFieldNo(0, Elts);
1821 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1822 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1825 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1826 Dst.isVolatileQualified());
1829 /// @brief Store of global named registers are always calls to intrinsics.
1830 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1831 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1832 "Bad type for register variable");
1833 llvm::MDNode *RegName = cast<llvm::MDNode>(
1834 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1835 assert(RegName && "Register LValue is not metadata");
1837 // We accept integer and pointer types only
1838 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1839 llvm::Type *Ty = OrigTy;
1840 if (OrigTy->isPointerTy())
1841 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1842 llvm::Type *Types[] = { Ty };
1844 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1845 llvm::Value *Value = Src.getScalarVal();
1846 if (OrigTy->isPointerTy())
1847 Value = Builder.CreatePtrToInt(Value, Ty);
1849 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1852 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1853 // generating write-barries API. It is currently a global, ivar,
1855 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1857 bool IsMemberAccess=false) {
1858 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1861 if (isa<ObjCIvarRefExpr>(E)) {
1862 QualType ExpTy = E->getType();
1863 if (IsMemberAccess && ExpTy->isPointerType()) {
1864 // If ivar is a structure pointer, assigning to field of
1865 // this struct follows gcc's behavior and makes it a non-ivar
1866 // writer-barrier conservatively.
1867 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1868 if (ExpTy->isRecordType()) {
1869 LV.setObjCIvar(false);
1873 LV.setObjCIvar(true);
1874 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1875 LV.setBaseIvarExp(Exp->getBase());
1876 LV.setObjCArray(E->getType()->isArrayType());
1880 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1881 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1882 if (VD->hasGlobalStorage()) {
1883 LV.setGlobalObjCRef(true);
1884 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1887 LV.setObjCArray(E->getType()->isArrayType());
1891 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1892 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1896 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1897 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1898 if (LV.isObjCIvar()) {
1899 // If cast is to a structure pointer, follow gcc's behavior and make it
1900 // a non-ivar write-barrier.
1901 QualType ExpTy = E->getType();
1902 if (ExpTy->isPointerType())
1903 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1904 if (ExpTy->isRecordType())
1905 LV.setObjCIvar(false);
1910 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1911 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1915 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1916 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1920 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1921 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1925 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1926 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1930 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1931 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1932 if (LV.isObjCIvar() && !LV.isObjCArray())
1933 // Using array syntax to assigning to what an ivar points to is not
1934 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1935 LV.setObjCIvar(false);
1936 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1937 // Using array syntax to assigning to what global points to is not
1938 // same as assigning to the global itself. {id *G;} G[i] = 0;
1939 LV.setGlobalObjCRef(false);
1943 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
1944 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1945 // We don't know if member is an 'ivar', but this flag is looked at
1946 // only in the context of LV.isObjCIvar().
1947 LV.setObjCArray(E->getType()->isArrayType());
1952 static llvm::Value *
1953 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1954 llvm::Value *V, llvm::Type *IRType,
1955 StringRef Name = StringRef()) {
1956 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1957 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1960 static LValue EmitThreadPrivateVarDeclLValue(
1961 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1962 llvm::Type *RealVarTy, SourceLocation Loc) {
1963 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1964 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1965 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1968 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1969 const ReferenceType *RefTy,
1970 AlignmentSource *Source) {
1971 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1972 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1973 Source, /*forPointee*/ true));
1977 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1978 const ReferenceType *RefTy) {
1979 AlignmentSource Source;
1980 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1981 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
1984 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1985 const PointerType *PtrTy,
1986 AlignmentSource *Source) {
1987 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1988 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1989 /*forPointeeType=*/true));
1992 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1993 const PointerType *PtrTy) {
1994 AlignmentSource Source;
1995 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
1996 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
1999 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2000 const Expr *E, const VarDecl *VD) {
2001 QualType T = E->getType();
2003 // If it's thread_local, emit a call to its wrapper function instead.
2004 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2005 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2006 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2008 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2009 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2010 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2011 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2012 Address Addr(V, Alignment);
2014 // Emit reference to the private copy of the variable if it is an OpenMP
2015 // threadprivate variable.
2016 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2017 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2019 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2020 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2022 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2024 setObjCGCLValueClass(CGF.getContext(), E, LV);
2028 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2029 const Expr *E, const FunctionDecl *FD) {
2030 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
2031 if (!FD->hasPrototype()) {
2032 if (const FunctionProtoType *Proto =
2033 FD->getType()->getAs<FunctionProtoType>()) {
2034 // Ugly case: for a K&R-style definition, the type of the definition
2035 // isn't the same as the type of a use. Correct for this with a
2037 QualType NoProtoType =
2038 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
2039 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
2040 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
2043 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2044 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2047 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2048 llvm::Value *ThisValue) {
2049 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2050 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2051 return CGF.EmitLValueForField(LV, FD);
2054 /// Named Registers are named metadata pointing to the register name
2055 /// which will be read from/written to as an argument to the intrinsic
2056 /// @llvm.read/write_register.
2057 /// So far, only the name is being passed down, but other options such as
2058 /// register type, allocation type or even optimization options could be
2059 /// passed down via the metadata node.
2060 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2061 SmallString<64> Name("llvm.named.register.");
2062 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2063 assert(Asm->getLabel().size() < 64-Name.size() &&
2064 "Register name too big");
2065 Name.append(Asm->getLabel());
2066 llvm::NamedMDNode *M =
2067 CGM.getModule().getOrInsertNamedMetadata(Name);
2068 if (M->getNumOperands() == 0) {
2069 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2071 llvm::Metadata *Ops[] = {Str};
2072 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2075 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2078 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2079 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2082 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2083 const NamedDecl *ND = E->getDecl();
2084 QualType T = E->getType();
2086 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2087 // Global Named registers access via intrinsics only
2088 if (VD->getStorageClass() == SC_Register &&
2089 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2090 return EmitGlobalNamedRegister(VD, CGM);
2092 // A DeclRefExpr for a reference initialized by a constant expression can
2093 // appear without being odr-used. Directly emit the constant initializer.
2094 const Expr *Init = VD->getAnyInitializer(VD);
2095 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2096 VD->isUsableInConstantExpressions(getContext()) &&
2097 VD->checkInitIsICE() &&
2098 // Do not emit if it is private OpenMP variable.
2099 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2100 LocalDeclMap.count(VD))) {
2101 llvm::Constant *Val =
2102 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2103 assert(Val && "failed to emit reference constant expression");
2104 // FIXME: Eventually we will want to emit vector element references.
2106 // Should we be using the alignment of the constant pointer we emitted?
2107 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2110 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2113 // Check for captured variables.
2114 if (E->refersToEnclosingVariableOrCapture()) {
2115 if (auto *FD = LambdaCaptureFields.lookup(VD))
2116 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2117 else if (CapturedStmtInfo) {
2118 auto it = LocalDeclMap.find(VD);
2119 if (it != LocalDeclMap.end()) {
2120 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2121 return EmitLoadOfReferenceLValue(it->second, RefTy);
2123 return MakeAddrLValue(it->second, T);
2126 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2127 CapturedStmtInfo->getContextValue());
2128 return MakeAddrLValue(
2129 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2130 CapLVal.getType(), AlignmentSource::Decl);
2133 assert(isa<BlockDecl>(CurCodeDecl));
2134 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2135 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2139 // FIXME: We should be able to assert this for FunctionDecls as well!
2140 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2141 // those with a valid source location.
2142 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2143 !E->getLocation().isValid()) &&
2144 "Should not use decl without marking it used!");
2146 if (ND->hasAttr<WeakRefAttr>()) {
2147 const auto *VD = cast<ValueDecl>(ND);
2148 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2149 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2152 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2153 // Check if this is a global variable.
2154 if (VD->hasLinkage() || VD->isStaticDataMember())
2155 return EmitGlobalVarDeclLValue(*this, E, VD);
2157 Address addr = Address::invalid();
2159 // The variable should generally be present in the local decl map.
2160 auto iter = LocalDeclMap.find(VD);
2161 if (iter != LocalDeclMap.end()) {
2162 addr = iter->second;
2164 // Otherwise, it might be static local we haven't emitted yet for
2165 // some reason; most likely, because it's in an outer function.
2166 } else if (VD->isStaticLocal()) {
2167 addr = Address(CGM.getOrCreateStaticVarDecl(
2168 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2169 getContext().getDeclAlign(VD));
2171 // No other cases for now.
2173 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2177 // Check for OpenMP threadprivate variables.
2178 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2179 return EmitThreadPrivateVarDeclLValue(
2180 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2184 // Drill into block byref variables.
2185 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2187 addr = emitBlockByrefAddress(addr, VD);
2190 // Drill into reference types.
2192 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2193 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2195 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2198 bool isLocalStorage = VD->hasLocalStorage();
2200 bool NonGCable = isLocalStorage &&
2201 !VD->getType()->isReferenceType() &&
2204 LV.getQuals().removeObjCGCAttr();
2208 bool isImpreciseLifetime =
2209 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2210 if (isImpreciseLifetime)
2211 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2212 setObjCGCLValueClass(getContext(), E, LV);
2216 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2217 return EmitFunctionDeclLValue(*this, E, FD);
2219 // FIXME: While we're emitting a binding from an enclosing scope, all other
2220 // DeclRefExprs we see should be implicitly treated as if they also refer to
2221 // an enclosing scope.
2222 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2223 return EmitLValue(BD->getBinding());
2225 llvm_unreachable("Unhandled DeclRefExpr");
2228 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2229 // __extension__ doesn't affect lvalue-ness.
2230 if (E->getOpcode() == UO_Extension)
2231 return EmitLValue(E->getSubExpr());
2233 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2234 switch (E->getOpcode()) {
2235 default: llvm_unreachable("Unknown unary operator lvalue!");
2237 QualType T = E->getSubExpr()->getType()->getPointeeType();
2238 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2240 AlignmentSource AlignSource;
2241 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2242 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2243 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2245 // We should not generate __weak write barrier on indirect reference
2246 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2247 // But, we continue to generate __strong write barrier on indirect write
2248 // into a pointer to object.
2249 if (getLangOpts().ObjC1 &&
2250 getLangOpts().getGC() != LangOptions::NonGC &&
2252 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2257 LValue LV = EmitLValue(E->getSubExpr());
2258 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2260 // __real is valid on scalars. This is a faster way of testing that.
2261 // __imag can only produce an rvalue on scalars.
2262 if (E->getOpcode() == UO_Real &&
2263 !LV.getAddress().getElementType()->isStructTy()) {
2264 assert(E->getSubExpr()->getType()->isArithmeticType());
2268 assert(E->getSubExpr()->getType()->isAnyComplexType());
2271 (E->getOpcode() == UO_Real
2272 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2273 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2274 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
2278 LValue LV = EmitLValue(E->getSubExpr());
2279 bool isInc = E->getOpcode() == UO_PreInc;
2281 if (E->getType()->isAnyComplexType())
2282 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2284 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2290 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2291 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2292 E->getType(), AlignmentSource::Decl);
2295 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2296 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2297 E->getType(), AlignmentSource::Decl);
2300 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2301 auto SL = E->getFunctionName();
2302 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2303 StringRef FnName = CurFn->getName();
2304 if (FnName.startswith("\01"))
2305 FnName = FnName.substr(1);
2306 StringRef NameItems[] = {
2307 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2308 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2309 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
2310 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2311 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2313 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2314 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2317 /// Emit a type description suitable for use by a runtime sanitizer library. The
2318 /// format of a type descriptor is
2321 /// { i16 TypeKind, i16 TypeInfo }
2324 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2325 /// integer, 1 for a floating point value, and -1 for anything else.
2326 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2327 // Only emit each type's descriptor once.
2328 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2331 uint16_t TypeKind = -1;
2332 uint16_t TypeInfo = 0;
2334 if (T->isIntegerType()) {
2336 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2337 (T->isSignedIntegerType() ? 1 : 0);
2338 } else if (T->isFloatingType()) {
2340 TypeInfo = getContext().getTypeSize(T);
2343 // Format the type name as if for a diagnostic, including quotes and
2344 // optionally an 'aka'.
2345 SmallString<32> Buffer;
2346 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2347 (intptr_t)T.getAsOpaquePtr(),
2348 StringRef(), StringRef(), None, Buffer,
2351 llvm::Constant *Components[] = {
2352 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2353 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2355 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2357 auto *GV = new llvm::GlobalVariable(
2358 CGM.getModule(), Descriptor->getType(),
2359 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2360 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2361 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2363 // Remember the descriptor for this type.
2364 CGM.setTypeDescriptorInMap(T, GV);
2369 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2370 llvm::Type *TargetTy = IntPtrTy;
2372 // Floating-point types which fit into intptr_t are bitcast to integers
2373 // and then passed directly (after zero-extension, if necessary).
2374 if (V->getType()->isFloatingPointTy()) {
2375 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2376 if (Bits <= TargetTy->getIntegerBitWidth())
2377 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2381 // Integers which fit in intptr_t are zero-extended and passed directly.
2382 if (V->getType()->isIntegerTy() &&
2383 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2384 return Builder.CreateZExt(V, TargetTy);
2386 // Pointers are passed directly, everything else is passed by address.
2387 if (!V->getType()->isPointerTy()) {
2388 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2389 Builder.CreateStore(V, Ptr);
2390 V = Ptr.getPointer();
2392 return Builder.CreatePtrToInt(V, TargetTy);
2395 /// \brief Emit a representation of a SourceLocation for passing to a handler
2396 /// in a sanitizer runtime library. The format for this data is:
2398 /// struct SourceLocation {
2399 /// const char *Filename;
2400 /// int32_t Line, Column;
2403 /// For an invalid SourceLocation, the Filename pointer is null.
2404 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2405 llvm::Constant *Filename;
2408 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2409 if (PLoc.isValid()) {
2410 StringRef FilenameString = PLoc.getFilename();
2412 int PathComponentsToStrip =
2413 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2414 if (PathComponentsToStrip < 0) {
2415 assert(PathComponentsToStrip != INT_MIN);
2416 int PathComponentsToKeep = -PathComponentsToStrip;
2417 auto I = llvm::sys::path::rbegin(FilenameString);
2418 auto E = llvm::sys::path::rend(FilenameString);
2419 while (I != E && --PathComponentsToKeep)
2422 FilenameString = FilenameString.substr(I - E);
2423 } else if (PathComponentsToStrip > 0) {
2424 auto I = llvm::sys::path::begin(FilenameString);
2425 auto E = llvm::sys::path::end(FilenameString);
2426 while (I != E && PathComponentsToStrip--)
2431 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2433 FilenameString = llvm::sys::path::filename(FilenameString);
2436 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2437 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2438 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2439 Filename = FilenameGV.getPointer();
2440 Line = PLoc.getLine();
2441 Column = PLoc.getColumn();
2443 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2447 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2448 Builder.getInt32(Column)};
2450 return llvm::ConstantStruct::getAnon(Data);
2454 /// \brief Specify under what conditions this check can be recovered
2455 enum class CheckRecoverableKind {
2456 /// Always terminate program execution if this check fails.
2458 /// Check supports recovering, runtime has both fatal (noreturn) and
2459 /// non-fatal handlers for this check.
2461 /// Runtime conditionally aborts, always need to support recovery.
2466 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2467 assert(llvm::countPopulation(Kind) == 1);
2469 case SanitizerKind::Vptr:
2470 return CheckRecoverableKind::AlwaysRecoverable;
2471 case SanitizerKind::Return:
2472 case SanitizerKind::Unreachable:
2473 return CheckRecoverableKind::Unrecoverable;
2475 return CheckRecoverableKind::Recoverable;
2479 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2480 llvm::FunctionType *FnType,
2481 ArrayRef<llvm::Value *> FnArgs,
2482 StringRef CheckName,
2483 CheckRecoverableKind RecoverKind, bool IsFatal,
2484 llvm::BasicBlock *ContBB) {
2485 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2486 bool NeedsAbortSuffix =
2487 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2488 std::string FnName = ("__ubsan_handle_" + CheckName +
2489 (NeedsAbortSuffix ? "_abort" : "")).str();
2491 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2493 llvm::AttrBuilder B;
2495 B.addAttribute(llvm::Attribute::NoReturn)
2496 .addAttribute(llvm::Attribute::NoUnwind);
2498 B.addAttribute(llvm::Attribute::UWTable);
2500 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2502 llvm::AttributeSet::get(CGF.getLLVMContext(),
2503 llvm::AttributeSet::FunctionIndex, B));
2504 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2506 HandlerCall->setDoesNotReturn();
2507 CGF.Builder.CreateUnreachable();
2509 CGF.Builder.CreateBr(ContBB);
2513 void CodeGenFunction::EmitCheck(
2514 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2515 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2516 ArrayRef<llvm::Value *> DynamicArgs) {
2517 assert(IsSanitizerScope);
2518 assert(Checked.size() > 0);
2520 llvm::Value *FatalCond = nullptr;
2521 llvm::Value *RecoverableCond = nullptr;
2522 llvm::Value *TrapCond = nullptr;
2523 for (int i = 0, n = Checked.size(); i < n; ++i) {
2524 llvm::Value *Check = Checked[i].first;
2525 // -fsanitize-trap= overrides -fsanitize-recover=.
2526 llvm::Value *&Cond =
2527 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2529 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2532 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2536 EmitTrapCheck(TrapCond);
2537 if (!FatalCond && !RecoverableCond)
2540 llvm::Value *JointCond;
2541 if (FatalCond && RecoverableCond)
2542 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2544 JointCond = FatalCond ? FatalCond : RecoverableCond;
2547 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2548 assert(SanOpts.has(Checked[0].second));
2550 for (int i = 1, n = Checked.size(); i < n; ++i) {
2551 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2552 "All recoverable kinds in a single check must be same!");
2553 assert(SanOpts.has(Checked[i].second));
2557 llvm::BasicBlock *Cont = createBasicBlock("cont");
2558 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2559 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2560 // Give hint that we very much don't expect to execute the handler
2561 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2562 llvm::MDBuilder MDHelper(getLLVMContext());
2563 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2564 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2565 EmitBlock(Handlers);
2567 // Handler functions take an i8* pointing to the (handler-specific) static
2568 // information block, followed by a sequence of intptr_t arguments
2569 // representing operand values.
2570 SmallVector<llvm::Value *, 4> Args;
2571 SmallVector<llvm::Type *, 4> ArgTypes;
2572 Args.reserve(DynamicArgs.size() + 1);
2573 ArgTypes.reserve(DynamicArgs.size() + 1);
2575 // Emit handler arguments and create handler function type.
2576 if (!StaticArgs.empty()) {
2577 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2579 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2580 llvm::GlobalVariable::PrivateLinkage, Info);
2581 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2582 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2583 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2584 ArgTypes.push_back(Int8PtrTy);
2587 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2588 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2589 ArgTypes.push_back(IntPtrTy);
2592 llvm::FunctionType *FnType =
2593 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2595 if (!FatalCond || !RecoverableCond) {
2596 // Simple case: we need to generate a single handler call, either
2597 // fatal, or non-fatal.
2598 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2599 (FatalCond != nullptr), Cont);
2601 // Emit two handler calls: first one for set of unrecoverable checks,
2602 // another one for recoverable.
2603 llvm::BasicBlock *NonFatalHandlerBB =
2604 createBasicBlock("non_fatal." + CheckName);
2605 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2606 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2607 EmitBlock(FatalHandlerBB);
2608 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2610 EmitBlock(NonFatalHandlerBB);
2611 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2618 void CodeGenFunction::EmitCfiSlowPathCheck(
2619 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2620 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2621 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2623 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2624 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2626 llvm::MDBuilder MDHelper(getLLVMContext());
2627 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2628 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2632 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2634 llvm::CallInst *CheckCall;
2636 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2638 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2639 llvm::GlobalVariable::PrivateLinkage, Info);
2640 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2641 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2643 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2644 "__cfi_slowpath_diag",
2645 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2647 CheckCall = Builder.CreateCall(
2649 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2651 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2653 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2654 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2657 CheckCall->setDoesNotThrow();
2662 // This function is basically a switch over the CFI failure kind, which is
2663 // extracted from CFICheckFailData (1st function argument). Each case is either
2664 // llvm.trap or a call to one of the two runtime handlers, based on
2665 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2666 // failure kind) traps, but this should really never happen. CFICheckFailData
2667 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2668 // check kind; in this case __cfi_check_fail traps as well.
2669 void CodeGenFunction::EmitCfiCheckFail() {
2670 SanitizerScope SanScope(this);
2671 FunctionArgList Args;
2672 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2673 getContext().VoidPtrTy);
2674 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2675 getContext().VoidPtrTy);
2676 Args.push_back(&ArgData);
2677 Args.push_back(&ArgAddr);
2679 const CGFunctionInfo &FI =
2680 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2682 llvm::Function *F = llvm::Function::Create(
2683 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2684 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2685 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2687 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2691 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2692 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2694 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2695 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2697 // Data == nullptr means the calling module has trap behaviour for this check.
2698 llvm::Value *DataIsNotNullPtr =
2699 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2700 EmitTrapCheck(DataIsNotNullPtr);
2702 llvm::StructType *SourceLocationTy =
2703 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2704 llvm::StructType *CfiCheckFailDataTy =
2705 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2707 llvm::Value *V = Builder.CreateConstGEP2_32(
2709 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2711 Address CheckKindAddr(V, getIntAlign());
2712 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2714 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2715 CGM.getLLVMContext(),
2716 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2717 llvm::Value *ValidVtable = Builder.CreateZExt(
2718 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2719 {Addr, AllVtables}),
2722 const std::pair<int, SanitizerMask> CheckKinds[] = {
2723 {CFITCK_VCall, SanitizerKind::CFIVCall},
2724 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2725 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2726 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2727 {CFITCK_ICall, SanitizerKind::CFIICall}};
2729 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2730 for (auto CheckKindMaskPair : CheckKinds) {
2731 int Kind = CheckKindMaskPair.first;
2732 SanitizerMask Mask = CheckKindMaskPair.second;
2734 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2735 if (CGM.getLangOpts().Sanitize.has(Mask))
2736 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {},
2737 {Data, Addr, ValidVtable});
2739 EmitTrapCheck(Cond);
2743 // The only reference to this function will be created during LTO link.
2744 // Make sure it survives until then.
2745 CGM.addUsedGlobal(F);
2748 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2749 llvm::BasicBlock *Cont = createBasicBlock("cont");
2751 // If we're optimizing, collapse all calls to trap down to just one per
2752 // function to save on code size.
2753 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2754 TrapBB = createBasicBlock("trap");
2755 Builder.CreateCondBr(Checked, Cont, TrapBB);
2757 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2758 TrapCall->setDoesNotReturn();
2759 TrapCall->setDoesNotThrow();
2760 Builder.CreateUnreachable();
2762 Builder.CreateCondBr(Checked, Cont, TrapBB);
2768 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2769 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2771 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2772 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2773 CGM.getCodeGenOpts().TrapFuncName);
2774 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2780 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2781 AlignmentSource *AlignSource) {
2782 assert(E->getType()->isArrayType() &&
2783 "Array to pointer decay must have array source type!");
2785 // Expressions of array type can't be bitfields or vector elements.
2786 LValue LV = EmitLValue(E);
2787 Address Addr = LV.getAddress();
2788 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2790 // If the array type was an incomplete type, we need to make sure
2791 // the decay ends up being the right type.
2792 llvm::Type *NewTy = ConvertType(E->getType());
2793 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2795 // Note that VLA pointers are always decayed, so we don't need to do
2797 if (!E->getType()->isVariableArrayType()) {
2798 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2799 "Expected pointer to array");
2800 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2803 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2804 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2807 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2808 /// array to pointer, return the array subexpression.
2809 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2810 // If this isn't just an array->pointer decay, bail out.
2811 const auto *CE = dyn_cast<CastExpr>(E);
2812 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2815 // If this is a decay from variable width array, bail out.
2816 const Expr *SubExpr = CE->getSubExpr();
2817 if (SubExpr->getType()->isVariableArrayType())
2823 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2825 ArrayRef<llvm::Value*> indices,
2827 const llvm::Twine &name = "arrayidx") {
2829 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2831 return CGF.Builder.CreateGEP(ptr, indices, name);
2835 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2837 CharUnits eltSize) {
2838 // If we have a constant index, we can use the exact offset of the
2839 // element we're accessing.
2840 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2841 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2842 return arrayAlign.alignmentAtOffset(offset);
2844 // Otherwise, use the worst-case alignment for any element.
2846 return arrayAlign.alignmentOfArrayElement(eltSize);
2850 static QualType getFixedSizeElementType(const ASTContext &ctx,
2851 const VariableArrayType *vla) {
2854 eltType = vla->getElementType();
2855 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2859 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2860 ArrayRef<llvm::Value*> indices,
2861 QualType eltType, bool inbounds,
2862 const llvm::Twine &name = "arrayidx") {
2863 // All the indices except that last must be zero.
2865 for (auto idx : indices.drop_back())
2866 assert(isa<llvm::ConstantInt>(idx) &&
2867 cast<llvm::ConstantInt>(idx)->isZero());
2870 // Determine the element size of the statically-sized base. This is
2871 // the thing that the indices are expressed in terms of.
2872 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2873 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2876 // We can use that to compute the best alignment of the element.
2877 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2878 CharUnits eltAlign =
2879 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2881 llvm::Value *eltPtr =
2882 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2883 return Address(eltPtr, eltAlign);
2886 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2888 // The index must always be an integer, which is not an aggregate. Emit it
2889 // in lexical order (this complexity is, sadly, required by C++17).
2890 llvm::Value *IdxPre =
2891 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
2892 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
2894 if (E->getLHS() != E->getIdx()) {
2895 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2896 Idx = EmitScalarExpr(E->getIdx());
2899 QualType IdxTy = E->getIdx()->getType();
2900 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2902 if (SanOpts.has(SanitizerKind::ArrayBounds))
2903 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2905 // Extend or truncate the index type to 32 or 64-bits.
2906 if (Promote && Idx->getType() != IntPtrTy)
2907 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2913 // If the base is a vector type, then we are forming a vector element lvalue
2914 // with this subscript.
2915 if (E->getBase()->getType()->isVectorType() &&
2916 !isa<ExtVectorElementExpr>(E->getBase())) {
2917 // Emit the vector as an lvalue to get its address.
2918 LValue LHS = EmitLValue(E->getBase());
2919 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
2920 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2921 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2922 E->getBase()->getType(),
2923 LHS.getAlignmentSource());
2926 // All the other cases basically behave like simple offsetting.
2928 // Handle the extvector case we ignored above.
2929 if (isa<ExtVectorElementExpr>(E->getBase())) {
2930 LValue LV = EmitLValue(E->getBase());
2931 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2932 Address Addr = EmitExtVectorElementLValue(LV);
2934 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2935 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2936 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
2939 AlignmentSource AlignSource;
2940 Address Addr = Address::invalid();
2941 if (const VariableArrayType *vla =
2942 getContext().getAsVariableArrayType(E->getType())) {
2943 // The base must be a pointer, which is not an aggregate. Emit
2944 // it. It needs to be emitted first in case it's what captures
2946 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2947 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2949 // The element count here is the total number of non-VLA elements.
2950 llvm::Value *numElements = getVLASize(vla).first;
2952 // Effectively, the multiply by the VLA size is part of the GEP.
2953 // GEP indexes are signed, and scaling an index isn't permitted to
2954 // signed-overflow, so we use the same semantics for our explicit
2955 // multiply. We suppress this if overflow is not undefined behavior.
2956 if (getLangOpts().isSignedOverflowDefined()) {
2957 Idx = Builder.CreateMul(Idx, numElements);
2959 Idx = Builder.CreateNSWMul(Idx, numElements);
2962 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2963 !getLangOpts().isSignedOverflowDefined());
2965 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2966 // Indexing over an interface, as in "NSString *P; P[4];"
2968 // Emit the base pointer.
2969 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2970 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
2972 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2973 llvm::Value *InterfaceSizeVal =
2974 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
2976 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
2978 // We don't necessarily build correct LLVM struct types for ObjC
2979 // interfaces, so we can't rely on GEP to do this scaling
2980 // correctly, so we need to cast to i8*. FIXME: is this actually
2981 // true? A lot of other things in the fragile ABI would break...
2982 llvm::Type *OrigBaseTy = Addr.getType();
2983 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2986 CharUnits EltAlign =
2987 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2988 llvm::Value *EltPtr =
2989 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2990 Addr = Address(EltPtr, EltAlign);
2993 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
2994 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2995 // If this is A[i] where A is an array, the frontend will have decayed the
2996 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2997 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2998 // "gep x, i" here. Emit one "gep A, 0, i".
2999 assert(Array->getType()->isArrayType() &&
3000 "Array to pointer decay must have array source type!");
3002 // For simple multidimensional array indexing, set the 'accessed' flag for
3003 // better bounds-checking of the base expression.
3004 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3005 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3007 ArrayLV = EmitLValue(Array);
3008 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3010 // Propagate the alignment from the array itself to the result.
3011 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3012 {CGM.getSize(CharUnits::Zero()), Idx},
3014 !getLangOpts().isSignedOverflowDefined());
3015 AlignSource = ArrayLV.getAlignmentSource();
3017 // The base must be a pointer; emit it with an estimate of its alignment.
3018 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3019 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3020 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3021 !getLangOpts().isSignedOverflowDefined());
3024 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3026 // TODO: Preserve/extend path TBAA metadata?
3028 if (getLangOpts().ObjC1 &&
3029 getLangOpts().getGC() != LangOptions::NonGC) {
3030 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3031 setObjCGCLValueClass(getContext(), E, LV);
3036 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3037 AlignmentSource &AlignSource,
3038 QualType BaseTy, QualType ElTy,
3039 bool IsLowerBound) {
3041 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3042 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3043 if (BaseTy->isArrayType()) {
3044 Address Addr = BaseLVal.getAddress();
3045 AlignSource = BaseLVal.getAlignmentSource();
3047 // If the array type was an incomplete type, we need to make sure
3048 // the decay ends up being the right type.
3049 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3050 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3052 // Note that VLA pointers are always decayed, so we don't need to do
3054 if (!BaseTy->isVariableArrayType()) {
3055 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3056 "Expected pointer to array");
3057 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3061 return CGF.Builder.CreateElementBitCast(Addr,
3062 CGF.ConvertTypeForMem(ElTy));
3064 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3065 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3067 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3070 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3071 bool IsLowerBound) {
3074 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3075 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3077 BaseTy = E->getBase()->getType();
3078 QualType ResultExprTy;
3079 if (auto *AT = getContext().getAsArrayType(BaseTy))
3080 ResultExprTy = AT->getElementType();
3082 ResultExprTy = BaseTy->getPointeeType();
3083 llvm::Value *Idx = nullptr;
3084 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3085 // Requesting lower bound or upper bound, but without provided length and
3086 // without ':' symbol for the default length -> length = 1.
3087 // Idx = LowerBound ?: 0;
3088 if (auto *LowerBound = E->getLowerBound()) {
3089 Idx = Builder.CreateIntCast(
3090 EmitScalarExpr(LowerBound), IntPtrTy,
3091 LowerBound->getType()->hasSignedIntegerRepresentation());
3093 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3095 // Try to emit length or lower bound as constant. If this is possible, 1
3096 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3097 // IR (LB + Len) - 1.
3098 auto &C = CGM.getContext();
3099 auto *Length = E->getLength();
3100 llvm::APSInt ConstLength;
3102 // Idx = LowerBound + Length - 1;
3103 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3104 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3107 auto *LowerBound = E->getLowerBound();
3108 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3109 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3110 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3111 LowerBound = nullptr;
3115 else if (!LowerBound)
3118 if (Length || LowerBound) {
3119 auto *LowerBoundVal =
3121 ? Builder.CreateIntCast(
3122 EmitScalarExpr(LowerBound), IntPtrTy,
3123 LowerBound->getType()->hasSignedIntegerRepresentation())
3124 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3127 ? Builder.CreateIntCast(
3128 EmitScalarExpr(Length), IntPtrTy,
3129 Length->getType()->hasSignedIntegerRepresentation())
3130 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3131 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3133 !getLangOpts().isSignedOverflowDefined());
3134 if (Length && LowerBound) {
3135 Idx = Builder.CreateSub(
3136 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3137 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3140 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3142 // Idx = ArraySize - 1;
3143 QualType ArrayTy = BaseTy->isPointerType()
3144 ? E->getBase()->IgnoreParenImpCasts()->getType()
3146 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3147 Length = VAT->getSizeExpr();
3148 if (Length->isIntegerConstantExpr(ConstLength, C))
3151 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3152 ConstLength = CAT->getSize();
3155 auto *LengthVal = Builder.CreateIntCast(
3156 EmitScalarExpr(Length), IntPtrTy,
3157 Length->getType()->hasSignedIntegerRepresentation());
3158 Idx = Builder.CreateSub(
3159 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3160 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3162 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3164 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3170 Address EltPtr = Address::invalid();
3171 AlignmentSource AlignSource;
3172 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3173 // The base must be a pointer, which is not an aggregate. Emit
3174 // it. It needs to be emitted first in case it's what captures
3177 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3178 VLA->getElementType(), IsLowerBound);
3179 // The element count here is the total number of non-VLA elements.
3180 llvm::Value *NumElements = getVLASize(VLA).first;
3182 // Effectively, the multiply by the VLA size is part of the GEP.
3183 // GEP indexes are signed, and scaling an index isn't permitted to
3184 // signed-overflow, so we use the same semantics for our explicit
3185 // multiply. We suppress this if overflow is not undefined behavior.
3186 if (getLangOpts().isSignedOverflowDefined())
3187 Idx = Builder.CreateMul(Idx, NumElements);
3189 Idx = Builder.CreateNSWMul(Idx, NumElements);
3190 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3191 !getLangOpts().isSignedOverflowDefined());
3192 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3193 // If this is A[i] where A is an array, the frontend will have decayed the
3194 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3195 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3196 // "gep x, i" here. Emit one "gep A, 0, i".
3197 assert(Array->getType()->isArrayType() &&
3198 "Array to pointer decay must have array source type!");
3200 // For simple multidimensional array indexing, set the 'accessed' flag for
3201 // better bounds-checking of the base expression.
3202 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3203 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3205 ArrayLV = EmitLValue(Array);
3207 // Propagate the alignment from the array itself to the result.
3208 EltPtr = emitArraySubscriptGEP(
3209 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3210 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3211 AlignSource = ArrayLV.getAlignmentSource();
3213 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3214 BaseTy, ResultExprTy, IsLowerBound);
3215 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3216 !getLangOpts().isSignedOverflowDefined());
3219 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3222 LValue CodeGenFunction::
3223 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3224 // Emit the base vector as an l-value.
3227 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3229 // If it is a pointer to a vector, emit the address and form an lvalue with
3231 AlignmentSource AlignSource;
3232 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3233 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3234 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3235 Base.getQuals().removeObjCGCAttr();
3236 } else if (E->getBase()->isGLValue()) {
3237 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3238 // emit the base as an lvalue.
3239 assert(E->getBase()->getType()->isVectorType());
3240 Base = EmitLValue(E->getBase());
3242 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3243 assert(E->getBase()->getType()->isVectorType() &&
3244 "Result must be a vector");
3245 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3247 // Store the vector to memory (because LValue wants an address).
3248 Address VecMem = CreateMemTemp(E->getBase()->getType());
3249 Builder.CreateStore(Vec, VecMem);
3250 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3251 AlignmentSource::Decl);
3255 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3257 // Encode the element access list into a vector of unsigned indices.
3258 SmallVector<uint32_t, 4> Indices;
3259 E->getEncodedElementAccess(Indices);
3261 if (Base.isSimple()) {
3262 llvm::Constant *CV =
3263 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3264 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3265 Base.getAlignmentSource());
3267 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3269 llvm::Constant *BaseElts = Base.getExtVectorElts();
3270 SmallVector<llvm::Constant *, 4> CElts;
3272 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3273 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3274 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3275 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3276 Base.getAlignmentSource());
3279 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3280 Expr *BaseExpr = E->getBase();
3282 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3285 AlignmentSource AlignSource;
3286 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3287 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3288 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3289 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3291 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3293 NamedDecl *ND = E->getMemberDecl();
3294 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3295 LValue LV = EmitLValueForField(BaseLV, Field);
3296 setObjCGCLValueClass(getContext(), E, LV);
3300 if (auto *VD = dyn_cast<VarDecl>(ND))
3301 return EmitGlobalVarDeclLValue(*this, E, VD);
3303 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3304 return EmitFunctionDeclLValue(*this, E, FD);
3306 llvm_unreachable("Unhandled member declaration!");
3309 /// Given that we are currently emitting a lambda, emit an l-value for
3310 /// one of its members.
3311 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3312 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3313 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3314 QualType LambdaTagType =
3315 getContext().getTagDeclType(Field->getParent());
3316 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3317 return EmitLValueForField(LambdaLV, Field);
3320 /// Drill down to the storage of a field without walking into
3321 /// reference types.
3323 /// The resulting address doesn't necessarily have the right type.
3324 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3325 const FieldDecl *field) {
3326 const RecordDecl *rec = field->getParent();
3329 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3332 // Adjust the alignment down to the given offset.
3333 // As a special case, if the LLVM field index is 0, we know that this
3335 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3336 .getFieldOffset(field->getFieldIndex()) == 0) &&
3337 "LLVM field at index zero had non-zero offset?");
3339 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3340 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3341 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3344 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3347 LValue CodeGenFunction::EmitLValueForField(LValue base,
3348 const FieldDecl *field) {
3349 AlignmentSource fieldAlignSource =
3350 getFieldAlignmentSource(base.getAlignmentSource());
3352 if (field->isBitField()) {
3353 const CGRecordLayout &RL =
3354 CGM.getTypes().getCGRecordLayout(field->getParent());
3355 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3356 Address Addr = base.getAddress();
3357 unsigned Idx = RL.getLLVMFieldNo(field);
3359 // For structs, we GEP to the field that the record layout suggests.
3360 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3362 // Get the access type.
3363 llvm::Type *FieldIntTy =
3364 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3365 if (Addr.getElementType() != FieldIntTy)
3366 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3368 QualType fieldType =
3369 field->getType().withCVRQualifiers(base.getVRQualifiers());
3370 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3373 const RecordDecl *rec = field->getParent();
3374 QualType type = field->getType();
3376 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3378 Address addr = base.getAddress();
3379 unsigned cvr = base.getVRQualifiers();
3380 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3381 if (rec->isUnion()) {
3382 // For unions, there is no pointer adjustment.
3383 assert(!type->isReferenceType() && "union has reference member");
3384 // TODO: handle path-aware TBAA for union.
3387 // For structs, we GEP to the field that the record layout suggests.
3388 addr = emitAddrOfFieldStorage(*this, addr, field);
3390 // If this is a reference field, load the reference right now.
3391 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3392 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3393 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3395 // Loading the reference will disable path-aware TBAA.
3397 if (CGM.shouldUseTBAA()) {
3400 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3402 tbaa = CGM.getTBAAInfo(type);
3404 CGM.DecorateInstructionWithTBAA(load, tbaa);
3408 type = refType->getPointeeType();
3410 CharUnits alignment =
3411 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3412 addr = Address(load, alignment);
3414 // Qualifiers on the struct don't apply to the referencee, and
3415 // we'll pick up CVR from the actual type later, so reset these
3416 // additional qualifiers now.
3421 // Make sure that the address is pointing to the right type. This is critical
3422 // for both unions and structs. A union needs a bitcast, a struct element
3423 // will need a bitcast if the LLVM type laid out doesn't match the desired
3425 addr = Builder.CreateElementBitCast(addr,
3426 CGM.getTypes().ConvertTypeForMem(type),
3429 if (field->hasAttr<AnnotateAttr>())
3430 addr = EmitFieldAnnotations(field, addr);
3432 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3433 LV.getQuals().addCVRQualifiers(cvr);
3435 const ASTRecordLayout &Layout =
3436 getContext().getASTRecordLayout(field->getParent());
3437 // Set the base type to be the base type of the base LValue and
3438 // update offset to be relative to the base type.
3439 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3440 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3441 Layout.getFieldOffset(field->getFieldIndex()) /
3442 getContext().getCharWidth());
3445 // __weak attribute on a field is ignored.
3446 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3447 LV.getQuals().removeObjCGCAttr();
3449 // Fields of may_alias structs act like 'char' for TBAA purposes.
3450 // FIXME: this should get propagated down through anonymous structs
3452 if (mayAlias && LV.getTBAAInfo())
3453 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3459 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3460 const FieldDecl *Field) {
3461 QualType FieldType = Field->getType();
3463 if (!FieldType->isReferenceType())
3464 return EmitLValueForField(Base, Field);
3466 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3468 // Make sure that the address is pointing to the right type.
3469 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3470 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3472 // TODO: access-path TBAA?
3473 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3474 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3477 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3478 if (E->isFileScope()) {
3479 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3480 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3482 if (E->getType()->isVariablyModifiedType())
3483 // make sure to emit the VLA size.
3484 EmitVariablyModifiedType(E->getType());
3486 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3487 const Expr *InitExpr = E->getInitializer();
3488 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3490 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3496 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3497 if (!E->isGLValue())
3498 // Initializing an aggregate temporary in C++11: T{...}.
3499 return EmitAggExprToLValue(E);
3501 // An lvalue initializer list must be initializing a reference.
3502 assert(E->getNumInits() == 1 && "reference init with multiple values");
3503 return EmitLValue(E->getInit(0));
3506 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3507 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3508 /// LValue is returned and the current block has been terminated.
3509 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3510 const Expr *Operand) {
3511 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3512 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3516 return CGF.EmitLValue(Operand);
3519 LValue CodeGenFunction::
3520 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3521 if (!expr->isGLValue()) {
3522 // ?: here should be an aggregate.
3523 assert(hasAggregateEvaluationKind(expr->getType()) &&
3524 "Unexpected conditional operator!");
3525 return EmitAggExprToLValue(expr);
3528 OpaqueValueMapping binding(*this, expr);
3530 const Expr *condExpr = expr->getCond();
3532 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3533 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3534 if (!CondExprBool) std::swap(live, dead);
3536 if (!ContainsLabel(dead)) {
3537 // If the true case is live, we need to track its region.
3539 incrementProfileCounter(expr);
3540 return EmitLValue(live);
3544 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3545 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3546 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3548 ConditionalEvaluation eval(*this);
3549 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3551 // Any temporaries created here are conditional.
3552 EmitBlock(lhsBlock);
3553 incrementProfileCounter(expr);
3555 Optional<LValue> lhs =
3556 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3559 if (lhs && !lhs->isSimple())
3560 return EmitUnsupportedLValue(expr, "conditional operator");
3562 lhsBlock = Builder.GetInsertBlock();
3564 Builder.CreateBr(contBlock);
3566 // Any temporaries created here are conditional.
3567 EmitBlock(rhsBlock);
3569 Optional<LValue> rhs =
3570 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3572 if (rhs && !rhs->isSimple())
3573 return EmitUnsupportedLValue(expr, "conditional operator");
3574 rhsBlock = Builder.GetInsertBlock();
3576 EmitBlock(contBlock);
3579 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3581 phi->addIncoming(lhs->getPointer(), lhsBlock);
3582 phi->addIncoming(rhs->getPointer(), rhsBlock);
3583 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3584 AlignmentSource alignSource =
3585 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3586 return MakeAddrLValue(result, expr->getType(), alignSource);
3588 assert((lhs || rhs) &&
3589 "both operands of glvalue conditional are throw-expressions?");
3590 return lhs ? *lhs : *rhs;
3594 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3595 /// type. If the cast is to a reference, we can have the usual lvalue result,
3596 /// otherwise if a cast is needed by the code generator in an lvalue context,
3597 /// then it must mean that we need the address of an aggregate in order to
3598 /// access one of its members. This can happen for all the reasons that casts
3599 /// are permitted with aggregate result, including noop aggregate casts, and
3600 /// cast from scalar to union.
3601 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3602 switch (E->getCastKind()) {
3605 case CK_ArrayToPointerDecay:
3606 case CK_FunctionToPointerDecay:
3607 case CK_NullToMemberPointer:
3608 case CK_NullToPointer:
3609 case CK_IntegralToPointer:
3610 case CK_PointerToIntegral:
3611 case CK_PointerToBoolean:
3612 case CK_VectorSplat:
3613 case CK_IntegralCast:
3614 case CK_BooleanToSignedIntegral:
3615 case CK_IntegralToBoolean:
3616 case CK_IntegralToFloating:
3617 case CK_FloatingToIntegral:
3618 case CK_FloatingToBoolean:
3619 case CK_FloatingCast:
3620 case CK_FloatingRealToComplex:
3621 case CK_FloatingComplexToReal:
3622 case CK_FloatingComplexToBoolean:
3623 case CK_FloatingComplexCast:
3624 case CK_FloatingComplexToIntegralComplex:
3625 case CK_IntegralRealToComplex:
3626 case CK_IntegralComplexToReal:
3627 case CK_IntegralComplexToBoolean:
3628 case CK_IntegralComplexCast:
3629 case CK_IntegralComplexToFloatingComplex:
3630 case CK_DerivedToBaseMemberPointer:
3631 case CK_BaseToDerivedMemberPointer:
3632 case CK_MemberPointerToBoolean:
3633 case CK_ReinterpretMemberPointer:
3634 case CK_AnyPointerToBlockPointerCast:
3635 case CK_ARCProduceObject:
3636 case CK_ARCConsumeObject:
3637 case CK_ARCReclaimReturnedObject:
3638 case CK_ARCExtendBlockObject:
3639 case CK_CopyAndAutoreleaseBlockObject:
3640 case CK_AddressSpaceConversion:
3641 case CK_IntToOCLSampler:
3642 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3645 llvm_unreachable("dependent cast kind in IR gen!");
3647 case CK_BuiltinFnToFnPtr:
3648 llvm_unreachable("builtin functions are handled elsewhere");
3650 // These are never l-values; just use the aggregate emission code.
3651 case CK_NonAtomicToAtomic:
3652 case CK_AtomicToNonAtomic:
3653 return EmitAggExprToLValue(E);
3656 LValue LV = EmitLValue(E->getSubExpr());
3657 Address V = LV.getAddress();
3658 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3659 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3662 case CK_ConstructorConversion:
3663 case CK_UserDefinedConversion:
3664 case CK_CPointerToObjCPointerCast:
3665 case CK_BlockPointerToObjCPointerCast:
3667 case CK_LValueToRValue:
3668 return EmitLValue(E->getSubExpr());
3670 case CK_UncheckedDerivedToBase:
3671 case CK_DerivedToBase: {
3672 const RecordType *DerivedClassTy =
3673 E->getSubExpr()->getType()->getAs<RecordType>();
3674 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3676 LValue LV = EmitLValue(E->getSubExpr());
3677 Address This = LV.getAddress();
3679 // Perform the derived-to-base conversion
3680 Address Base = GetAddressOfBaseClass(
3681 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3682 /*NullCheckValue=*/false, E->getExprLoc());
3684 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3687 return EmitAggExprToLValue(E);
3688 case CK_BaseToDerived: {
3689 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3690 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3692 LValue LV = EmitLValue(E->getSubExpr());
3694 // Perform the base-to-derived conversion
3696 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3697 E->path_begin(), E->path_end(),
3698 /*NullCheckValue=*/false);
3700 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3701 // performed and the object is not of the derived type.
3702 if (sanitizePerformTypeCheck())
3703 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3704 Derived.getPointer(), E->getType());
3706 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3707 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3708 /*MayBeNull=*/false,
3709 CFITCK_DerivedCast, E->getLocStart());
3711 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3713 case CK_LValueBitCast: {
3714 // This must be a reinterpret_cast (or c-style equivalent).
3715 const auto *CE = cast<ExplicitCastExpr>(E);
3717 CGM.EmitExplicitCastExprType(CE, this);
3718 LValue LV = EmitLValue(E->getSubExpr());
3719 Address V = Builder.CreateBitCast(LV.getAddress(),
3720 ConvertType(CE->getTypeAsWritten()));
3722 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3723 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3724 /*MayBeNull=*/false,
3725 CFITCK_UnrelatedCast, E->getLocStart());
3727 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3729 case CK_ObjCObjectLValueCast: {
3730 LValue LV = EmitLValue(E->getSubExpr());
3731 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3732 ConvertType(E->getType()));
3733 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3735 case CK_ZeroToOCLEvent:
3736 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3739 llvm_unreachable("Unhandled lvalue cast kind?");
3742 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3743 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3744 return getOpaqueLValueMapping(e);
3747 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3748 const FieldDecl *FD,
3749 SourceLocation Loc) {
3750 QualType FT = FD->getType();
3751 LValue FieldLV = EmitLValueForField(LV, FD);
3752 switch (getEvaluationKind(FT)) {
3754 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3756 return FieldLV.asAggregateRValue();
3758 // This routine is used to load fields one-by-one to perform a copy, so
3759 // don't load reference fields.
3760 if (FD->getType()->isReferenceType())
3761 return RValue::get(FieldLV.getPointer());
3762 return EmitLoadOfLValue(FieldLV, Loc);
3764 llvm_unreachable("bad evaluation kind");
3767 //===--------------------------------------------------------------------===//
3768 // Expression Emission
3769 //===--------------------------------------------------------------------===//
3771 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3772 ReturnValueSlot ReturnValue) {
3773 // Builtins never have block type.
3774 if (E->getCallee()->getType()->isBlockPointerType())
3775 return EmitBlockCallExpr(E, ReturnValue);
3777 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3778 return EmitCXXMemberCallExpr(CE, ReturnValue);
3780 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3781 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3783 const Decl *TargetDecl = E->getCalleeDecl();
3784 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3785 if (unsigned builtinID = FD->getBuiltinID())
3786 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
3789 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3790 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
3791 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3793 if (const auto *PseudoDtor =
3794 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
3795 QualType DestroyedType = PseudoDtor->getDestroyedType();
3796 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
3797 // Automatic Reference Counting:
3798 // If the pseudo-expression names a retainable object with weak or
3799 // strong lifetime, the object shall be released.
3800 Expr *BaseExpr = PseudoDtor->getBase();
3801 Address BaseValue = Address::invalid();
3802 Qualifiers BaseQuals;
3804 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3805 if (PseudoDtor->isArrow()) {
3806 BaseValue = EmitPointerWithAlignment(BaseExpr);
3807 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3808 BaseQuals = PTy->getPointeeType().getQualifiers();
3810 LValue BaseLV = EmitLValue(BaseExpr);
3811 BaseValue = BaseLV.getAddress();
3812 QualType BaseTy = BaseExpr->getType();
3813 BaseQuals = BaseTy.getQualifiers();
3816 switch (DestroyedType.getObjCLifetime()) {
3817 case Qualifiers::OCL_None:
3818 case Qualifiers::OCL_ExplicitNone:
3819 case Qualifiers::OCL_Autoreleasing:
3822 case Qualifiers::OCL_Strong:
3823 EmitARCRelease(Builder.CreateLoad(BaseValue,
3824 PseudoDtor->getDestroyedType().isVolatileQualified()),
3825 ARCPreciseLifetime);
3828 case Qualifiers::OCL_Weak:
3829 EmitARCDestroyWeak(BaseValue);
3833 // C++ [expr.pseudo]p1:
3834 // The result shall only be used as the operand for the function call
3835 // operator (), and the result of such a call has type void. The only
3836 // effect is the evaluation of the postfix-expression before the dot or
3838 EmitScalarExpr(E->getCallee());
3841 return RValue::get(nullptr);
3844 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3845 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3849 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3850 // Comma expressions just emit their LHS then their RHS as an l-value.
3851 if (E->getOpcode() == BO_Comma) {
3852 EmitIgnoredExpr(E->getLHS());
3853 EnsureInsertPoint();
3854 return EmitLValue(E->getRHS());
3857 if (E->getOpcode() == BO_PtrMemD ||
3858 E->getOpcode() == BO_PtrMemI)
3859 return EmitPointerToDataMemberBinaryExpr(E);
3861 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
3863 // Note that in all of these cases, __block variables need the RHS
3864 // evaluated first just in case the variable gets moved by the RHS.
3866 switch (getEvaluationKind(E->getType())) {
3868 switch (E->getLHS()->getType().getObjCLifetime()) {
3869 case Qualifiers::OCL_Strong:
3870 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3872 case Qualifiers::OCL_Autoreleasing:
3873 return EmitARCStoreAutoreleasing(E).first;
3875 // No reason to do any of these differently.
3876 case Qualifiers::OCL_None:
3877 case Qualifiers::OCL_ExplicitNone:
3878 case Qualifiers::OCL_Weak:
3882 RValue RV = EmitAnyExpr(E->getRHS());
3883 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
3884 EmitStoreThroughLValue(RV, LV);
3889 return EmitComplexAssignmentLValue(E);
3892 return EmitAggExprToLValue(E);
3894 llvm_unreachable("bad evaluation kind");
3897 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
3898 RValue RV = EmitCallExpr(E);
3901 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3902 AlignmentSource::Decl);
3904 assert(E->getCallReturnType(getContext())->isReferenceType() &&
3905 "Can't have a scalar return unless the return type is a "
3908 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
3911 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3912 // FIXME: This shouldn't require another copy.
3913 return EmitAggExprToLValue(E);
3916 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
3917 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3918 && "binding l-value to type which needs a temporary");
3919 AggValueSlot Slot = CreateAggTemp(E->getType());
3920 EmitCXXConstructExpr(E, Slot);
3921 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3922 AlignmentSource::Decl);
3926 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
3927 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
3930 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3931 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3932 ConvertType(E->getType()));
3935 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
3936 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3937 AlignmentSource::Decl);
3941 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
3942 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3943 Slot.setExternallyDestructed();
3944 EmitAggExpr(E->getSubExpr(), Slot);
3945 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3946 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3947 AlignmentSource::Decl);
3951 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
3952 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3953 EmitLambdaExpr(E, Slot);
3954 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3955 AlignmentSource::Decl);
3958 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
3959 RValue RV = EmitObjCMessageExpr(E);
3962 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3963 AlignmentSource::Decl);
3965 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
3966 "Can't have a scalar return unless the return type is a "
3969 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
3972 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
3974 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3975 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
3978 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3979 const ObjCIvarDecl *Ivar) {
3980 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
3983 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3984 llvm::Value *BaseValue,
3985 const ObjCIvarDecl *Ivar,
3986 unsigned CVRQualifiers) {
3987 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
3988 Ivar, CVRQualifiers);
3991 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
3992 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3993 llvm::Value *BaseValue = nullptr;
3994 const Expr *BaseExpr = E->getBase();
3995 Qualifiers BaseQuals;
3998 BaseValue = EmitScalarExpr(BaseExpr);
3999 ObjectTy = BaseExpr->getType()->getPointeeType();
4000 BaseQuals = ObjectTy.getQualifiers();
4002 LValue BaseLV = EmitLValue(BaseExpr);
4003 BaseValue = BaseLV.getPointer();
4004 ObjectTy = BaseExpr->getType();
4005 BaseQuals = ObjectTy.getQualifiers();
4009 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4010 BaseQuals.getCVRQualifiers());
4011 setObjCGCLValueClass(getContext(), E, LV);
4015 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4016 // Can only get l-value for message expression returning aggregate type
4017 RValue RV = EmitAnyExprToTemp(E);
4018 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4019 AlignmentSource::Decl);
4022 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
4023 const CallExpr *E, ReturnValueSlot ReturnValue,
4024 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
4025 // Get the actual function type. The callee type will always be a pointer to
4026 // function type or a block pointer type.
4027 assert(CalleeType->isFunctionPointerType() &&
4028 "Call must have function pointer type!");
4030 // Preserve the non-canonical function type because things like exception
4031 // specifications disappear in the canonical type. That information is useful
4032 // to drive the generation of more accurate code for this call later on.
4033 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
4035 ->getAs<FunctionProtoType>();
4037 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
4039 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4040 // We can only guarantee that a function is called from the correct
4041 // context/function based on the appropriate target attributes,
4042 // so only check in the case where we have both always_inline and target
4043 // since otherwise we could be making a conditional call after a check for
4044 // the proper cpu features (and it won't cause code generation issues due to
4045 // function based code generation).
4046 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4047 TargetDecl->hasAttr<TargetAttr>())
4048 checkTargetFeatures(E, FD);
4050 CalleeType = getContext().getCanonicalType(CalleeType);
4052 const auto *FnType =
4053 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4055 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4056 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4057 if (llvm::Constant *PrefixSig =
4058 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4059 SanitizerScope SanScope(this);
4060 llvm::Constant *FTRTTIConst =
4061 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4062 llvm::Type *PrefixStructTyElems[] = {
4063 PrefixSig->getType(),
4064 FTRTTIConst->getType()
4066 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4067 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4069 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4070 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
4071 llvm::Value *CalleeSigPtr =
4072 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4073 llvm::Value *CalleeSig =
4074 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4075 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4077 llvm::BasicBlock *Cont = createBasicBlock("cont");
4078 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4079 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4081 EmitBlock(TypeCheck);
4082 llvm::Value *CalleeRTTIPtr =
4083 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4084 llvm::Value *CalleeRTTI =
4085 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4086 llvm::Value *CalleeRTTIMatch =
4087 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4088 llvm::Constant *StaticData[] = {
4089 EmitCheckSourceLocation(E->getLocStart()),
4090 EmitCheckTypeDescriptor(CalleeType)
4092 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4093 "function_type_mismatch", StaticData, Callee);
4095 Builder.CreateBr(Cont);
4100 // If we are checking indirect calls and this call is indirect, check that the
4101 // function pointer is a member of the bit set for the function type.
4102 if (SanOpts.has(SanitizerKind::CFIICall) &&
4103 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4104 SanitizerScope SanScope(this);
4105 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4107 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4108 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4110 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
4111 llvm::Value *TypeTest = Builder.CreateCall(
4112 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4114 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4115 llvm::Constant *StaticData[] = {
4116 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4117 EmitCheckSourceLocation(E->getLocStart()),
4118 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4120 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4121 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4122 CastedCallee, StaticData);
4124 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4125 "cfi_check_fail", StaticData,
4126 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4132 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4133 CGM.getContext().VoidPtrTy);
4135 // C++17 requires that we evaluate arguments to a call using assignment syntax
4136 // right-to-left, and that we evaluate arguments to certain other operators
4137 // left-to-right. Note that we allow this to override the order dictated by
4138 // the calling convention on the MS ABI, which means that parameter
4139 // destruction order is not necessarily reverse construction order.
4140 // FIXME: Revisit this based on C++ committee response to unimplementability.
4141 EvaluationOrder Order = EvaluationOrder::Default;
4142 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4143 if (OCE->isAssignmentOp())
4144 Order = EvaluationOrder::ForceRightToLeft;
4146 switch (OCE->getOperator()) {
4148 case OO_GreaterGreater:
4153 Order = EvaluationOrder::ForceLeftToRight;
4161 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4162 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4164 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4165 Args, FnType, /*isChainCall=*/Chain);
4168 // If the expression that denotes the called function has a type
4169 // that does not include a prototype, [the default argument
4170 // promotions are performed]. If the number of arguments does not
4171 // equal the number of parameters, the behavior is undefined. If
4172 // the function is defined with a type that includes a prototype,
4173 // and either the prototype ends with an ellipsis (, ...) or the
4174 // types of the arguments after promotion are not compatible with
4175 // the types of the parameters, the behavior is undefined. If the
4176 // function is defined with a type that does not include a
4177 // prototype, and the types of the arguments after promotion are
4178 // not compatible with those of the parameters after promotion,
4179 // the behavior is undefined [except in some trivial cases].
4180 // That is, in the general case, we should assume that a call
4181 // through an unprototyped function type works like a *non-variadic*
4182 // call. The way we make this work is to cast to the exact type
4183 // of the promoted arguments.
4185 // Chain calls use this same code path to add the invisible chain parameter
4186 // to the function type.
4187 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4188 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4189 CalleeTy = CalleeTy->getPointerTo();
4190 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
4193 return EmitCall(FnInfo, Callee, ReturnValue, Args,
4194 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
4197 LValue CodeGenFunction::
4198 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4199 Address BaseAddr = Address::invalid();
4200 if (E->getOpcode() == BO_PtrMemI) {
4201 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4203 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4206 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4208 const MemberPointerType *MPT
4209 = E->getRHS()->getType()->getAs<MemberPointerType>();
4211 AlignmentSource AlignSource;
4212 Address MemberAddr =
4213 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4216 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4219 /// Given the address of a temporary variable, produce an r-value of
4221 RValue CodeGenFunction::convertTempToRValue(Address addr,
4223 SourceLocation loc) {
4224 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4225 switch (getEvaluationKind(type)) {
4227 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4229 return lvalue.asAggregateRValue();
4231 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4233 llvm_unreachable("bad evaluation kind");
4236 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4237 assert(Val->getType()->isFPOrFPVectorTy());
4238 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4241 llvm::MDBuilder MDHelper(getLLVMContext());
4242 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4244 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4248 struct LValueOrRValue {
4254 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4255 const PseudoObjectExpr *E,
4257 AggValueSlot slot) {
4258 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4260 // Find the result expression, if any.
4261 const Expr *resultExpr = E->getResultExpr();
4262 LValueOrRValue result;
4264 for (PseudoObjectExpr::const_semantics_iterator
4265 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4266 const Expr *semantic = *i;
4268 // If this semantic expression is an opaque value, bind it
4269 // to the result of its source expression.
4270 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4272 // If this is the result expression, we may need to evaluate
4273 // directly into the slot.
4274 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4276 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4277 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4278 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4280 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4281 AlignmentSource::Decl);
4282 opaqueData = OVMA::bind(CGF, ov, LV);
4283 result.RV = slot.asRValue();
4285 // Otherwise, emit as normal.
4287 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4289 // If this is the result, also evaluate the result now.
4290 if (ov == resultExpr) {
4292 result.LV = CGF.EmitLValue(ov);
4294 result.RV = CGF.EmitAnyExpr(ov, slot);
4298 opaques.push_back(opaqueData);
4300 // Otherwise, if the expression is the result, evaluate it
4301 // and remember the result.
4302 } else if (semantic == resultExpr) {
4304 result.LV = CGF.EmitLValue(semantic);
4306 result.RV = CGF.EmitAnyExpr(semantic, slot);
4308 // Otherwise, evaluate the expression in an ignored context.
4310 CGF.EmitIgnoredExpr(semantic);
4314 // Unbind all the opaques now.
4315 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4316 opaques[i].unbind(CGF);
4321 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4322 AggValueSlot slot) {
4323 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4326 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4327 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;