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 "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 using namespace clang;
25 using namespace CodeGen;
27 //===----------------------------------------------------------------------===//
28 // Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
38 ReturnValueSlot getReturnValueSlot() const {
39 // If the destination slot requires garbage collection, we can't
40 // use the real return value slot, because we have to use the GC
42 if (Dest.requiresGCollection()) return ReturnValueSlot();
44 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
47 AggValueSlot EnsureSlot(QualType T) {
48 if (!Dest.isIgnored()) return Dest;
49 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
53 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
55 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
56 IgnoreResult(ignore) {
59 //===--------------------------------------------------------------------===//
61 //===--------------------------------------------------------------------===//
63 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
64 /// represents a value lvalue, this method emits the address of the lvalue,
65 /// then loads the result into DestPtr.
66 void EmitAggLoadOfLValue(const Expr *E);
68 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
72 void EmitGCMove(const Expr *E, RValue Src);
74 bool TypeRequiresGCollection(QualType T);
76 //===--------------------------------------------------------------------===//
78 //===--------------------------------------------------------------------===//
80 void VisitStmt(Stmt *S) {
81 CGF.ErrorUnsupported(S, "aggregate expression");
83 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
84 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
85 Visit(GE->getResultExpr());
87 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
90 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
91 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
92 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
93 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
94 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
95 EmitAggLoadOfLValue(E);
97 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
98 EmitAggLoadOfLValue(E);
100 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
101 EmitAggLoadOfLValue(E);
103 void VisitPredefinedExpr(const PredefinedExpr *E) {
104 EmitAggLoadOfLValue(E);
108 void VisitCastExpr(CastExpr *E);
109 void VisitCallExpr(const CallExpr *E);
110 void VisitStmtExpr(const StmtExpr *E);
111 void VisitBinaryOperator(const BinaryOperator *BO);
112 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
113 void VisitBinAssign(const BinaryOperator *E);
114 void VisitBinComma(const BinaryOperator *E);
116 void VisitObjCMessageExpr(ObjCMessageExpr *E);
117 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
118 EmitAggLoadOfLValue(E);
120 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
122 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
123 void VisitChooseExpr(const ChooseExpr *CE);
124 void VisitInitListExpr(InitListExpr *E);
125 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
126 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
127 Visit(DAE->getExpr());
129 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
130 void VisitCXXConstructExpr(const CXXConstructExpr *E);
131 void VisitExprWithCleanups(ExprWithCleanups *E);
132 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
133 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
135 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
137 void VisitVAArgExpr(VAArgExpr *E);
139 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
140 void EmitNullInitializationToLValue(LValue Address, QualType T);
141 // case Expr::ChooseExprClass:
142 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
144 } // end anonymous namespace.
146 //===----------------------------------------------------------------------===//
148 //===----------------------------------------------------------------------===//
150 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
151 /// represents a value lvalue, this method emits the address of the lvalue,
152 /// then loads the result into DestPtr.
153 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
154 LValue LV = CGF.EmitLValue(E);
155 EmitFinalDestCopy(E, LV);
158 /// \brief True if the given aggregate type requires special GC API calls.
159 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
160 // Only record types have members that might require garbage collection.
161 const RecordType *RecordTy = T->getAs<RecordType>();
162 if (!RecordTy) return false;
164 // Don't mess with non-trivial C++ types.
165 RecordDecl *Record = RecordTy->getDecl();
166 if (isa<CXXRecordDecl>(Record) &&
167 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
168 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
171 // Check whether the type has an object member.
172 return Record->hasObjectMember();
175 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
177 /// The idea is that you do something like this:
178 /// RValue Result = EmitSomething(..., getReturnValueSlot());
179 /// EmitGCMove(E, Result);
180 /// If GC doesn't interfere, this will cause the result to be emitted
181 /// directly into the return value slot. If GC does interfere, a final
182 /// move will be performed.
183 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
184 if (Dest.requiresGCollection()) {
185 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
186 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
187 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
188 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
189 Src.getAggregateAddr(),
194 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
195 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
196 assert(Src.isAggregate() && "value must be aggregate value!");
198 // If Dest is ignored, then we're evaluating an aggregate expression
199 // in a context (like an expression statement) that doesn't care
200 // about the result. C says that an lvalue-to-rvalue conversion is
201 // performed in these cases; C++ says that it is not. In either
202 // case, we don't actually need to do anything unless the value is
204 if (Dest.isIgnored()) {
205 if (!Src.isVolatileQualified() ||
206 CGF.CGM.getLangOptions().CPlusPlus ||
207 (IgnoreResult && Ignore))
210 // If the source is volatile, we must read from it; to do that, we need
211 // some place to put it.
212 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
215 if (Dest.requiresGCollection()) {
216 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
217 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
218 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
219 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
221 Src.getAggregateAddr(),
225 // If the result of the assignment is used, copy the LHS there also.
226 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
227 // from the source as well, as we can't eliminate it if either operand
228 // is volatile, unless copy has volatile for both source and destination..
229 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
230 Dest.isVolatile()|Src.isVolatileQualified());
233 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
234 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
235 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
237 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
238 Src.isVolatileQualified()),
242 //===----------------------------------------------------------------------===//
244 //===----------------------------------------------------------------------===//
246 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
247 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
250 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
251 switch (E->getCastKind()) {
253 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
254 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
255 // FIXME: Do we also need to handle property references here?
257 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
259 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
261 if (!Dest.isIgnored())
262 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
267 if (Dest.isIgnored()) break;
269 // GCC union extension
270 QualType Ty = E->getSubExpr()->getType();
271 QualType PtrTy = CGF.getContext().getPointerType(Ty);
272 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
273 CGF.ConvertType(PtrTy));
274 EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
279 case CK_DerivedToBase:
280 case CK_BaseToDerived:
281 case CK_UncheckedDerivedToBase: {
282 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
283 "should have been unpacked before we got here");
287 case CK_GetObjCProperty: {
288 LValue LV = CGF.EmitLValue(E->getSubExpr());
289 assert(LV.isPropertyRef());
290 RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
295 case CK_LValueToRValue: // hope for downstream optimization
297 case CK_UserDefinedConversion:
298 case CK_ConstructorConversion:
299 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
301 "Implicit cast types must be compatible");
302 Visit(E->getSubExpr());
305 case CK_LValueBitCast:
306 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
311 case CK_ArrayToPointerDecay:
312 case CK_FunctionToPointerDecay:
313 case CK_NullToPointer:
314 case CK_NullToMemberPointer:
315 case CK_BaseToDerivedMemberPointer:
316 case CK_DerivedToBaseMemberPointer:
317 case CK_MemberPointerToBoolean:
318 case CK_IntegralToPointer:
319 case CK_PointerToIntegral:
320 case CK_PointerToBoolean:
323 case CK_IntegralCast:
324 case CK_IntegralToBoolean:
325 case CK_IntegralToFloating:
326 case CK_FloatingToIntegral:
327 case CK_FloatingToBoolean:
328 case CK_FloatingCast:
329 case CK_AnyPointerToObjCPointerCast:
330 case CK_AnyPointerToBlockPointerCast:
331 case CK_ObjCObjectLValueCast:
332 case CK_FloatingRealToComplex:
333 case CK_FloatingComplexToReal:
334 case CK_FloatingComplexToBoolean:
335 case CK_FloatingComplexCast:
336 case CK_FloatingComplexToIntegralComplex:
337 case CK_IntegralRealToComplex:
338 case CK_IntegralComplexToReal:
339 case CK_IntegralComplexToBoolean:
340 case CK_IntegralComplexCast:
341 case CK_IntegralComplexToFloatingComplex:
342 llvm_unreachable("cast kind invalid for aggregate types");
346 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
347 if (E->getCallReturnType()->isReferenceType()) {
348 EmitAggLoadOfLValue(E);
352 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
356 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
357 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
361 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
362 llvm_unreachable("direct property access not surrounded by "
363 "lvalue-to-rvalue cast");
366 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
367 CGF.EmitIgnoredExpr(E->getLHS());
371 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
372 CodeGenFunction::StmtExprEvaluation eval(CGF);
373 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
376 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
377 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
378 VisitPointerToDataMemberBinaryOperator(E);
380 CGF.ErrorUnsupported(E, "aggregate binary expression");
383 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
384 const BinaryOperator *E) {
385 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
386 EmitFinalDestCopy(E, LV);
389 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
390 // For an assignment to work, the value on the right has
391 // to be compatible with the value on the left.
392 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
393 E->getRHS()->getType())
394 && "Invalid assignment");
396 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
397 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
398 if (VD->hasAttr<BlocksAttr>() &&
399 E->getRHS()->HasSideEffects(CGF.getContext())) {
400 // When __block variable on LHS, the RHS must be evaluated first
401 // as it may change the 'forwarding' field via call to Block_copy.
402 LValue RHS = CGF.EmitLValue(E->getRHS());
403 LValue LHS = CGF.EmitLValue(E->getLHS());
404 bool GCollection = false;
405 if (CGF.getContext().getLangOptions().getGCMode())
406 GCollection = TypeRequiresGCollection(E->getLHS()->getType());
407 Dest = AggValueSlot::forLValue(LHS, true, GCollection);
408 EmitFinalDestCopy(E, RHS, true);
412 LValue LHS = CGF.EmitLValue(E->getLHS());
414 // We have to special case property setters, otherwise we must have
415 // a simple lvalue (no aggregates inside vectors, bitfields).
416 if (LHS.isPropertyRef()) {
417 const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
418 QualType ArgType = RE->getSetterArgType();
420 if (ArgType->isReferenceType())
421 Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
423 AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
424 CGF.EmitAggExpr(E->getRHS(), Slot);
425 Src = Slot.asRValue();
427 CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
429 bool GCollection = false;
430 if (CGF.getContext().getLangOptions().getGCMode())
431 GCollection = TypeRequiresGCollection(E->getLHS()->getType());
433 // Codegen the RHS so that it stores directly into the LHS.
434 AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
436 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
437 EmitFinalDestCopy(E, LHS, true);
441 void AggExprEmitter::
442 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
443 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
444 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
445 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
447 // Bind the common expression if necessary.
448 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
450 CodeGenFunction::ConditionalEvaluation eval(CGF);
451 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
453 // Save whether the destination's lifetime is externally managed.
454 bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
457 CGF.EmitBlock(LHSBlock);
458 Visit(E->getTrueExpr());
461 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
462 CGF.Builder.CreateBr(ContBlock);
464 // If the result of an agg expression is unused, then the emission
465 // of the LHS might need to create a destination slot. That's fine
466 // with us, and we can safely emit the RHS into the same slot, but
467 // we shouldn't claim that its lifetime is externally managed.
468 Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
471 CGF.EmitBlock(RHSBlock);
472 Visit(E->getFalseExpr());
475 CGF.EmitBlock(ContBlock);
478 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
479 Visit(CE->getChosenSubExpr(CGF.getContext()));
482 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
483 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
484 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
487 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
491 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
494 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
495 // Ensure that we have a slot, but if we already do, remember
496 // whether its lifetime was externally managed.
497 bool WasManaged = Dest.isLifetimeExternallyManaged();
498 Dest = EnsureSlot(E->getType());
499 Dest.setLifetimeExternallyManaged();
501 Visit(E->getSubExpr());
503 // Set up the temporary's destructor if its lifetime wasn't already
506 CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
510 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
511 AggValueSlot Slot = EnsureSlot(E->getType());
512 CGF.EmitCXXConstructExpr(E, Slot);
515 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
516 CGF.EmitExprWithCleanups(E, Dest);
519 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
520 QualType T = E->getType();
521 AggValueSlot Slot = EnsureSlot(T);
522 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
525 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
526 QualType T = E->getType();
527 AggValueSlot Slot = EnsureSlot(T);
528 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T);
531 /// isSimpleZero - If emitting this value will obviously just cause a store of
532 /// zero to memory, return true. This can return false if uncertain, so it just
533 /// handles simple cases.
534 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
535 E = E->IgnoreParens();
538 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
539 return IL->getValue() == 0;
541 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
542 return FL->getValue().isPosZero();
544 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
545 CGF.getTypes().isZeroInitializable(E->getType()))
547 // (int*)0 - Null pointer expressions.
548 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
549 return ICE->getCastKind() == CK_NullToPointer;
551 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
552 return CL->getValue() == 0;
554 // Otherwise, hard case: conservatively return false.
560 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
561 // FIXME: Ignore result?
562 // FIXME: Are initializers affected by volatile?
563 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
564 // Storing "i32 0" to a zero'd memory location is a noop.
565 } else if (isa<ImplicitValueInitExpr>(E)) {
566 EmitNullInitializationToLValue(LV, T);
567 } else if (T->isReferenceType()) {
568 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
569 CGF.EmitStoreThroughLValue(RV, LV, T);
570 } else if (T->isAnyComplexType()) {
571 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
572 } else if (CGF.hasAggregateLLVMType(T)) {
573 CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true,
574 false, Dest.isZeroed()));
576 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, T);
580 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
581 // If the destination slot is already zeroed out before the aggregate is
582 // copied into it, we don't have to emit any zeros here.
583 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(T))
586 if (!CGF.hasAggregateLLVMType(T)) {
587 // For non-aggregates, we can store zero
588 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
589 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
591 // There's a potential optimization opportunity in combining
592 // memsets; that would be easy for arrays, but relatively
593 // difficult for structures with the current code.
594 CGF.EmitNullInitialization(LV.getAddress(), T);
598 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
600 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
601 // (Length of globals? Chunks of zeroed-out space?).
603 // If we can, prefer a copy from a global; this is a lot less code for long
604 // globals, and it's easier for the current optimizers to analyze.
605 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
606 llvm::GlobalVariable* GV =
607 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
608 llvm::GlobalValue::InternalLinkage, C, "");
609 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
613 if (E->hadArrayRangeDesignator())
614 CGF.ErrorUnsupported(E, "GNU array range designator extension");
616 llvm::Value *DestPtr = Dest.getAddr();
618 // Handle initialization of an array.
619 if (E->getType()->isArrayType()) {
620 const llvm::PointerType *APType =
621 cast<llvm::PointerType>(DestPtr->getType());
622 const llvm::ArrayType *AType =
623 cast<llvm::ArrayType>(APType->getElementType());
625 uint64_t NumInitElements = E->getNumInits();
627 if (E->getNumInits() > 0) {
628 QualType T1 = E->getType();
629 QualType T2 = E->getInit(0)->getType();
630 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
631 EmitAggLoadOfLValue(E->getInit(0));
636 uint64_t NumArrayElements = AType->getNumElements();
637 QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
638 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
640 bool hasNonTrivialCXXConstructor = false;
641 if (CGF.getContext().getLangOptions().CPlusPlus)
642 if (const RecordType *RT = CGF.getContext()
643 .getBaseElementType(ElementType)->getAs<RecordType>()) {
644 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
645 hasNonTrivialCXXConstructor = !RD->hasTrivialConstructor();
648 // FIXME: were we intentionally ignoring address spaces and GC attributes?
650 for (uint64_t i = 0; i != NumArrayElements; ++i) {
651 // If we're done emitting initializers and the destination is known-zeroed
653 if (i == NumInitElements &&
655 CGF.getTypes().isZeroInitializable(ElementType) &&
656 !hasNonTrivialCXXConstructor)
659 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
660 LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
662 if (i < NumInitElements)
663 EmitInitializationToLValue(E->getInit(i), LV, ElementType);
664 else if (Expr *filler = E->getArrayFiller())
665 EmitInitializationToLValue(filler, LV, ElementType);
667 EmitNullInitializationToLValue(LV, ElementType);
669 // If the GEP didn't get used because of a dead zero init or something
670 // else, clean it up for -O0 builds and general tidiness.
671 if (llvm::GetElementPtrInst *GEP =
672 dyn_cast<llvm::GetElementPtrInst>(NextVal))
673 if (GEP->use_empty())
674 GEP->eraseFromParent();
679 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
681 // Do struct initialization; this code just sets each individual member
682 // to the approprate value. This makes bitfield support automatic;
683 // the disadvantage is that the generated code is more difficult for
684 // the optimizer, especially with bitfields.
685 unsigned NumInitElements = E->getNumInits();
686 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
688 if (E->getType()->isUnionType()) {
689 // Only initialize one field of a union. The field itself is
690 // specified by the initializer list.
691 if (!E->getInitializedFieldInUnion()) {
692 // Empty union; we have nothing to do.
695 // Make sure that it's really an empty and not a failure of
696 // semantic analysis.
697 for (RecordDecl::field_iterator Field = SD->field_begin(),
698 FieldEnd = SD->field_end();
699 Field != FieldEnd; ++Field)
700 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
706 FieldDecl *Field = E->getInitializedFieldInUnion();
708 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
709 if (NumInitElements) {
710 // Store the initializer into the field
711 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
713 // Default-initialize to null.
714 EmitNullInitializationToLValue(FieldLoc, Field->getType());
720 // Here we iterate over the fields; this makes it simpler to both
721 // default-initialize fields and skip over unnamed fields.
722 unsigned CurInitVal = 0;
723 for (RecordDecl::field_iterator Field = SD->field_begin(),
724 FieldEnd = SD->field_end();
725 Field != FieldEnd; ++Field) {
726 // We're done once we hit the flexible array member
727 if (Field->getType()->isIncompleteArrayType())
730 if (Field->isUnnamedBitfield())
733 // Don't emit GEP before a noop store of zero.
734 if (CurInitVal == NumInitElements && Dest.isZeroed() &&
735 CGF.getTypes().isZeroInitializable(E->getType()))
739 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
740 // We never generate write-barries for initialized fields.
741 FieldLoc.setNonGC(true);
743 if (CurInitVal < NumInitElements) {
744 // Store the initializer into the field.
745 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
748 // We're out of initalizers; default-initialize to null
749 EmitNullInitializationToLValue(FieldLoc, Field->getType());
752 // If the GEP didn't get used because of a dead zero init or something
753 // else, clean it up for -O0 builds and general tidiness.
754 if (FieldLoc.isSimple())
755 if (llvm::GetElementPtrInst *GEP =
756 dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress()))
757 if (GEP->use_empty())
758 GEP->eraseFromParent();
762 //===----------------------------------------------------------------------===//
763 // Entry Points into this File
764 //===----------------------------------------------------------------------===//
766 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
767 /// non-zero bytes that will be stored when outputting the initializer for the
768 /// specified initializer expression.
769 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
770 E = E->IgnoreParens();
772 // 0 and 0.0 won't require any non-zero stores!
773 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
775 // If this is an initlist expr, sum up the size of sizes of the (present)
776 // elements. If this is something weird, assume the whole thing is non-zero.
777 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
778 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
779 return CGF.getContext().getTypeSizeInChars(E->getType());
781 // InitListExprs for structs have to be handled carefully. If there are
782 // reference members, we need to consider the size of the reference, not the
783 // referencee. InitListExprs for unions and arrays can't have references.
784 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
785 if (!RT->isUnionType()) {
786 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
787 CharUnits NumNonZeroBytes = CharUnits::Zero();
789 unsigned ILEElement = 0;
790 for (RecordDecl::field_iterator Field = SD->field_begin(),
791 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
792 // We're done once we hit the flexible array member or run out of
793 // InitListExpr elements.
794 if (Field->getType()->isIncompleteArrayType() ||
795 ILEElement == ILE->getNumInits())
797 if (Field->isUnnamedBitfield())
800 const Expr *E = ILE->getInit(ILEElement++);
802 // Reference values are always non-null and have the width of a pointer.
803 if (Field->getType()->isReferenceType())
804 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
805 CGF.getContext().Target.getPointerWidth(0));
807 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
810 return NumNonZeroBytes;
815 CharUnits NumNonZeroBytes = CharUnits::Zero();
816 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
817 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
818 return NumNonZeroBytes;
821 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
822 /// zeros in it, emit a memset and avoid storing the individual zeros.
824 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
825 CodeGenFunction &CGF) {
826 // If the slot is already known to be zeroed, nothing to do. Don't mess with
828 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
830 // C++ objects with a user-declared constructor don't need zero'ing.
831 if (CGF.getContext().getLangOptions().CPlusPlus)
832 if (const RecordType *RT = CGF.getContext()
833 .getBaseElementType(E->getType())->getAs<RecordType>()) {
834 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
835 if (RD->hasUserDeclaredConstructor())
839 // If the type is 16-bytes or smaller, prefer individual stores over memset.
840 std::pair<CharUnits, CharUnits> TypeInfo =
841 CGF.getContext().getTypeInfoInChars(E->getType());
842 if (TypeInfo.first <= CharUnits::fromQuantity(16))
845 // Check to see if over 3/4 of the initializer are known to be zero. If so,
846 // we prefer to emit memset + individual stores for the rest.
847 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
848 if (NumNonZeroBytes*4 > TypeInfo.first)
851 // Okay, it seems like a good idea to use an initial memset, emit the call.
852 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
853 CharUnits Align = TypeInfo.second;
855 llvm::Value *Loc = Slot.getAddr();
856 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
858 Loc = CGF.Builder.CreateBitCast(Loc, BP);
859 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
860 Align.getQuantity(), false);
862 // Tell the AggExprEmitter that the slot is known zero.
869 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
870 /// type. The result is computed into DestPtr. Note that if DestPtr is null,
871 /// the value of the aggregate expression is not needed. If VolatileDest is
872 /// true, DestPtr cannot be 0.
874 /// \param IsInitializer - true if this evaluation is initializing an
875 /// object whose lifetime is already being managed.
877 // FIXME: Take Qualifiers object.
878 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
880 assert(E && hasAggregateLLVMType(E->getType()) &&
881 "Invalid aggregate expression to emit");
882 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
883 "slot has bits but no address");
885 // Optimize the slot if possible.
886 CheckAggExprForMemSetUse(Slot, E, *this);
888 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
891 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
892 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
893 llvm::Value *Temp = CreateMemTemp(E->getType());
894 LValue LV = MakeAddrLValue(Temp, E->getType());
895 EmitAggExpr(E, AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false));
899 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
900 llvm::Value *SrcPtr, QualType Ty,
902 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
904 if (getContext().getLangOptions().CPlusPlus) {
905 if (const RecordType *RT = Ty->getAs<RecordType>()) {
906 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
907 assert((Record->hasTrivialCopyConstructor() ||
908 Record->hasTrivialCopyAssignment()) &&
909 "Trying to aggregate-copy a type without a trivial copy "
910 "constructor or assignment operator");
911 // Ignore empty classes in C++.
912 if (Record->isEmpty())
917 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
918 // C99 6.5.16.1p3, which states "If the value being stored in an object is
919 // read from another object that overlaps in anyway the storage of the first
920 // object, then the overlap shall be exact and the two objects shall have
921 // qualified or unqualified versions of a compatible type."
923 // memcpy is not defined if the source and destination pointers are exactly
924 // equal, but other compilers do this optimization, and almost every memcpy
925 // implementation handles this case safely. If there is a libc that does not
926 // safely handle this, we can add a target hook.
928 // Get size and alignment info for this aggregate.
929 std::pair<CharUnits, CharUnits> TypeInfo =
930 getContext().getTypeInfoInChars(Ty);
932 // FIXME: Handle variable sized types.
934 // FIXME: If we have a volatile struct, the optimizer can remove what might
935 // appear to be `extra' memory ops:
937 // volatile struct { int i; } a, b;
944 // we need to use a different call here. We use isVolatile to indicate when
945 // either the source or the destination is volatile.
947 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
948 const llvm::Type *DBP =
949 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
950 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
952 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
953 const llvm::Type *SBP =
954 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
955 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
957 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
958 RecordDecl *Record = RecordTy->getDecl();
959 if (Record->hasObjectMember()) {
960 CharUnits size = TypeInfo.first;
961 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
962 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
963 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
967 } else if (getContext().getAsArrayType(Ty)) {
968 QualType BaseType = getContext().getBaseElementType(Ty);
969 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
970 if (RecordTy->getDecl()->hasObjectMember()) {
971 CharUnits size = TypeInfo.first;
972 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
973 llvm::Value *SizeVal =
974 llvm::ConstantInt::get(SizeTy, size.getQuantity());
975 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
982 Builder.CreateMemCpy(DestPtr, SrcPtr,
983 llvm::ConstantInt::get(IntPtrTy,
984 TypeInfo.first.getQuantity()),
985 TypeInfo.second.getQuantity(), isVolatile);