1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate 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 Aggregate Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
28 //===----------------------------------------------------------------------===//
29 // Aggregate Expression Emitter
30 //===----------------------------------------------------------------------===//
33 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
38 /// We want to use 'dest' as the return slot except under two
40 /// - The destination slot requires garbage collection, so we
41 /// need to use the GC API.
42 /// - The destination slot is potentially aliased.
43 bool shouldUseDestForReturnSlot() const {
44 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
47 ReturnValueSlot getReturnValueSlot() const {
48 if (!shouldUseDestForReturnSlot())
49 return ReturnValueSlot();
51 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
54 AggValueSlot EnsureSlot(QualType T) {
55 if (!Dest.isIgnored()) return Dest;
56 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
58 void EnsureDest(QualType T) {
59 if (!Dest.isIgnored()) return;
60 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
64 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
65 : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
68 //===--------------------------------------------------------------------===//
70 //===--------------------------------------------------------------------===//
72 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
73 /// represents a value lvalue, this method emits the address of the lvalue,
74 /// then loads the result into DestPtr.
75 void EmitAggLoadOfLValue(const Expr *E);
77 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
78 void EmitFinalDestCopy(QualType type, const LValue &src);
79 void EmitFinalDestCopy(QualType type, RValue src,
80 CharUnits srcAlignment = CharUnits::Zero());
81 void EmitCopy(QualType type, const AggValueSlot &dest,
82 const AggValueSlot &src);
84 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
86 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
87 QualType elementType, InitListExpr *E);
89 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
90 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
91 return AggValueSlot::NeedsGCBarriers;
92 return AggValueSlot::DoesNotNeedGCBarriers;
95 bool TypeRequiresGCollection(QualType T);
97 //===--------------------------------------------------------------------===//
99 //===--------------------------------------------------------------------===//
101 void Visit(Expr *E) {
102 ApplyDebugLocation DL(CGF, E);
103 StmtVisitor<AggExprEmitter>::Visit(E);
106 void VisitStmt(Stmt *S) {
107 CGF.ErrorUnsupported(S, "aggregate expression");
109 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
110 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
111 Visit(GE->getResultExpr());
113 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
114 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
115 return Visit(E->getReplacement());
119 void VisitDeclRefExpr(DeclRefExpr *E) {
120 // For aggregates, we should always be able to emit the variable
121 // as an l-value unless it's a reference. This is due to the fact
122 // that we can't actually ever see a normal l2r conversion on an
123 // aggregate in C++, and in C there's no language standard
124 // actively preventing us from listing variables in the captures
126 if (E->getDecl()->getType()->isReferenceType()) {
127 if (CodeGenFunction::ConstantEmission result
128 = CGF.tryEmitAsConstant(E)) {
129 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
134 EmitAggLoadOfLValue(E);
137 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
138 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
139 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
140 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
141 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
142 EmitAggLoadOfLValue(E);
144 void VisitPredefinedExpr(const PredefinedExpr *E) {
145 EmitAggLoadOfLValue(E);
149 void VisitCastExpr(CastExpr *E);
150 void VisitCallExpr(const CallExpr *E);
151 void VisitStmtExpr(const StmtExpr *E);
152 void VisitBinaryOperator(const BinaryOperator *BO);
153 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
154 void VisitBinAssign(const BinaryOperator *E);
155 void VisitBinComma(const BinaryOperator *E);
157 void VisitObjCMessageExpr(ObjCMessageExpr *E);
158 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
159 EmitAggLoadOfLValue(E);
162 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
163 void VisitChooseExpr(const ChooseExpr *CE);
164 void VisitInitListExpr(InitListExpr *E);
165 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
166 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
167 Visit(DAE->getExpr());
169 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
170 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
171 Visit(DIE->getExpr());
173 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
174 void VisitCXXConstructExpr(const CXXConstructExpr *E);
175 void VisitLambdaExpr(LambdaExpr *E);
176 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
177 void VisitExprWithCleanups(ExprWithCleanups *E);
178 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
179 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
180 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
181 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
183 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
184 if (E->isGLValue()) {
185 LValue LV = CGF.EmitPseudoObjectLValue(E);
186 return EmitFinalDestCopy(E->getType(), LV);
189 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
192 void VisitVAArgExpr(VAArgExpr *E);
194 void EmitInitializationToLValue(Expr *E, LValue Address);
195 void EmitNullInitializationToLValue(LValue Address);
196 // case Expr::ChooseExprClass:
197 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
198 void VisitAtomicExpr(AtomicExpr *E) {
199 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
202 } // end anonymous namespace.
204 //===----------------------------------------------------------------------===//
206 //===----------------------------------------------------------------------===//
208 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
209 /// represents a value lvalue, this method emits the address of the lvalue,
210 /// then loads the result into DestPtr.
211 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
212 LValue LV = CGF.EmitLValue(E);
214 // If the type of the l-value is atomic, then do an atomic load.
215 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
216 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
220 EmitFinalDestCopy(E->getType(), LV);
223 /// \brief True if the given aggregate type requires special GC API calls.
224 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
225 // Only record types have members that might require garbage collection.
226 const RecordType *RecordTy = T->getAs<RecordType>();
227 if (!RecordTy) return false;
229 // Don't mess with non-trivial C++ types.
230 RecordDecl *Record = RecordTy->getDecl();
231 if (isa<CXXRecordDecl>(Record) &&
232 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
233 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
236 // Check whether the type has an object member.
237 return Record->hasObjectMember();
240 /// \brief Perform the final move to DestPtr if for some reason
241 /// getReturnValueSlot() didn't use it directly.
243 /// The idea is that you do something like this:
244 /// RValue Result = EmitSomething(..., getReturnValueSlot());
245 /// EmitMoveFromReturnSlot(E, Result);
247 /// If nothing interferes, this will cause the result to be emitted
248 /// directly into the return value slot. Otherwise, a final move
249 /// will be performed.
250 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
251 if (shouldUseDestForReturnSlot()) {
252 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
253 // The possibility of undef rvalues complicates that a lot,
254 // though, so we can't really assert.
258 // Otherwise, copy from there to the destination.
259 assert(Dest.getAddr() != src.getAggregateAddr());
260 std::pair<CharUnits, CharUnits> typeInfo =
261 CGF.getContext().getTypeInfoInChars(E->getType());
262 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
265 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
266 void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
267 CharUnits srcAlign) {
268 assert(src.isAggregate() && "value must be aggregate value!");
269 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
270 EmitFinalDestCopy(type, srcLV);
273 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
274 void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
275 // If Dest is ignored, then we're evaluating an aggregate expression
276 // in a context that doesn't care about the result. Note that loads
277 // from volatile l-values force the existence of a non-ignored
279 if (Dest.isIgnored())
282 AggValueSlot srcAgg =
283 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
284 needsGC(type), AggValueSlot::IsAliased);
285 EmitCopy(type, Dest, srcAgg);
288 /// Perform a copy from the source into the destination.
290 /// \param type - the type of the aggregate being copied; qualifiers are
292 void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
293 const AggValueSlot &src) {
294 if (dest.requiresGCollection()) {
295 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
296 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
297 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
304 // If the result of the assignment is used, copy the LHS there also.
305 // It's volatile if either side is. Use the minimum alignment of
307 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
308 dest.isVolatile() || src.isVolatile(),
309 std::min(dest.getAlignment(), src.getAlignment()));
312 /// \brief Emit the initializer for a std::initializer_list initialized with a
313 /// real initializer list.
315 AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
316 // Emit an array containing the elements. The array is externally destructed
317 // if the std::initializer_list object is.
318 ASTContext &Ctx = CGF.getContext();
319 LValue Array = CGF.EmitLValue(E->getSubExpr());
320 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
321 llvm::Value *ArrayPtr = Array.getAddress();
323 const ConstantArrayType *ArrayType =
324 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
325 assert(ArrayType && "std::initializer_list constructed from non-array");
327 // FIXME: Perform the checks on the field types in SemaInit.
328 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
329 RecordDecl::field_iterator Field = Record->field_begin();
330 if (Field == Record->field_end()) {
331 CGF.ErrorUnsupported(E, "weird std::initializer_list");
336 if (!Field->getType()->isPointerType() ||
337 !Ctx.hasSameType(Field->getType()->getPointeeType(),
338 ArrayType->getElementType())) {
339 CGF.ErrorUnsupported(E, "weird std::initializer_list");
343 AggValueSlot Dest = EnsureSlot(E->getType());
344 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
345 Dest.getAlignment());
346 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
347 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
348 llvm::Value *IdxStart[] = { Zero, Zero };
349 llvm::Value *ArrayStart =
350 Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
351 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
354 if (Field == Record->field_end()) {
355 CGF.ErrorUnsupported(E, "weird std::initializer_list");
359 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
360 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
361 if (Field->getType()->isPointerType() &&
362 Ctx.hasSameType(Field->getType()->getPointeeType(),
363 ArrayType->getElementType())) {
365 llvm::Value *IdxEnd[] = { Zero, Size };
366 llvm::Value *ArrayEnd =
367 Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
368 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
369 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
371 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
373 CGF.ErrorUnsupported(E, "weird std::initializer_list");
378 /// \brief Determine if E is a trivial array filler, that is, one that is
379 /// equivalent to zero-initialization.
380 static bool isTrivialFiller(Expr *E) {
384 if (isa<ImplicitValueInitExpr>(E))
387 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
388 if (ILE->getNumInits())
390 return isTrivialFiller(ILE->getArrayFiller());
393 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
394 return Cons->getConstructor()->isDefaultConstructor() &&
395 Cons->getConstructor()->isTrivial();
397 // FIXME: Are there other cases where we can avoid emitting an initializer?
401 /// \brief Emit initialization of an array from an initializer list.
402 void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
403 QualType elementType, InitListExpr *E) {
404 uint64_t NumInitElements = E->getNumInits();
406 uint64_t NumArrayElements = AType->getNumElements();
407 assert(NumInitElements <= NumArrayElements);
409 // DestPtr is an array*. Construct an elementType* by drilling
411 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
412 llvm::Value *indices[] = { zero, zero };
414 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
416 // Exception safety requires us to destroy all the
417 // already-constructed members if an initializer throws.
418 // For that, we'll need an EH cleanup.
419 QualType::DestructionKind dtorKind = elementType.isDestructedType();
420 llvm::AllocaInst *endOfInit = nullptr;
421 EHScopeStack::stable_iterator cleanup;
422 llvm::Instruction *cleanupDominator = nullptr;
423 if (CGF.needsEHCleanup(dtorKind)) {
424 // In principle we could tell the cleanup where we are more
425 // directly, but the control flow can get so varied here that it
426 // would actually be quite complex. Therefore we go through an
428 endOfInit = CGF.CreateTempAlloca(begin->getType(),
429 "arrayinit.endOfInit");
430 cleanupDominator = Builder.CreateStore(begin, endOfInit);
431 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
432 CGF.getDestroyer(dtorKind));
433 cleanup = CGF.EHStack.stable_begin();
435 // Otherwise, remember that we didn't need a cleanup.
437 dtorKind = QualType::DK_none;
440 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
442 // The 'current element to initialize'. The invariants on this
443 // variable are complicated. Essentially, after each iteration of
444 // the loop, it points to the last initialized element, except
445 // that it points to the beginning of the array before any
446 // elements have been initialized.
447 llvm::Value *element = begin;
449 // Emit the explicit initializers.
450 for (uint64_t i = 0; i != NumInitElements; ++i) {
451 // Advance to the next element.
453 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
455 // Tell the cleanup that it needs to destroy up to this
456 // element. TODO: some of these stores can be trivially
457 // observed to be unnecessary.
458 if (endOfInit) Builder.CreateStore(element, endOfInit);
461 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
462 EmitInitializationToLValue(E->getInit(i), elementLV);
465 // Check whether there's a non-trivial array-fill expression.
466 Expr *filler = E->getArrayFiller();
467 bool hasTrivialFiller = isTrivialFiller(filler);
469 // Any remaining elements need to be zero-initialized, possibly
470 // using the filler expression. We can skip this if the we're
471 // emitting to zeroed memory.
472 if (NumInitElements != NumArrayElements &&
473 !(Dest.isZeroed() && hasTrivialFiller &&
474 CGF.getTypes().isZeroInitializable(elementType))) {
476 // Use an actual loop. This is basically
477 // do { *array++ = filler; } while (array != end);
479 // Advance to the start of the rest of the array.
480 if (NumInitElements) {
481 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
482 if (endOfInit) Builder.CreateStore(element, endOfInit);
485 // Compute the end of the array.
486 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
487 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
490 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
491 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
493 // Jump into the body.
494 CGF.EmitBlock(bodyBB);
495 llvm::PHINode *currentElement =
496 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
497 currentElement->addIncoming(element, entryBB);
499 // Emit the actual filler expression.
500 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
502 EmitInitializationToLValue(filler, elementLV);
504 EmitNullInitializationToLValue(elementLV);
506 // Move on to the next element.
507 llvm::Value *nextElement =
508 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
510 // Tell the EH cleanup that we finished with the last element.
511 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
513 // Leave the loop if we're done.
514 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
516 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
517 Builder.CreateCondBr(done, endBB, bodyBB);
518 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
520 CGF.EmitBlock(endBB);
523 // Leave the partial-array cleanup if we entered one.
524 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
527 //===----------------------------------------------------------------------===//
529 //===----------------------------------------------------------------------===//
531 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
532 Visit(E->GetTemporaryExpr());
535 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
536 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
540 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
541 if (Dest.isPotentiallyAliased() &&
542 E->getType().isPODType(CGF.getContext())) {
543 // For a POD type, just emit a load of the lvalue + a copy, because our
544 // compound literal might alias the destination.
545 EmitAggLoadOfLValue(E);
549 AggValueSlot Slot = EnsureSlot(E->getType());
550 CGF.EmitAggExpr(E->getInitializer(), Slot);
553 /// Attempt to look through various unimportant expressions to find a
554 /// cast of the given kind.
555 static Expr *findPeephole(Expr *op, CastKind kind) {
557 op = op->IgnoreParens();
558 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
559 if (castE->getCastKind() == kind)
560 return castE->getSubExpr();
561 if (castE->getCastKind() == CK_NoOp)
568 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
569 switch (E->getCastKind()) {
571 // FIXME: Can this actually happen? We have no test coverage for it.
572 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
573 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
574 CodeGenFunction::TCK_Load);
575 // FIXME: Do we also need to handle property references here?
577 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
579 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
581 if (!Dest.isIgnored())
582 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
587 // Evaluate even if the destination is ignored.
588 if (Dest.isIgnored()) {
589 CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
590 /*ignoreResult=*/true);
594 // GCC union extension
595 QualType Ty = E->getSubExpr()->getType();
596 QualType PtrTy = CGF.getContext().getPointerType(Ty);
597 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
598 CGF.ConvertType(PtrTy));
599 EmitInitializationToLValue(E->getSubExpr(),
600 CGF.MakeAddrLValue(CastPtr, Ty));
604 case CK_DerivedToBase:
605 case CK_BaseToDerived:
606 case CK_UncheckedDerivedToBase: {
607 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
608 "should have been unpacked before we got here");
611 case CK_NonAtomicToAtomic:
612 case CK_AtomicToNonAtomic: {
613 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
615 // Determine the atomic and value types.
616 QualType atomicType = E->getSubExpr()->getType();
617 QualType valueType = E->getType();
618 if (isToAtomic) std::swap(atomicType, valueType);
620 assert(atomicType->isAtomicType());
621 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
622 atomicType->castAs<AtomicType>()->getValueType()));
624 // Just recurse normally if we're ignoring the result or the
625 // atomic type doesn't change representation.
626 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
627 return Visit(E->getSubExpr());
630 CastKind peepholeTarget =
631 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
633 // These two cases are reverses of each other; try to peephole them.
634 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
635 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
637 "peephole significantly changed types?");
641 // If we're converting an r-value of non-atomic type to an r-value
642 // of atomic type, just emit directly into the relevant sub-object.
644 AggValueSlot valueDest = Dest;
645 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
646 // Zero-initialize. (Strictly speaking, we only need to intialize
647 // the padding at the end, but this is simpler.)
648 if (!Dest.isZeroed())
649 CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
651 // Build a GEP to refer to the subobject.
652 llvm::Value *valueAddr =
653 CGF.Builder.CreateStructGEP(nullptr, valueDest.getAddr(), 0);
654 valueDest = AggValueSlot::forAddr(valueAddr,
655 valueDest.getAlignment(),
656 valueDest.getQualifiers(),
657 valueDest.isExternallyDestructed(),
658 valueDest.requiresGCollection(),
659 valueDest.isPotentiallyAliased(),
660 AggValueSlot::IsZeroed);
663 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
667 // Otherwise, we're converting an atomic type to a non-atomic type.
668 // Make an atomic temporary, emit into that, and then copy the value out.
669 AggValueSlot atomicSlot =
670 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
671 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
673 llvm::Value *valueAddr =
674 Builder.CreateStructGEP(nullptr, atomicSlot.getAddr(), 0);
675 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
676 return EmitFinalDestCopy(valueType, rvalue);
679 case CK_LValueToRValue:
680 // If we're loading from a volatile type, force the destination
682 if (E->getSubExpr()->getType().isVolatileQualified()) {
683 EnsureDest(E->getType());
684 return Visit(E->getSubExpr());
690 case CK_UserDefinedConversion:
691 case CK_ConstructorConversion:
692 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
694 "Implicit cast types must be compatible");
695 Visit(E->getSubExpr());
698 case CK_LValueBitCast:
699 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
703 case CK_ArrayToPointerDecay:
704 case CK_FunctionToPointerDecay:
705 case CK_NullToPointer:
706 case CK_NullToMemberPointer:
707 case CK_BaseToDerivedMemberPointer:
708 case CK_DerivedToBaseMemberPointer:
709 case CK_MemberPointerToBoolean:
710 case CK_ReinterpretMemberPointer:
711 case CK_IntegralToPointer:
712 case CK_PointerToIntegral:
713 case CK_PointerToBoolean:
716 case CK_IntegralCast:
717 case CK_IntegralToBoolean:
718 case CK_IntegralToFloating:
719 case CK_FloatingToIntegral:
720 case CK_FloatingToBoolean:
721 case CK_FloatingCast:
722 case CK_CPointerToObjCPointerCast:
723 case CK_BlockPointerToObjCPointerCast:
724 case CK_AnyPointerToBlockPointerCast:
725 case CK_ObjCObjectLValueCast:
726 case CK_FloatingRealToComplex:
727 case CK_FloatingComplexToReal:
728 case CK_FloatingComplexToBoolean:
729 case CK_FloatingComplexCast:
730 case CK_FloatingComplexToIntegralComplex:
731 case CK_IntegralRealToComplex:
732 case CK_IntegralComplexToReal:
733 case CK_IntegralComplexToBoolean:
734 case CK_IntegralComplexCast:
735 case CK_IntegralComplexToFloatingComplex:
736 case CK_ARCProduceObject:
737 case CK_ARCConsumeObject:
738 case CK_ARCReclaimReturnedObject:
739 case CK_ARCExtendBlockObject:
740 case CK_CopyAndAutoreleaseBlockObject:
741 case CK_BuiltinFnToFnPtr:
742 case CK_ZeroToOCLEvent:
743 case CK_AddressSpaceConversion:
744 llvm_unreachable("cast kind invalid for aggregate types");
748 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
749 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
750 EmitAggLoadOfLValue(E);
754 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
755 EmitMoveFromReturnSlot(E, RV);
758 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
759 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
760 EmitMoveFromReturnSlot(E, RV);
763 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
764 CGF.EmitIgnoredExpr(E->getLHS());
768 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
769 CodeGenFunction::StmtExprEvaluation eval(CGF);
770 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
773 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
774 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
775 VisitPointerToDataMemberBinaryOperator(E);
777 CGF.ErrorUnsupported(E, "aggregate binary expression");
780 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
781 const BinaryOperator *E) {
782 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
783 EmitFinalDestCopy(E->getType(), LV);
786 /// Is the value of the given expression possibly a reference to or
787 /// into a __block variable?
788 static bool isBlockVarRef(const Expr *E) {
789 // Make sure we look through parens.
790 E = E->IgnoreParens();
792 // Check for a direct reference to a __block variable.
793 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
794 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
795 return (var && var->hasAttr<BlocksAttr>());
798 // More complicated stuff.
801 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
802 // For an assignment or pointer-to-member operation, just care
804 if (op->isAssignmentOp() || op->isPtrMemOp())
805 return isBlockVarRef(op->getLHS());
807 // For a comma, just care about the RHS.
808 if (op->getOpcode() == BO_Comma)
809 return isBlockVarRef(op->getRHS());
811 // FIXME: pointer arithmetic?
814 // Check both sides of a conditional operator.
815 } else if (const AbstractConditionalOperator *op
816 = dyn_cast<AbstractConditionalOperator>(E)) {
817 return isBlockVarRef(op->getTrueExpr())
818 || isBlockVarRef(op->getFalseExpr());
820 // OVEs are required to support BinaryConditionalOperators.
821 } else if (const OpaqueValueExpr *op
822 = dyn_cast<OpaqueValueExpr>(E)) {
823 if (const Expr *src = op->getSourceExpr())
824 return isBlockVarRef(src);
826 // Casts are necessary to get things like (*(int*)&var) = foo().
827 // We don't really care about the kind of cast here, except
828 // we don't want to look through l2r casts, because it's okay
829 // to get the *value* in a __block variable.
830 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
831 if (cast->getCastKind() == CK_LValueToRValue)
833 return isBlockVarRef(cast->getSubExpr());
835 // Handle unary operators. Again, just aggressively look through
836 // it, ignoring the operation.
837 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
838 return isBlockVarRef(uop->getSubExpr());
840 // Look into the base of a field access.
841 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
842 return isBlockVarRef(mem->getBase());
844 // Look into the base of a subscript.
845 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
846 return isBlockVarRef(sub->getBase());
852 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
853 // For an assignment to work, the value on the right has
854 // to be compatible with the value on the left.
855 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
856 E->getRHS()->getType())
857 && "Invalid assignment");
859 // If the LHS might be a __block variable, and the RHS can
860 // potentially cause a block copy, we need to evaluate the RHS first
861 // so that the assignment goes the right place.
862 // This is pretty semantically fragile.
863 if (isBlockVarRef(E->getLHS()) &&
864 E->getRHS()->HasSideEffects(CGF.getContext())) {
865 // Ensure that we have a destination, and evaluate the RHS into that.
866 EnsureDest(E->getRHS()->getType());
869 // Now emit the LHS and copy into it.
870 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
872 // That copy is an atomic copy if the LHS is atomic.
873 if (LHS.getType()->isAtomicType() ||
874 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
875 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
879 EmitCopy(E->getLHS()->getType(),
880 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
881 needsGC(E->getLHS()->getType()),
882 AggValueSlot::IsAliased),
887 LValue LHS = CGF.EmitLValue(E->getLHS());
889 // If we have an atomic type, evaluate into the destination and then
890 // do an atomic copy.
891 if (LHS.getType()->isAtomicType() ||
892 CGF.LValueIsSuitableForInlineAtomic(LHS)) {
893 EnsureDest(E->getRHS()->getType());
895 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
899 // Codegen the RHS so that it stores directly into the LHS.
900 AggValueSlot LHSSlot =
901 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
902 needsGC(E->getLHS()->getType()),
903 AggValueSlot::IsAliased);
904 // A non-volatile aggregate destination might have volatile member.
905 if (!LHSSlot.isVolatile() &&
906 CGF.hasVolatileMember(E->getLHS()->getType()))
907 LHSSlot.setVolatile(true);
909 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
911 // Copy into the destination if the assignment isn't ignored.
912 EmitFinalDestCopy(E->getType(), LHS);
915 void AggExprEmitter::
916 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
917 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
918 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
919 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
921 // Bind the common expression if necessary.
922 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
924 CodeGenFunction::ConditionalEvaluation eval(CGF);
925 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
926 CGF.getProfileCount(E));
928 // Save whether the destination's lifetime is externally managed.
929 bool isExternallyDestructed = Dest.isExternallyDestructed();
932 CGF.EmitBlock(LHSBlock);
933 CGF.incrementProfileCounter(E);
934 Visit(E->getTrueExpr());
937 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
938 CGF.Builder.CreateBr(ContBlock);
940 // If the result of an agg expression is unused, then the emission
941 // of the LHS might need to create a destination slot. That's fine
942 // with us, and we can safely emit the RHS into the same slot, but
943 // we shouldn't claim that it's already being destructed.
944 Dest.setExternallyDestructed(isExternallyDestructed);
947 CGF.EmitBlock(RHSBlock);
948 Visit(E->getFalseExpr());
951 CGF.EmitBlock(ContBlock);
954 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
955 Visit(CE->getChosenSubExpr());
958 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
959 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
960 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
963 // If EmitVAArg fails, we fall back to the LLVM instruction.
965 Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
966 if (!Dest.isIgnored())
967 Builder.CreateStore(Val, Dest.getAddr());
971 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
974 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
975 // Ensure that we have a slot, but if we already do, remember
976 // whether it was externally destructed.
977 bool wasExternallyDestructed = Dest.isExternallyDestructed();
978 EnsureDest(E->getType());
980 // We're going to push a destructor if there isn't already one.
981 Dest.setExternallyDestructed();
983 Visit(E->getSubExpr());
985 // Push that destructor we promised.
986 if (!wasExternallyDestructed)
987 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
991 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
992 AggValueSlot Slot = EnsureSlot(E->getType());
993 CGF.EmitCXXConstructExpr(E, Slot);
997 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
998 AggValueSlot Slot = EnsureSlot(E->getType());
999 CGF.EmitLambdaExpr(E, Slot);
1002 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1003 CGF.enterFullExpression(E);
1004 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1005 Visit(E->getSubExpr());
1008 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1009 QualType T = E->getType();
1010 AggValueSlot Slot = EnsureSlot(T);
1011 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1014 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1015 QualType T = E->getType();
1016 AggValueSlot Slot = EnsureSlot(T);
1017 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1020 /// isSimpleZero - If emitting this value will obviously just cause a store of
1021 /// zero to memory, return true. This can return false if uncertain, so it just
1022 /// handles simple cases.
1023 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1024 E = E->IgnoreParens();
1027 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1028 return IL->getValue() == 0;
1030 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1031 return FL->getValue().isPosZero();
1033 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1034 CGF.getTypes().isZeroInitializable(E->getType()))
1036 // (int*)0 - Null pointer expressions.
1037 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1038 return ICE->getCastKind() == CK_NullToPointer;
1040 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1041 return CL->getValue() == 0;
1043 // Otherwise, hard case: conservatively return false.
1049 AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1050 QualType type = LV.getType();
1051 // FIXME: Ignore result?
1052 // FIXME: Are initializers affected by volatile?
1053 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1054 // Storing "i32 0" to a zero'd memory location is a noop.
1056 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1057 return EmitNullInitializationToLValue(LV);
1058 } else if (type->isReferenceType()) {
1059 RValue RV = CGF.EmitReferenceBindingToExpr(E);
1060 return CGF.EmitStoreThroughLValue(RV, LV);
1063 switch (CGF.getEvaluationKind(type)) {
1065 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1068 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1069 AggValueSlot::IsDestructed,
1070 AggValueSlot::DoesNotNeedGCBarriers,
1071 AggValueSlot::IsNotAliased,
1075 if (LV.isSimple()) {
1076 CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1078 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1082 llvm_unreachable("bad evaluation kind");
1085 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1086 QualType type = lv.getType();
1088 // If the destination slot is already zeroed out before the aggregate is
1089 // copied into it, we don't have to emit any zeros here.
1090 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1093 if (CGF.hasScalarEvaluationKind(type)) {
1094 // For non-aggregates, we can store the appropriate null constant.
1095 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1096 // Note that the following is not equivalent to
1097 // EmitStoreThroughBitfieldLValue for ARC types.
1098 if (lv.isBitField()) {
1099 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1101 assert(lv.isSimple());
1102 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1105 // There's a potential optimization opportunity in combining
1106 // memsets; that would be easy for arrays, but relatively
1107 // difficult for structures with the current code.
1108 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1112 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1114 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1115 // (Length of globals? Chunks of zeroed-out space?).
1117 // If we can, prefer a copy from a global; this is a lot less code for long
1118 // globals, and it's easier for the current optimizers to analyze.
1119 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1120 llvm::GlobalVariable* GV =
1121 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1122 llvm::GlobalValue::InternalLinkage, C, "");
1123 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1127 if (E->hadArrayRangeDesignator())
1128 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1130 AggValueSlot Dest = EnsureSlot(E->getType());
1132 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1133 Dest.getAlignment());
1135 // Handle initialization of an array.
1136 if (E->getType()->isArrayType()) {
1137 if (E->isStringLiteralInit())
1138 return Visit(E->getInit(0));
1140 QualType elementType =
1141 CGF.getContext().getAsArrayType(E->getType())->getElementType();
1143 llvm::PointerType *APType =
1144 cast<llvm::PointerType>(Dest.getAddr()->getType());
1145 llvm::ArrayType *AType =
1146 cast<llvm::ArrayType>(APType->getElementType());
1148 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
1152 if (E->getType()->isAtomicType()) {
1153 // An _Atomic(T) object can be list-initialized from an expression
1154 // of the same type.
1155 assert(E->getNumInits() == 1 &&
1156 CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
1158 "unexpected list initialization for atomic object");
1159 return Visit(E->getInit(0));
1162 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1164 // Do struct initialization; this code just sets each individual member
1165 // to the approprate value. This makes bitfield support automatic;
1166 // the disadvantage is that the generated code is more difficult for
1167 // the optimizer, especially with bitfields.
1168 unsigned NumInitElements = E->getNumInits();
1169 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1171 // Prepare a 'this' for CXXDefaultInitExprs.
1172 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1174 if (record->isUnion()) {
1175 // Only initialize one field of a union. The field itself is
1176 // specified by the initializer list.
1177 if (!E->getInitializedFieldInUnion()) {
1178 // Empty union; we have nothing to do.
1181 // Make sure that it's really an empty and not a failure of
1182 // semantic analysis.
1183 for (const auto *Field : record->fields())
1184 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1189 // FIXME: volatility
1190 FieldDecl *Field = E->getInitializedFieldInUnion();
1192 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1193 if (NumInitElements) {
1194 // Store the initializer into the field
1195 EmitInitializationToLValue(E->getInit(0), FieldLoc);
1197 // Default-initialize to null.
1198 EmitNullInitializationToLValue(FieldLoc);
1204 // We'll need to enter cleanup scopes in case any of the member
1205 // initializers throw an exception.
1206 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1207 llvm::Instruction *cleanupDominator = nullptr;
1209 // Here we iterate over the fields; this makes it simpler to both
1210 // default-initialize fields and skip over unnamed fields.
1211 unsigned curInitIndex = 0;
1212 for (const auto *field : record->fields()) {
1213 // We're done once we hit the flexible array member.
1214 if (field->getType()->isIncompleteArrayType())
1217 // Always skip anonymous bitfields.
1218 if (field->isUnnamedBitfield())
1221 // We're done if we reach the end of the explicit initializers, we
1222 // have a zeroed object, and the rest of the fields are
1223 // zero-initializable.
1224 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1225 CGF.getTypes().isZeroInitializable(E->getType()))
1229 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1230 // We never generate write-barries for initialized fields.
1233 if (curInitIndex < NumInitElements) {
1234 // Store the initializer into the field.
1235 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1237 // We're out of initalizers; default-initialize to null
1238 EmitNullInitializationToLValue(LV);
1241 // Push a destructor if necessary.
1242 // FIXME: if we have an array of structures, all explicitly
1243 // initialized, we can end up pushing a linear number of cleanups.
1244 bool pushedCleanup = false;
1245 if (QualType::DestructionKind dtorKind
1246 = field->getType().isDestructedType()) {
1247 assert(LV.isSimple());
1248 if (CGF.needsEHCleanup(dtorKind)) {
1249 if (!cleanupDominator)
1250 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1252 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1253 CGF.getDestroyer(dtorKind), false);
1254 cleanups.push_back(CGF.EHStack.stable_begin());
1255 pushedCleanup = true;
1259 // If the GEP didn't get used because of a dead zero init or something
1260 // else, clean it up for -O0 builds and general tidiness.
1261 if (!pushedCleanup && LV.isSimple())
1262 if (llvm::GetElementPtrInst *GEP =
1263 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
1264 if (GEP->use_empty())
1265 GEP->eraseFromParent();
1268 // Deactivate all the partial cleanups in reverse order, which
1269 // generally means popping them.
1270 for (unsigned i = cleanups.size(); i != 0; --i)
1271 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1273 // Destroy the placeholder if we made one.
1274 if (cleanupDominator)
1275 cleanupDominator->eraseFromParent();
1278 //===----------------------------------------------------------------------===//
1279 // Entry Points into this File
1280 //===----------------------------------------------------------------------===//
1282 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1283 /// non-zero bytes that will be stored when outputting the initializer for the
1284 /// specified initializer expression.
1285 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1286 E = E->IgnoreParens();
1288 // 0 and 0.0 won't require any non-zero stores!
1289 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1291 // If this is an initlist expr, sum up the size of sizes of the (present)
1292 // elements. If this is something weird, assume the whole thing is non-zero.
1293 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1294 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1295 return CGF.getContext().getTypeSizeInChars(E->getType());
1297 // InitListExprs for structs have to be handled carefully. If there are
1298 // reference members, we need to consider the size of the reference, not the
1299 // referencee. InitListExprs for unions and arrays can't have references.
1300 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1301 if (!RT->isUnionType()) {
1302 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1303 CharUnits NumNonZeroBytes = CharUnits::Zero();
1305 unsigned ILEElement = 0;
1306 for (const auto *Field : SD->fields()) {
1307 // We're done once we hit the flexible array member or run out of
1308 // InitListExpr elements.
1309 if (Field->getType()->isIncompleteArrayType() ||
1310 ILEElement == ILE->getNumInits())
1312 if (Field->isUnnamedBitfield())
1315 const Expr *E = ILE->getInit(ILEElement++);
1317 // Reference values are always non-null and have the width of a pointer.
1318 if (Field->getType()->isReferenceType())
1319 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1320 CGF.getTarget().getPointerWidth(0));
1322 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1325 return NumNonZeroBytes;
1330 CharUnits NumNonZeroBytes = CharUnits::Zero();
1331 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1332 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1333 return NumNonZeroBytes;
1336 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1337 /// zeros in it, emit a memset and avoid storing the individual zeros.
1339 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1340 CodeGenFunction &CGF) {
1341 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1343 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
1346 // C++ objects with a user-declared constructor don't need zero'ing.
1347 if (CGF.getLangOpts().CPlusPlus)
1348 if (const RecordType *RT = CGF.getContext()
1349 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1350 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1351 if (RD->hasUserDeclaredConstructor())
1355 // If the type is 16-bytes or smaller, prefer individual stores over memset.
1356 std::pair<CharUnits, CharUnits> TypeInfo =
1357 CGF.getContext().getTypeInfoInChars(E->getType());
1358 if (TypeInfo.first <= CharUnits::fromQuantity(16))
1361 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1362 // we prefer to emit memset + individual stores for the rest.
1363 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1364 if (NumNonZeroBytes*4 > TypeInfo.first)
1367 // Okay, it seems like a good idea to use an initial memset, emit the call.
1368 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1369 CharUnits Align = TypeInfo.second;
1371 llvm::Value *Loc = Slot.getAddr();
1373 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1374 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1375 Align.getQuantity(), false);
1377 // Tell the AggExprEmitter that the slot is known zero.
1384 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1385 /// type. The result is computed into DestPtr. Note that if DestPtr is null,
1386 /// the value of the aggregate expression is not needed. If VolatileDest is
1387 /// true, DestPtr cannot be 0.
1388 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1389 assert(E && hasAggregateEvaluationKind(E->getType()) &&
1390 "Invalid aggregate expression to emit");
1391 assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
1392 "slot has bits but no address");
1394 // Optimize the slot if possible.
1395 CheckAggExprForMemSetUse(Slot, E, *this);
1397 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
1400 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1401 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1402 llvm::Value *Temp = CreateMemTemp(E->getType());
1403 LValue LV = MakeAddrLValue(Temp, E->getType());
1404 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
1405 AggValueSlot::DoesNotNeedGCBarriers,
1406 AggValueSlot::IsNotAliased));
1410 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1411 llvm::Value *SrcPtr, QualType Ty,
1413 CharUnits alignment,
1414 bool isAssignment) {
1415 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1417 if (getLangOpts().CPlusPlus) {
1418 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1419 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1420 assert((Record->hasTrivialCopyConstructor() ||
1421 Record->hasTrivialCopyAssignment() ||
1422 Record->hasTrivialMoveConstructor() ||
1423 Record->hasTrivialMoveAssignment() ||
1424 Record->isUnion()) &&
1425 "Trying to aggregate-copy a type without a trivial copy/move "
1426 "constructor or assignment operator");
1427 // Ignore empty classes in C++.
1428 if (Record->isEmpty())
1433 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
1434 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1435 // read from another object that overlaps in anyway the storage of the first
1436 // object, then the overlap shall be exact and the two objects shall have
1437 // qualified or unqualified versions of a compatible type."
1439 // memcpy is not defined if the source and destination pointers are exactly
1440 // equal, but other compilers do this optimization, and almost every memcpy
1441 // implementation handles this case safely. If there is a libc that does not
1442 // safely handle this, we can add a target hook.
1444 // Get data size and alignment info for this aggregate. If this is an
1445 // assignment don't copy the tail padding. Otherwise copying it is fine.
1446 std::pair<CharUnits, CharUnits> TypeInfo;
1448 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1450 TypeInfo = getContext().getTypeInfoInChars(Ty);
1452 if (alignment.isZero())
1453 alignment = TypeInfo.second;
1455 llvm::Value *SizeVal = nullptr;
1456 if (TypeInfo.first.isZero()) {
1457 // But note that getTypeInfo returns 0 for a VLA.
1458 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1459 getContext().getAsArrayType(Ty))) {
1461 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1462 TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
1463 std::pair<CharUnits, CharUnits> LastElementTypeInfo;
1465 LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1466 assert(!TypeInfo.first.isZero());
1467 SizeVal = Builder.CreateNUWMul(
1469 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1470 if (!isAssignment) {
1471 SizeVal = Builder.CreateNUWSub(
1473 llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1474 SizeVal = Builder.CreateNUWAdd(
1475 SizeVal, llvm::ConstantInt::get(
1476 SizeTy, LastElementTypeInfo.first.getQuantity()));
1481 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1484 // FIXME: If we have a volatile struct, the optimizer can remove what might
1485 // appear to be `extra' memory ops:
1487 // volatile struct { int i; } a, b;
1494 // we need to use a different call here. We use isVolatile to indicate when
1495 // either the source or the destination is volatile.
1497 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1499 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1500 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1502 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1504 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1505 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1507 // Don't do any of the memmove_collectable tests if GC isn't set.
1508 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1510 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1511 RecordDecl *Record = RecordTy->getDecl();
1512 if (Record->hasObjectMember()) {
1513 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1517 } else if (Ty->isArrayType()) {
1518 QualType BaseType = getContext().getBaseElementType(Ty);
1519 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1520 if (RecordTy->getDecl()->hasObjectMember()) {
1521 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1528 // Determine the metadata to describe the position of any padding in this
1529 // memcpy, as well as the TBAA tags for the members of the struct, in case
1530 // the optimizer wishes to expand it in to scalar memory operations.
1531 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
1533 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, alignment.getQuantity(),
1534 isVolatile, /*TBAATag=*/nullptr, TBAAStructTag);