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> {
39 bool RequiresGCollection;
41 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
42 bool ignore, bool isinit, bool requiresGCollection)
43 : CGF(cgf), Builder(CGF.Builder),
44 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
45 IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
48 //===--------------------------------------------------------------------===//
50 //===--------------------------------------------------------------------===//
52 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
53 /// represents a value lvalue, this method emits the address of the lvalue,
54 /// then loads the result into DestPtr.
55 void EmitAggLoadOfLValue(const Expr *E);
57 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
58 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
59 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
61 //===--------------------------------------------------------------------===//
63 //===--------------------------------------------------------------------===//
65 void VisitStmt(Stmt *S) {
66 CGF.ErrorUnsupported(S, "aggregate expression");
68 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
69 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
72 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
73 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
74 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
75 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
76 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
77 EmitAggLoadOfLValue(E);
79 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
80 EmitAggLoadOfLValue(E);
82 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
83 EmitAggLoadOfLValue(E);
85 void VisitPredefinedExpr(const PredefinedExpr *E) {
86 EmitAggLoadOfLValue(E);
90 void VisitCastExpr(CastExpr *E);
91 void VisitCallExpr(const CallExpr *E);
92 void VisitStmtExpr(const StmtExpr *E);
93 void VisitBinaryOperator(const BinaryOperator *BO);
94 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
95 void VisitBinAssign(const BinaryOperator *E);
96 void VisitBinComma(const BinaryOperator *E);
97 void VisitUnaryAddrOf(const UnaryOperator *E);
99 void VisitObjCMessageExpr(ObjCMessageExpr *E);
100 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
101 EmitAggLoadOfLValue(E);
103 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
104 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
106 void VisitConditionalOperator(const ConditionalOperator *CO);
107 void VisitChooseExpr(const ChooseExpr *CE);
108 void VisitInitListExpr(InitListExpr *E);
109 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
110 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
111 Visit(DAE->getExpr());
113 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
114 void VisitCXXConstructExpr(const CXXConstructExpr *E);
115 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
116 void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
117 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
119 void VisitVAArgExpr(VAArgExpr *E);
121 void EmitInitializationToLValue(Expr *E, LValue Address);
122 void EmitNullInitializationToLValue(LValue Address, QualType T);
123 // case Expr::ChooseExprClass:
124 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
126 } // end anonymous namespace.
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
132 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
133 /// represents a value lvalue, this method emits the address of the lvalue,
134 /// then loads the result into DestPtr.
135 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
136 LValue LV = CGF.EmitLValue(E);
137 EmitFinalDestCopy(E, LV);
140 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
141 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
142 assert(Src.isAggregate() && "value must be aggregate value!");
144 // If the result is ignored, don't copy from the value.
146 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
148 // If the source is volatile, we must read from it; to do that, we need
149 // some place to put it.
150 DestPtr = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp");
153 if (RequiresGCollection) {
154 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
155 DestPtr, Src.getAggregateAddr(),
159 // If the result of the assignment is used, copy the LHS there also.
160 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
161 // from the source as well, as we can't eliminate it if either operand
162 // is volatile, unless copy has volatile for both source and destination..
163 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
164 VolatileDest|Src.isVolatileQualified());
167 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
168 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
169 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
171 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
172 Src.isVolatileQualified()),
176 //===----------------------------------------------------------------------===//
178 //===----------------------------------------------------------------------===//
180 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
181 switch (E->getCastKind()) {
182 default: assert(0 && "Unhandled cast kind!");
184 case CastExpr::CK_ToUnion: {
185 // GCC union extension
187 CGF.getContext().getPointerType(E->getSubExpr()->getType());
188 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
189 CGF.ConvertType(PtrTy));
190 EmitInitializationToLValue(E->getSubExpr(),
191 LValue::MakeAddr(CastPtr, Qualifiers()));
195 // FIXME: Remove the CK_Unknown check here.
196 case CastExpr::CK_Unknown:
197 case CastExpr::CK_NoOp:
198 case CastExpr::CK_UserDefinedConversion:
199 case CastExpr::CK_ConstructorConversion:
200 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
202 "Implicit cast types must be compatible");
203 Visit(E->getSubExpr());
206 case CastExpr::CK_NullToMemberPointer: {
207 const llvm::Type *PtrDiffTy =
208 CGF.ConvertType(CGF.getContext().getPointerDiffType());
210 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy);
211 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr");
212 Builder.CreateStore(NullValue, Ptr, VolatileDest);
214 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj");
215 Builder.CreateStore(NullValue, Adj, VolatileDest);
220 case CastExpr::CK_BitCast: {
221 // This must be a member function pointer cast.
222 Visit(E->getSubExpr());
226 case CastExpr::CK_DerivedToBaseMemberPointer:
227 case CastExpr::CK_BaseToDerivedMemberPointer: {
228 QualType SrcType = E->getSubExpr()->getType();
230 llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType),
232 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified());
234 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr");
235 SrcPtr = Builder.CreateLoad(SrcPtr);
237 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj");
238 SrcAdj = Builder.CreateLoad(SrcAdj);
240 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
241 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest);
243 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
245 // Now See if we need to update the adjustment.
246 const CXXRecordDecl *BaseDecl =
247 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()->
248 getClass()->getAs<RecordType>()->getDecl());
249 const CXXRecordDecl *DerivedDecl =
250 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
251 getClass()->getAs<RecordType>()->getDecl());
252 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
253 std::swap(DerivedDecl, BaseDecl);
255 llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl);
257 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
258 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj");
260 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj");
263 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest);
269 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
270 if (E->getCallReturnType()->isReferenceType()) {
271 EmitAggLoadOfLValue(E);
275 // If the struct doesn't require GC, we can just pass the destination
276 // directly to EmitCall.
277 if (!RequiresGCollection) {
278 CGF.EmitCallExpr(E, ReturnValueSlot(DestPtr, VolatileDest));
282 RValue RV = CGF.EmitCallExpr(E);
283 EmitFinalDestCopy(E, RV);
286 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
287 RValue RV = CGF.EmitObjCMessageExpr(E);
288 EmitFinalDestCopy(E, RV);
291 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
292 RValue RV = CGF.EmitObjCPropertyGet(E);
293 EmitFinalDestCopy(E, RV);
296 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
297 ObjCImplicitSetterGetterRefExpr *E) {
298 RValue RV = CGF.EmitObjCPropertyGet(E);
299 EmitFinalDestCopy(E, RV);
302 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
303 CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
304 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
305 /*IgnoreResult=*/false, IsInitializer);
308 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) {
309 // We have a member function pointer.
310 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
312 assert(MPT->getPointeeType()->isFunctionProtoType() &&
313 "Unexpected member pointer type!");
315 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr());
316 const CXXMethodDecl *MD =
317 cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl();
319 const llvm::Type *PtrDiffTy =
320 CGF.ConvertType(CGF.getContext().getPointerDiffType());
322 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr");
323 llvm::Value *FuncPtr;
325 if (MD->isVirtual()) {
327 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD);
329 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1);
331 FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD),
334 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest);
336 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj");
338 // The adjustment will always be 0.
339 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr,
343 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
344 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
347 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
348 if (E->getOpcode() == BinaryOperator::PtrMemD ||
349 E->getOpcode() == BinaryOperator::PtrMemI)
350 VisitPointerToDataMemberBinaryOperator(E);
352 CGF.ErrorUnsupported(E, "aggregate binary expression");
355 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
356 const BinaryOperator *E) {
357 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
358 EmitFinalDestCopy(E, LV);
361 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
362 // For an assignment to work, the value on the right has
363 // to be compatible with the value on the left.
364 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
365 E->getRHS()->getType())
366 && "Invalid assignment");
367 LValue LHS = CGF.EmitLValue(E->getLHS());
369 // We have to special case property setters, otherwise we must have
370 // a simple lvalue (no aggregates inside vectors, bitfields).
371 if (LHS.isPropertyRef()) {
372 llvm::Value *AggLoc = DestPtr;
374 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
375 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
376 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
377 RValue::getAggregate(AggLoc, VolatileDest));
378 } else if (LHS.isKVCRef()) {
379 llvm::Value *AggLoc = DestPtr;
381 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
382 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
383 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
384 RValue::getAggregate(AggLoc, VolatileDest));
386 bool RequiresGCollection = false;
387 if (CGF.getContext().getLangOptions().NeXTRuntime) {
388 QualType LHSTy = E->getLHS()->getType();
389 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>())
390 RequiresGCollection = FDTTy->getDecl()->hasObjectMember();
392 // Codegen the RHS so that it stores directly into the LHS.
393 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
394 false, false, RequiresGCollection);
395 EmitFinalDestCopy(E, LHS, true);
399 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
401 CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
405 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
406 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
407 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
409 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
411 CGF.StartConditionalBranch();
412 CGF.EmitBlock(LHSBlock);
414 // Handle the GNU extension for missing LHS.
415 assert(E->getLHS() && "Must have LHS for aggregate value");
418 CGF.FinishConditionalBranch();
419 CGF.EmitBranch(ContBlock);
421 CGF.StartConditionalBranch();
422 CGF.EmitBlock(RHSBlock);
425 CGF.FinishConditionalBranch();
426 CGF.EmitBranch(ContBlock);
428 CGF.EmitBlock(ContBlock);
431 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
432 Visit(CE->getChosenSubExpr(CGF.getContext()));
435 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
436 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
437 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
440 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
444 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers()));
447 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
448 llvm::Value *Val = DestPtr;
451 // Create a temporary variable.
452 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
455 CGF.EmitAggExpr(E->getSubExpr(), Val, false);
457 Visit(E->getSubExpr());
459 // Don't make this a live temporary if we're emitting an initializer expr.
461 CGF.PushCXXTemporary(E->getTemporary(), Val);
465 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
466 llvm::Value *Val = DestPtr;
469 // Create a temporary variable.
470 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
473 if (E->requiresZeroInitialization())
474 EmitNullInitializationToLValue(LValue::MakeAddr(Val,
475 // FIXME: Qualifiers()?
476 E->getType().getQualifiers()),
479 CGF.EmitCXXConstructExpr(Val, E);
482 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
483 llvm::Value *Val = DestPtr;
486 // Create a temporary variable.
487 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
489 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
492 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
493 llvm::Value *Val = DestPtr;
496 // Create a temporary variable.
497 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
499 LValue LV = LValue::MakeAddr(Val, Qualifiers());
500 EmitNullInitializationToLValue(LV, E->getType());
503 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
504 llvm::Value *Val = DestPtr;
507 // Create a temporary variable.
508 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp");
510 LValue LV = LValue::MakeAddr(Val, Qualifiers());
511 EmitNullInitializationToLValue(LV, E->getType());
514 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
515 // FIXME: Ignore result?
516 // FIXME: Are initializers affected by volatile?
517 if (isa<ImplicitValueInitExpr>(E)) {
518 EmitNullInitializationToLValue(LV, E->getType());
519 } else if (E->getType()->isComplexType()) {
520 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
521 } else if (CGF.hasAggregateLLVMType(E->getType())) {
522 CGF.EmitAnyExpr(E, LV.getAddress(), false);
524 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
528 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
529 if (!CGF.hasAggregateLLVMType(T)) {
530 // For non-aggregates, we can store zero
531 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
532 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
534 // Otherwise, just memset the whole thing to zero. This is legal
535 // because in LLVM, all default initializers are guaranteed to have a
536 // bit pattern of all zeros.
537 // FIXME: That isn't true for member pointers!
538 // There's a potential optimization opportunity in combining
539 // memsets; that would be easy for arrays, but relatively
540 // difficult for structures with the current code.
541 CGF.EmitMemSetToZero(LV.getAddress(), T);
545 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
547 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
548 // (Length of globals? Chunks of zeroed-out space?).
550 // If we can, prefer a copy from a global; this is a lot less code for long
551 // globals, and it's easier for the current optimizers to analyze.
552 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
553 llvm::GlobalVariable* GV =
554 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
555 llvm::GlobalValue::InternalLinkage, C, "");
556 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers()));
560 if (E->hadArrayRangeDesignator()) {
561 CGF.ErrorUnsupported(E, "GNU array range designator extension");
564 // Handle initialization of an array.
565 if (E->getType()->isArrayType()) {
566 const llvm::PointerType *APType =
567 cast<llvm::PointerType>(DestPtr->getType());
568 const llvm::ArrayType *AType =
569 cast<llvm::ArrayType>(APType->getElementType());
571 uint64_t NumInitElements = E->getNumInits();
573 if (E->getNumInits() > 0) {
574 QualType T1 = E->getType();
575 QualType T2 = E->getInit(0)->getType();
576 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
577 EmitAggLoadOfLValue(E->getInit(0));
582 uint64_t NumArrayElements = AType->getNumElements();
583 QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
584 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
586 // FIXME: were we intentionally ignoring address spaces and GC attributes?
587 Qualifiers Quals = CGF.MakeQualifiers(ElementType);
589 for (uint64_t i = 0; i != NumArrayElements; ++i) {
590 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
591 if (i < NumInitElements)
592 EmitInitializationToLValue(E->getInit(i),
593 LValue::MakeAddr(NextVal, Quals));
595 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals),
601 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
603 // Do struct initialization; this code just sets each individual member
604 // to the approprate value. This makes bitfield support automatic;
605 // the disadvantage is that the generated code is more difficult for
606 // the optimizer, especially with bitfields.
607 unsigned NumInitElements = E->getNumInits();
608 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
609 unsigned CurInitVal = 0;
611 if (E->getType()->isUnionType()) {
612 // Only initialize one field of a union. The field itself is
613 // specified by the initializer list.
614 if (!E->getInitializedFieldInUnion()) {
615 // Empty union; we have nothing to do.
618 // Make sure that it's really an empty and not a failure of
619 // semantic analysis.
620 for (RecordDecl::field_iterator Field = SD->field_begin(),
621 FieldEnd = SD->field_end();
622 Field != FieldEnd; ++Field)
623 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
629 FieldDecl *Field = E->getInitializedFieldInUnion();
630 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0);
632 if (NumInitElements) {
633 // Store the initializer into the field
634 EmitInitializationToLValue(E->getInit(0), FieldLoc);
636 // Default-initialize to null
637 EmitNullInitializationToLValue(FieldLoc, Field->getType());
643 // Here we iterate over the fields; this makes it simpler to both
644 // default-initialize fields and skip over unnamed fields.
645 for (RecordDecl::field_iterator Field = SD->field_begin(),
646 FieldEnd = SD->field_end();
647 Field != FieldEnd; ++Field) {
648 // We're done once we hit the flexible array member
649 if (Field->getType()->isIncompleteArrayType())
652 if (Field->isUnnamedBitfield())
656 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0);
657 // We never generate write-barries for initialized fields.
658 LValue::SetObjCNonGC(FieldLoc, true);
659 if (CurInitVal < NumInitElements) {
660 // Store the initializer into the field
661 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
663 // We're out of initalizers; default-initialize to null
664 EmitNullInitializationToLValue(FieldLoc, Field->getType());
669 //===----------------------------------------------------------------------===//
670 // Entry Points into this File
671 //===----------------------------------------------------------------------===//
673 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
674 /// type. The result is computed into DestPtr. Note that if DestPtr is null,
675 /// the value of the aggregate expression is not needed. If VolatileDest is
676 /// true, DestPtr cannot be 0.
677 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
678 bool VolatileDest, bool IgnoreResult,
680 bool RequiresGCollection) {
681 assert(E && hasAggregateLLVMType(E->getType()) &&
682 "Invalid aggregate expression to emit");
683 assert ((DestPtr != 0 || VolatileDest == false)
684 && "volatile aggregate can't be 0");
686 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
688 .Visit(const_cast<Expr*>(E));
691 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
692 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
694 EmitMemSetToZero(DestPtr, Ty);
697 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
698 llvm::Value *SrcPtr, QualType Ty,
700 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
702 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
703 // C99 6.5.16.1p3, which states "If the value being stored in an object is
704 // read from another object that overlaps in anyway the storage of the first
705 // object, then the overlap shall be exact and the two objects shall have
706 // qualified or unqualified versions of a compatible type."
708 // memcpy is not defined if the source and destination pointers are exactly
709 // equal, but other compilers do this optimization, and almost every memcpy
710 // implementation handles this case safely. If there is a libc that does not
711 // safely handle this, we can add a target hook.
712 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
713 if (DestPtr->getType() != BP)
714 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
715 if (SrcPtr->getType() != BP)
716 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
718 // Get size and alignment info for this aggregate.
719 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
721 // FIXME: Handle variable sized types.
722 const llvm::Type *IntPtr =
723 llvm::IntegerType::get(VMContext, LLVMPointerWidth);
725 // FIXME: If we have a volatile struct, the optimizer can remove what might
726 // appear to be `extra' memory ops:
728 // volatile struct { int i; } a, b;
735 // we need to use a differnt call here. We use isVolatile to indicate when
736 // either the source or the destination is volatile.
737 Builder.CreateCall4(CGM.getMemCpyFn(),
739 // TypeInfo.first describes size in bits.
740 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
741 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),