CGExprAgg.cpp revision ef072fd2f3347cfd857d6eb787b245b950771430
1//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Aggregate Expr nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 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" 24using namespace clang; 25using namespace CodeGen; 26 27//===----------------------------------------------------------------------===// 28// Aggregate Expression Emitter 29//===----------------------------------------------------------------------===// 30 31namespace { 32class AggExprEmitter : public StmtVisitor<AggExprEmitter> { 33 CodeGenFunction &CGF; 34 CGBuilderTy &Builder; 35 llvm::Value *DestPtr; 36 bool VolatileDest; 37 bool IgnoreResult; 38 bool IsInitializer; 39 bool RequiresGCollection; 40 41 ReturnValueSlot getReturnValueSlot() const { 42 return ReturnValueSlot(DestPtr, VolatileDest); 43 } 44public: 45 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v, 46 bool ignore, bool isinit, bool requiresGCollection) 47 : CGF(cgf), Builder(CGF.Builder), 48 DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore), 49 IsInitializer(isinit), RequiresGCollection(requiresGCollection) { 50 } 51 52 //===--------------------------------------------------------------------===// 53 // Utilities 54 //===--------------------------------------------------------------------===// 55 56 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 57 /// represents a value lvalue, this method emits the address of the lvalue, 58 /// then loads the result into DestPtr. 59 void EmitAggLoadOfLValue(const Expr *E); 60 61 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 62 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 63 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 64 65 //===--------------------------------------------------------------------===// 66 // Visitor Methods 67 //===--------------------------------------------------------------------===// 68 69 void VisitStmt(Stmt *S) { 70 CGF.ErrorUnsupported(S, "aggregate expression"); 71 } 72 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 73 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 74 75 // l-values. 76 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 77 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 78 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 79 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 80 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 81 EmitAggLoadOfLValue(E); 82 } 83 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 84 EmitAggLoadOfLValue(E); 85 } 86 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 87 EmitAggLoadOfLValue(E); 88 } 89 void VisitPredefinedExpr(const PredefinedExpr *E) { 90 EmitAggLoadOfLValue(E); 91 } 92 93 // Operators. 94 void VisitCastExpr(CastExpr *E); 95 void VisitCallExpr(const CallExpr *E); 96 void VisitStmtExpr(const StmtExpr *E); 97 void VisitBinaryOperator(const BinaryOperator *BO); 98 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 99 void VisitBinAssign(const BinaryOperator *E); 100 void VisitBinComma(const BinaryOperator *E); 101 void VisitUnaryAddrOf(const UnaryOperator *E); 102 103 void VisitObjCMessageExpr(ObjCMessageExpr *E); 104 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 105 EmitAggLoadOfLValue(E); 106 } 107 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 108 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 109 110 void VisitConditionalOperator(const ConditionalOperator *CO); 111 void VisitChooseExpr(const ChooseExpr *CE); 112 void VisitInitListExpr(InitListExpr *E); 113 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 114 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 115 Visit(DAE->getExpr()); 116 } 117 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 118 void VisitCXXConstructExpr(const CXXConstructExpr *E); 119 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E); 120 void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E); 121 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 122 123 void VisitVAArgExpr(VAArgExpr *E); 124 125 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T); 126 void EmitNullInitializationToLValue(LValue Address, QualType T); 127 // case Expr::ChooseExprClass: 128 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 129}; 130} // end anonymous namespace. 131 132//===----------------------------------------------------------------------===// 133// Utilities 134//===----------------------------------------------------------------------===// 135 136/// EmitAggLoadOfLValue - Given an expression with aggregate type that 137/// represents a value lvalue, this method emits the address of the lvalue, 138/// then loads the result into DestPtr. 139void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 140 LValue LV = CGF.EmitLValue(E); 141 EmitFinalDestCopy(E, LV); 142} 143 144/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 145void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 146 assert(Src.isAggregate() && "value must be aggregate value!"); 147 148 // If the result is ignored, don't copy from the value. 149 if (DestPtr == 0) { 150 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore)) 151 return; 152 // If the source is volatile, we must read from it; to do that, we need 153 // some place to put it. 154 DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp"); 155 } 156 157 if (RequiresGCollection) { 158 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 159 DestPtr, Src.getAggregateAddr(), 160 E->getType()); 161 return; 162 } 163 // If the result of the assignment is used, copy the LHS there also. 164 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 165 // from the source as well, as we can't eliminate it if either operand 166 // is volatile, unless copy has volatile for both source and destination.. 167 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(), 168 VolatileDest|Src.isVolatileQualified()); 169} 170 171/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 172void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 173 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 174 175 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 176 Src.isVolatileQualified()), 177 Ignore); 178} 179 180//===----------------------------------------------------------------------===// 181// Visitor Methods 182//===----------------------------------------------------------------------===// 183 184void AggExprEmitter::VisitCastExpr(CastExpr *E) { 185 if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) { 186 Visit(E->getSubExpr()); 187 return; 188 } 189 190 switch (E->getCastKind()) { 191 default: assert(0 && "Unhandled cast kind!"); 192 193 case CastExpr::CK_Dynamic: { 194 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 195 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 196 // FIXME: Do we also need to handle property references here? 197 if (LV.isSimple()) 198 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 199 else 200 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 201 202 if (DestPtr) 203 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 204 break; 205 } 206 207 case CastExpr::CK_ToUnion: { 208 // GCC union extension 209 QualType PtrTy = 210 CGF.getContext().getPointerType(E->getSubExpr()->getType()); 211 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr, 212 CGF.ConvertType(PtrTy)); 213 EmitInitializationToLValue(E->getSubExpr(), 214 LValue::MakeAddr(CastPtr, Qualifiers()), 215 E->getSubExpr()->getType()); 216 break; 217 } 218 219 // FIXME: Remove the CK_Unknown check here. 220 case CastExpr::CK_Unknown: 221 case CastExpr::CK_NoOp: 222 case CastExpr::CK_UserDefinedConversion: 223 case CastExpr::CK_ConstructorConversion: 224 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 225 E->getType()) && 226 "Implicit cast types must be compatible"); 227 Visit(E->getSubExpr()); 228 break; 229 230 case CastExpr::CK_NullToMemberPointer: { 231 // If the subexpression's type is the C++0x nullptr_t, emit the 232 // subexpression, which may have side effects. 233 if (E->getSubExpr()->getType()->isNullPtrType()) 234 Visit(E->getSubExpr()); 235 236 const llvm::Type *PtrDiffTy = 237 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 238 239 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy); 240 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr"); 241 Builder.CreateStore(NullValue, Ptr, VolatileDest); 242 243 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj"); 244 Builder.CreateStore(NullValue, Adj, VolatileDest); 245 246 break; 247 } 248 249 case CastExpr::CK_BitCast: { 250 // This must be a member function pointer cast. 251 Visit(E->getSubExpr()); 252 break; 253 } 254 255 case CastExpr::CK_DerivedToBaseMemberPointer: 256 case CastExpr::CK_BaseToDerivedMemberPointer: { 257 QualType SrcType = E->getSubExpr()->getType(); 258 259 llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp"); 260 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 261 262 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr"); 263 SrcPtr = Builder.CreateLoad(SrcPtr); 264 265 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj"); 266 SrcAdj = Builder.CreateLoad(SrcAdj); 267 268 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 269 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest); 270 271 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 272 273 // Now See if we need to update the adjustment. 274 const CXXRecordDecl *BaseDecl = 275 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()-> 276 getClass()->getAs<RecordType>()->getDecl()); 277 const CXXRecordDecl *DerivedDecl = 278 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 279 getClass()->getAs<RecordType>()->getDecl()); 280 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 281 std::swap(DerivedDecl, BaseDecl); 282 283 if (llvm::Constant *Adj = 284 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, E->getBasePath())) { 285 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 286 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj"); 287 else 288 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj"); 289 } 290 291 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest); 292 break; 293 } 294 } 295} 296 297void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 298 if (E->getCallReturnType()->isReferenceType()) { 299 EmitAggLoadOfLValue(E); 300 return; 301 } 302 303 // If the struct doesn't require GC, we can just pass the destination 304 // directly to EmitCall. 305 if (!RequiresGCollection) { 306 CGF.EmitCallExpr(E, getReturnValueSlot()); 307 return; 308 } 309 310 RValue RV = CGF.EmitCallExpr(E); 311 EmitFinalDestCopy(E, RV); 312} 313 314void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 315 CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 316} 317 318void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 319 CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 320} 321 322void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 323 ObjCImplicitSetterGetterRefExpr *E) { 324 CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 325} 326 327void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 328 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 329 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 330 /*IgnoreResult=*/false, IsInitializer); 331} 332 333void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 334 // We have a member function pointer. 335 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 336 (void) MPT; 337 assert(MPT->getPointeeType()->isFunctionProtoType() && 338 "Unexpected member pointer type!"); 339 340 // The creation of member function pointers has no side effects; if 341 // there is no destination pointer, we have nothing to do. 342 if (!DestPtr) 343 return; 344 345 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 346 const CXXMethodDecl *MD = 347 cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl(); 348 349 const llvm::Type *PtrDiffTy = 350 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 351 352 353 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 354 llvm::Value *FuncPtr; 355 356 if (MD->isVirtual()) { 357 int64_t Index = CGF.CGM.getVTables().getMethodVTableIndex(MD); 358 359 // FIXME: We shouldn't use / 8 here. 360 uint64_t PointerWidthInBytes = 361 CGF.CGM.getContext().Target.getPointerWidth(0) / 8; 362 363 // Itanium C++ ABI 2.3: 364 // For a non-virtual function, this field is a simple function pointer. 365 // For a virtual function, it is 1 plus the virtual table offset 366 // (in bytes) of the function, represented as a ptrdiff_t. 367 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, 368 (Index * PointerWidthInBytes) + 1); 369 } else { 370 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 371 const llvm::Type *Ty = 372 CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD), 373 FPT->isVariadic()); 374 llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty); 375 FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy); 376 } 377 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 378 379 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 380 381 // The adjustment will always be 0. 382 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 383 VolatileDest); 384} 385 386void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 387 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 388} 389 390void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 391 if (E->getOpcode() == BinaryOperator::PtrMemD || 392 E->getOpcode() == BinaryOperator::PtrMemI) 393 VisitPointerToDataMemberBinaryOperator(E); 394 else 395 CGF.ErrorUnsupported(E, "aggregate binary expression"); 396} 397 398void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 399 const BinaryOperator *E) { 400 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 401 EmitFinalDestCopy(E, LV); 402} 403 404void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 405 // For an assignment to work, the value on the right has 406 // to be compatible with the value on the left. 407 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 408 E->getRHS()->getType()) 409 && "Invalid assignment"); 410 LValue LHS = CGF.EmitLValue(E->getLHS()); 411 412 // We have to special case property setters, otherwise we must have 413 // a simple lvalue (no aggregates inside vectors, bitfields). 414 if (LHS.isPropertyRef()) { 415 llvm::Value *AggLoc = DestPtr; 416 if (!AggLoc) 417 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 418 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 419 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 420 RValue::getAggregate(AggLoc, VolatileDest)); 421 } else if (LHS.isKVCRef()) { 422 llvm::Value *AggLoc = DestPtr; 423 if (!AggLoc) 424 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 425 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 426 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 427 RValue::getAggregate(AggLoc, VolatileDest)); 428 } else { 429 bool RequiresGCollection = false; 430 if (CGF.getContext().getLangOptions().NeXTRuntime) { 431 QualType LHSTy = E->getLHS()->getType(); 432 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 433 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 434 } 435 // Codegen the RHS so that it stores directly into the LHS. 436 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 437 false, false, RequiresGCollection); 438 EmitFinalDestCopy(E, LHS, true); 439 } 440} 441 442void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 443 if (!E->getLHS()) { 444 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 445 return; 446 } 447 448 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 449 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 450 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 451 452 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 453 454 CGF.BeginConditionalBranch(); 455 CGF.EmitBlock(LHSBlock); 456 457 // Handle the GNU extension for missing LHS. 458 assert(E->getLHS() && "Must have LHS for aggregate value"); 459 460 Visit(E->getLHS()); 461 CGF.EndConditionalBranch(); 462 CGF.EmitBranch(ContBlock); 463 464 CGF.BeginConditionalBranch(); 465 CGF.EmitBlock(RHSBlock); 466 467 Visit(E->getRHS()); 468 CGF.EndConditionalBranch(); 469 CGF.EmitBranch(ContBlock); 470 471 CGF.EmitBlock(ContBlock); 472} 473 474void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 475 Visit(CE->getChosenSubExpr(CGF.getContext())); 476} 477 478void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 479 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 480 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 481 482 if (!ArgPtr) { 483 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 484 return; 485 } 486 487 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 488} 489 490void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 491 llvm::Value *Val = DestPtr; 492 493 if (!Val) { 494 // Create a temporary variable. 495 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 496 497 // FIXME: volatile 498 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 499 } else 500 Visit(E->getSubExpr()); 501 502 // Don't make this a live temporary if we're emitting an initializer expr. 503 if (!IsInitializer) 504 CGF.PushCXXTemporary(E->getTemporary(), Val); 505} 506 507void 508AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 509 llvm::Value *Val = DestPtr; 510 511 if (!Val) { 512 // Create a temporary variable. 513 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 514 } 515 516 if (E->requiresZeroInitialization()) 517 EmitNullInitializationToLValue(LValue::MakeAddr(Val, 518 // FIXME: Qualifiers()? 519 E->getType().getQualifiers()), 520 E->getType()); 521 522 CGF.EmitCXXConstructExpr(Val, E); 523} 524 525void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 526 llvm::Value *Val = DestPtr; 527 528 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer); 529} 530 531void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 532 llvm::Value *Val = DestPtr; 533 534 if (!Val) { 535 // Create a temporary variable. 536 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 537 } 538 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 539 EmitNullInitializationToLValue(LV, E->getType()); 540} 541 542void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 543 llvm::Value *Val = DestPtr; 544 545 if (!Val) { 546 // Create a temporary variable. 547 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 548 } 549 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 550 EmitNullInitializationToLValue(LV, E->getType()); 551} 552 553void 554AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 555 // FIXME: Ignore result? 556 // FIXME: Are initializers affected by volatile? 557 if (isa<ImplicitValueInitExpr>(E)) { 558 EmitNullInitializationToLValue(LV, T); 559 } else if (T->isReferenceType()) { 560 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false); 561 CGF.EmitStoreThroughLValue(RV, LV, T); 562 } else if (T->isAnyComplexType()) { 563 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 564 } else if (CGF.hasAggregateLLVMType(T)) { 565 CGF.EmitAnyExpr(E, LV.getAddress(), false); 566 } else { 567 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T); 568 } 569} 570 571void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 572 if (!CGF.hasAggregateLLVMType(T)) { 573 // For non-aggregates, we can store zero 574 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 575 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 576 } else { 577 // Otherwise, just memset the whole thing to zero. This is legal 578 // because in LLVM, all default initializers are guaranteed to have a 579 // bit pattern of all zeros. 580 // FIXME: That isn't true for member pointers! 581 // There's a potential optimization opportunity in combining 582 // memsets; that would be easy for arrays, but relatively 583 // difficult for structures with the current code. 584 CGF.EmitMemSetToZero(LV.getAddress(), T); 585 } 586} 587 588void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 589#if 0 590 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 591 // (Length of globals? Chunks of zeroed-out space?). 592 // 593 // If we can, prefer a copy from a global; this is a lot less code for long 594 // globals, and it's easier for the current optimizers to analyze. 595 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 596 llvm::GlobalVariable* GV = 597 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 598 llvm::GlobalValue::InternalLinkage, C, ""); 599 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers())); 600 return; 601 } 602#endif 603 if (E->hadArrayRangeDesignator()) { 604 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 605 } 606 607 // Handle initialization of an array. 608 if (E->getType()->isArrayType()) { 609 const llvm::PointerType *APType = 610 cast<llvm::PointerType>(DestPtr->getType()); 611 const llvm::ArrayType *AType = 612 cast<llvm::ArrayType>(APType->getElementType()); 613 614 uint64_t NumInitElements = E->getNumInits(); 615 616 if (E->getNumInits() > 0) { 617 QualType T1 = E->getType(); 618 QualType T2 = E->getInit(0)->getType(); 619 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 620 EmitAggLoadOfLValue(E->getInit(0)); 621 return; 622 } 623 } 624 625 uint64_t NumArrayElements = AType->getNumElements(); 626 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 627 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 628 629 // FIXME: were we intentionally ignoring address spaces and GC attributes? 630 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 631 632 for (uint64_t i = 0; i != NumArrayElements; ++i) { 633 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 634 if (i < NumInitElements) 635 EmitInitializationToLValue(E->getInit(i), 636 LValue::MakeAddr(NextVal, Quals), 637 ElementType); 638 else 639 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 640 ElementType); 641 } 642 return; 643 } 644 645 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 646 647 // Do struct initialization; this code just sets each individual member 648 // to the approprate value. This makes bitfield support automatic; 649 // the disadvantage is that the generated code is more difficult for 650 // the optimizer, especially with bitfields. 651 unsigned NumInitElements = E->getNumInits(); 652 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 653 unsigned CurInitVal = 0; 654 655 if (E->getType()->isUnionType()) { 656 // Only initialize one field of a union. The field itself is 657 // specified by the initializer list. 658 if (!E->getInitializedFieldInUnion()) { 659 // Empty union; we have nothing to do. 660 661#ifndef NDEBUG 662 // Make sure that it's really an empty and not a failure of 663 // semantic analysis. 664 for (RecordDecl::field_iterator Field = SD->field_begin(), 665 FieldEnd = SD->field_end(); 666 Field != FieldEnd; ++Field) 667 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 668#endif 669 return; 670 } 671 672 // FIXME: volatility 673 FieldDecl *Field = E->getInitializedFieldInUnion(); 674 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 675 676 if (NumInitElements) { 677 // Store the initializer into the field 678 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 679 } else { 680 // Default-initialize to null 681 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 682 } 683 684 return; 685 } 686 687 // If we're initializing the whole aggregate, just do it in place. 688 // FIXME: This is a hack around an AST bug (PR6537). 689 if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) { 690 EmitInitializationToLValue(E->getInit(0), 691 LValue::MakeAddr(DestPtr, Qualifiers()), 692 E->getType()); 693 return; 694 } 695 696 697 // Here we iterate over the fields; this makes it simpler to both 698 // default-initialize fields and skip over unnamed fields. 699 for (RecordDecl::field_iterator Field = SD->field_begin(), 700 FieldEnd = SD->field_end(); 701 Field != FieldEnd; ++Field) { 702 // We're done once we hit the flexible array member 703 if (Field->getType()->isIncompleteArrayType()) 704 break; 705 706 if (Field->isUnnamedBitfield()) 707 continue; 708 709 // FIXME: volatility 710 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 711 // We never generate write-barries for initialized fields. 712 LValue::SetObjCNonGC(FieldLoc, true); 713 if (CurInitVal < NumInitElements) { 714 // Store the initializer into the field. 715 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 716 Field->getType()); 717 } else { 718 // We're out of initalizers; default-initialize to null 719 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 720 } 721 } 722} 723 724//===----------------------------------------------------------------------===// 725// Entry Points into this File 726//===----------------------------------------------------------------------===// 727 728/// EmitAggExpr - Emit the computation of the specified expression of aggregate 729/// type. The result is computed into DestPtr. Note that if DestPtr is null, 730/// the value of the aggregate expression is not needed. If VolatileDest is 731/// true, DestPtr cannot be 0. 732// 733// FIXME: Take Qualifiers object. 734void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 735 bool VolatileDest, bool IgnoreResult, 736 bool IsInitializer, 737 bool RequiresGCollection) { 738 assert(E && hasAggregateLLVMType(E->getType()) && 739 "Invalid aggregate expression to emit"); 740 assert ((DestPtr != 0 || VolatileDest == false) 741 && "volatile aggregate can't be 0"); 742 743 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 744 RequiresGCollection) 745 .Visit(const_cast<Expr*>(E)); 746} 747 748LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 749 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 750 Qualifiers Q = MakeQualifiers(E->getType()); 751 llvm::Value *Temp = CreateMemTemp(E->getType()); 752 EmitAggExpr(E, Temp, Q.hasVolatile()); 753 return LValue::MakeAddr(Temp, Q); 754} 755 756void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 757 llvm::Value *SrcPtr, QualType Ty, 758 bool isVolatile) { 759 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 760 761 if (getContext().getLangOptions().CPlusPlus) { 762 if (const RecordType *RT = Ty->getAs<RecordType>()) { 763 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 764 assert((Record->hasTrivialCopyConstructor() || 765 Record->hasTrivialCopyAssignment()) && 766 "Trying to aggregate-copy a type without a trivial copy " 767 "constructor or assignment operator"); 768 // Ignore empty classes in C++. 769 if (Record->isEmpty()) 770 return; 771 } 772 } 773 774 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 775 // C99 6.5.16.1p3, which states "If the value being stored in an object is 776 // read from another object that overlaps in anyway the storage of the first 777 // object, then the overlap shall be exact and the two objects shall have 778 // qualified or unqualified versions of a compatible type." 779 // 780 // memcpy is not defined if the source and destination pointers are exactly 781 // equal, but other compilers do this optimization, and almost every memcpy 782 // implementation handles this case safely. If there is a libc that does not 783 // safely handle this, we can add a target hook. 784 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 785 if (DestPtr->getType() != BP) 786 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 787 if (SrcPtr->getType() != BP) 788 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 789 790 // Get size and alignment info for this aggregate. 791 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 792 793 // FIXME: Handle variable sized types. 794 const llvm::Type *IntPtr = 795 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 796 797 // FIXME: If we have a volatile struct, the optimizer can remove what might 798 // appear to be `extra' memory ops: 799 // 800 // volatile struct { int i; } a, b; 801 // 802 // int main() { 803 // a = b; 804 // a = b; 805 // } 806 // 807 // we need to use a different call here. We use isVolatile to indicate when 808 // either the source or the destination is volatile. 809 const llvm::Type *I1Ty = llvm::Type::getInt1Ty(VMContext); 810 const llvm::Type *I8Ty = llvm::Type::getInt8Ty(VMContext); 811 const llvm::Type *I32Ty = llvm::Type::getInt32Ty(VMContext); 812 813 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 814 const llvm::Type *DBP = llvm::PointerType::get(I8Ty, DPT->getAddressSpace()); 815 if (DestPtr->getType() != DBP) 816 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 817 818 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 819 const llvm::Type *SBP = llvm::PointerType::get(I8Ty, SPT->getAddressSpace()); 820 if (SrcPtr->getType() != SBP) 821 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 822 823 Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), 824 IntPtr), 825 DestPtr, SrcPtr, 826 // TypeInfo.first describes size in bits. 827 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 828 llvm::ConstantInt::get(I32Ty, TypeInfo.second/8), 829 llvm::ConstantInt::get(I1Ty, isVolatile)); 830} 831