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" 24 using namespace clang; 25 using namespace CodeGen; 26 27 //===----------------------------------------------------------------------===// 28 // Aggregate Expression Emitter 29 //===----------------------------------------------------------------------===// 30 31 namespace { 32 class 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 } 44 public: 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. 139 void 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. 145 void 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. 172 void 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 184 void 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 case CastExpr::CK_DerivedToBase: 220 case CastExpr::CK_BaseToDerived: 221 case CastExpr::CK_UncheckedDerivedToBase: { 222 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: " 223 "should have been unpacked before we got here"); 224 break; 225 } 226 227 // FIXME: Remove the CK_Unknown check here. 228 case CastExpr::CK_Unknown: 229 case CastExpr::CK_NoOp: 230 case CastExpr::CK_UserDefinedConversion: 231 case CastExpr::CK_ConstructorConversion: 232 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 233 E->getType()) && 234 "Implicit cast types must be compatible"); 235 Visit(E->getSubExpr()); 236 break; 237 238 case CastExpr::CK_NullToMemberPointer: { 239 // If the subexpression's type is the C++0x nullptr_t, emit the 240 // subexpression, which may have side effects. 241 if (E->getSubExpr()->getType()->isNullPtrType()) 242 Visit(E->getSubExpr()); 243 244 const llvm::Type *PtrDiffTy = 245 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 246 247 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy); 248 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr"); 249 Builder.CreateStore(NullValue, Ptr, VolatileDest); 250 251 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj"); 252 Builder.CreateStore(NullValue, Adj, VolatileDest); 253 254 break; 255 } 256 257 case CastExpr::CK_BitCast: { 258 // This must be a member function pointer cast. 259 Visit(E->getSubExpr()); 260 break; 261 } 262 263 case CastExpr::CK_DerivedToBaseMemberPointer: 264 case CastExpr::CK_BaseToDerivedMemberPointer: { 265 QualType SrcType = E->getSubExpr()->getType(); 266 267 llvm::Value *Src = CGF.CreateMemTemp(SrcType, "tmp"); 268 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 269 270 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr"); 271 SrcPtr = Builder.CreateLoad(SrcPtr); 272 273 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj"); 274 SrcAdj = Builder.CreateLoad(SrcAdj); 275 276 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 277 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest); 278 279 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 280 281 // Now See if we need to update the adjustment. 282 const CXXRecordDecl *BaseDecl = 283 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()-> 284 getClass()->getAs<RecordType>()->getDecl()); 285 const CXXRecordDecl *DerivedDecl = 286 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 287 getClass()->getAs<RecordType>()->getDecl()); 288 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 289 std::swap(DerivedDecl, BaseDecl); 290 291 if (llvm::Constant *Adj = 292 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, E->getBasePath())) { 293 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 294 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj"); 295 else 296 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj"); 297 } 298 299 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest); 300 break; 301 } 302 } 303 } 304 305 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 306 if (E->getCallReturnType()->isReferenceType()) { 307 EmitAggLoadOfLValue(E); 308 return; 309 } 310 311 // If the struct doesn't require GC, we can just pass the destination 312 // directly to EmitCall. 313 if (!RequiresGCollection) { 314 CGF.EmitCallExpr(E, getReturnValueSlot()); 315 return; 316 } 317 318 RValue RV = CGF.EmitCallExpr(E); 319 EmitFinalDestCopy(E, RV); 320 } 321 322 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 323 CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 324 } 325 326 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 327 CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 328 } 329 330 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 331 ObjCImplicitSetterGetterRefExpr *E) { 332 CGF.EmitObjCPropertyGet(E, getReturnValueSlot()); 333 } 334 335 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 336 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 337 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 338 /*IgnoreResult=*/false, IsInitializer); 339 } 340 341 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 342 // We have a member function pointer. 343 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 344 (void) MPT; 345 assert(MPT->getPointeeType()->isFunctionProtoType() && 346 "Unexpected member pointer type!"); 347 348 // The creation of member function pointers has no side effects; if 349 // there is no destination pointer, we have nothing to do. 350 if (!DestPtr) 351 return; 352 353 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 354 const CXXMethodDecl *MD = 355 cast<CXXMethodDecl>(DRE->getDecl())->getCanonicalDecl(); 356 357 const llvm::Type *PtrDiffTy = 358 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 359 360 361 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 362 llvm::Value *FuncPtr; 363 364 if (MD->isVirtual()) { 365 int64_t Index = CGF.CGM.getVTables().getMethodVTableIndex(MD); 366 367 // FIXME: We shouldn't use / 8 here. 368 uint64_t PointerWidthInBytes = 369 CGF.CGM.getContext().Target.getPointerWidth(0) / 8; 370 371 // Itanium C++ ABI 2.3: 372 // For a non-virtual function, this field is a simple function pointer. 373 // For a virtual function, it is 1 plus the virtual table offset 374 // (in bytes) of the function, represented as a ptrdiff_t. 375 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, 376 (Index * PointerWidthInBytes) + 1); 377 } else { 378 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 379 const llvm::Type *Ty = 380 CGF.CGM.getTypes().GetFunctionType(CGF.CGM.getTypes().getFunctionInfo(MD), 381 FPT->isVariadic()); 382 llvm::Constant *Fn = CGF.CGM.GetAddrOfFunction(MD, Ty); 383 FuncPtr = llvm::ConstantExpr::getPtrToInt(Fn, PtrDiffTy); 384 } 385 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 386 387 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 388 389 // The adjustment will always be 0. 390 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 391 VolatileDest); 392 } 393 394 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 395 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 396 } 397 398 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 399 if (E->getOpcode() == BinaryOperator::PtrMemD || 400 E->getOpcode() == BinaryOperator::PtrMemI) 401 VisitPointerToDataMemberBinaryOperator(E); 402 else 403 CGF.ErrorUnsupported(E, "aggregate binary expression"); 404 } 405 406 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 407 const BinaryOperator *E) { 408 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 409 EmitFinalDestCopy(E, LV); 410 } 411 412 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 413 // For an assignment to work, the value on the right has 414 // to be compatible with the value on the left. 415 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 416 E->getRHS()->getType()) 417 && "Invalid assignment"); 418 LValue LHS = CGF.EmitLValue(E->getLHS()); 419 420 // We have to special case property setters, otherwise we must have 421 // a simple lvalue (no aggregates inside vectors, bitfields). 422 if (LHS.isPropertyRef()) { 423 llvm::Value *AggLoc = DestPtr; 424 if (!AggLoc) 425 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 426 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 427 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 428 RValue::getAggregate(AggLoc, VolatileDest)); 429 } else if (LHS.isKVCRef()) { 430 llvm::Value *AggLoc = DestPtr; 431 if (!AggLoc) 432 AggLoc = CGF.CreateMemTemp(E->getRHS()->getType()); 433 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 434 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 435 RValue::getAggregate(AggLoc, VolatileDest)); 436 } else { 437 bool RequiresGCollection = false; 438 if (CGF.getContext().getLangOptions().NeXTRuntime) { 439 QualType LHSTy = E->getLHS()->getType(); 440 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 441 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 442 } 443 // Codegen the RHS so that it stores directly into the LHS. 444 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 445 false, false, RequiresGCollection); 446 EmitFinalDestCopy(E, LHS, true); 447 } 448 } 449 450 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 451 if (!E->getLHS()) { 452 CGF.ErrorUnsupported(E, "conditional operator with missing LHS"); 453 return; 454 } 455 456 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 457 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 458 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 459 460 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 461 462 CGF.BeginConditionalBranch(); 463 CGF.EmitBlock(LHSBlock); 464 465 // Handle the GNU extension for missing LHS. 466 assert(E->getLHS() && "Must have LHS for aggregate value"); 467 468 Visit(E->getLHS()); 469 CGF.EndConditionalBranch(); 470 CGF.EmitBranch(ContBlock); 471 472 CGF.BeginConditionalBranch(); 473 CGF.EmitBlock(RHSBlock); 474 475 Visit(E->getRHS()); 476 CGF.EndConditionalBranch(); 477 CGF.EmitBranch(ContBlock); 478 479 CGF.EmitBlock(ContBlock); 480 } 481 482 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 483 Visit(CE->getChosenSubExpr(CGF.getContext())); 484 } 485 486 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 487 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 488 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 489 490 if (!ArgPtr) { 491 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 492 return; 493 } 494 495 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 496 } 497 498 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 499 llvm::Value *Val = DestPtr; 500 501 if (!Val) { 502 // Create a temporary variable. 503 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 504 505 // FIXME: volatile 506 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 507 } else 508 Visit(E->getSubExpr()); 509 510 // Don't make this a live temporary if we're emitting an initializer expr. 511 if (!IsInitializer) 512 CGF.PushCXXTemporary(E->getTemporary(), Val); 513 } 514 515 void 516 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 517 llvm::Value *Val = DestPtr; 518 519 if (!Val) { 520 // Create a temporary variable. 521 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 522 } 523 524 if (E->requiresZeroInitialization()) 525 EmitNullInitializationToLValue(LValue::MakeAddr(Val, 526 // FIXME: Qualifiers()? 527 E->getType().getQualifiers()), 528 E->getType()); 529 530 CGF.EmitCXXConstructExpr(Val, E); 531 } 532 533 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 534 llvm::Value *Val = DestPtr; 535 536 CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer); 537 } 538 539 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 540 llvm::Value *Val = DestPtr; 541 542 if (!Val) { 543 // Create a temporary variable. 544 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 545 } 546 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 547 EmitNullInitializationToLValue(LV, E->getType()); 548 } 549 550 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 551 llvm::Value *Val = DestPtr; 552 553 if (!Val) { 554 // Create a temporary variable. 555 Val = CGF.CreateMemTemp(E->getType(), "tmp"); 556 } 557 LValue LV = LValue::MakeAddr(Val, Qualifiers()); 558 EmitNullInitializationToLValue(LV, E->getType()); 559 } 560 561 void 562 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 563 // FIXME: Ignore result? 564 // FIXME: Are initializers affected by volatile? 565 if (isa<ImplicitValueInitExpr>(E)) { 566 EmitNullInitializationToLValue(LV, T); 567 } else if (T->isReferenceType()) { 568 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*IsInitializer=*/false); 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.EmitAnyExpr(E, LV.getAddress(), false); 574 } else { 575 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T); 576 } 577 } 578 579 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 580 if (!CGF.hasAggregateLLVMType(T)) { 581 // For non-aggregates, we can store zero 582 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 583 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 584 } else { 585 // There's a potential optimization opportunity in combining 586 // memsets; that would be easy for arrays, but relatively 587 // difficult for structures with the current code. 588 CGF.EmitNullInitialization(LV.getAddress(), T); 589 } 590 } 591 592 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 593 #if 0 594 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 595 // (Length of globals? Chunks of zeroed-out space?). 596 // 597 // If we can, prefer a copy from a global; this is a lot less code for long 598 // globals, and it's easier for the current optimizers to analyze. 599 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 600 llvm::GlobalVariable* GV = 601 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 602 llvm::GlobalValue::InternalLinkage, C, ""); 603 EmitFinalDestCopy(E, LValue::MakeAddr(GV, Qualifiers())); 604 return; 605 } 606 #endif 607 if (E->hadArrayRangeDesignator()) { 608 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 609 } 610 611 // Handle initialization of an array. 612 if (E->getType()->isArrayType()) { 613 const llvm::PointerType *APType = 614 cast<llvm::PointerType>(DestPtr->getType()); 615 const llvm::ArrayType *AType = 616 cast<llvm::ArrayType>(APType->getElementType()); 617 618 uint64_t NumInitElements = E->getNumInits(); 619 620 if (E->getNumInits() > 0) { 621 QualType T1 = E->getType(); 622 QualType T2 = E->getInit(0)->getType(); 623 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 624 EmitAggLoadOfLValue(E->getInit(0)); 625 return; 626 } 627 } 628 629 uint64_t NumArrayElements = AType->getNumElements(); 630 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 631 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 632 633 // FIXME: were we intentionally ignoring address spaces and GC attributes? 634 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 635 636 for (uint64_t i = 0; i != NumArrayElements; ++i) { 637 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 638 if (i < NumInitElements) 639 EmitInitializationToLValue(E->getInit(i), 640 LValue::MakeAddr(NextVal, Quals), 641 ElementType); 642 else 643 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 644 ElementType); 645 } 646 return; 647 } 648 649 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 650 651 // Do struct initialization; this code just sets each individual member 652 // to the approprate value. This makes bitfield support automatic; 653 // the disadvantage is that the generated code is more difficult for 654 // the optimizer, especially with bitfields. 655 unsigned NumInitElements = E->getNumInits(); 656 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 657 unsigned CurInitVal = 0; 658 659 if (E->getType()->isUnionType()) { 660 // Only initialize one field of a union. The field itself is 661 // specified by the initializer list. 662 if (!E->getInitializedFieldInUnion()) { 663 // Empty union; we have nothing to do. 664 665 #ifndef NDEBUG 666 // Make sure that it's really an empty and not a failure of 667 // semantic analysis. 668 for (RecordDecl::field_iterator Field = SD->field_begin(), 669 FieldEnd = SD->field_end(); 670 Field != FieldEnd; ++Field) 671 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 672 #endif 673 return; 674 } 675 676 // FIXME: volatility 677 FieldDecl *Field = E->getInitializedFieldInUnion(); 678 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 679 680 if (NumInitElements) { 681 // Store the initializer into the field 682 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 683 } else { 684 // Default-initialize to null 685 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 686 } 687 688 return; 689 } 690 691 // If we're initializing the whole aggregate, just do it in place. 692 // FIXME: This is a hack around an AST bug (PR6537). 693 if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) { 694 EmitInitializationToLValue(E->getInit(0), 695 LValue::MakeAddr(DestPtr, Qualifiers()), 696 E->getType()); 697 return; 698 } 699 700 701 // Here we iterate over the fields; this makes it simpler to both 702 // default-initialize fields and skip over unnamed fields. 703 for (RecordDecl::field_iterator Field = SD->field_begin(), 704 FieldEnd = SD->field_end(); 705 Field != FieldEnd; ++Field) { 706 // We're done once we hit the flexible array member 707 if (Field->getType()->isIncompleteArrayType()) 708 break; 709 710 if (Field->isUnnamedBitfield()) 711 continue; 712 713 // FIXME: volatility 714 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 715 // We never generate write-barries for initialized fields. 716 LValue::SetObjCNonGC(FieldLoc, true); 717 if (CurInitVal < NumInitElements) { 718 // Store the initializer into the field. 719 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 720 Field->getType()); 721 } else { 722 // We're out of initalizers; default-initialize to null 723 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 724 } 725 } 726 } 727 728 //===----------------------------------------------------------------------===// 729 // Entry Points into this File 730 //===----------------------------------------------------------------------===// 731 732 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 733 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 734 /// the value of the aggregate expression is not needed. If VolatileDest is 735 /// true, DestPtr cannot be 0. 736 // 737 // FIXME: Take Qualifiers object. 738 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 739 bool VolatileDest, bool IgnoreResult, 740 bool IsInitializer, 741 bool RequiresGCollection) { 742 assert(E && hasAggregateLLVMType(E->getType()) && 743 "Invalid aggregate expression to emit"); 744 assert ((DestPtr != 0 || VolatileDest == false) 745 && "volatile aggregate can't be 0"); 746 747 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 748 RequiresGCollection) 749 .Visit(const_cast<Expr*>(E)); 750 } 751 752 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 753 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 754 Qualifiers Q = MakeQualifiers(E->getType()); 755 llvm::Value *Temp = CreateMemTemp(E->getType()); 756 EmitAggExpr(E, Temp, Q.hasVolatile()); 757 return LValue::MakeAddr(Temp, Q); 758 } 759 760 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 761 llvm::Value *SrcPtr, QualType Ty, 762 bool isVolatile) { 763 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 764 765 if (getContext().getLangOptions().CPlusPlus) { 766 if (const RecordType *RT = Ty->getAs<RecordType>()) { 767 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 768 assert((Record->hasTrivialCopyConstructor() || 769 Record->hasTrivialCopyAssignment()) && 770 "Trying to aggregate-copy a type without a trivial copy " 771 "constructor or assignment operator"); 772 // Ignore empty classes in C++. 773 if (Record->isEmpty()) 774 return; 775 } 776 } 777 778 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 779 // C99 6.5.16.1p3, which states "If the value being stored in an object is 780 // read from another object that overlaps in anyway the storage of the first 781 // object, then the overlap shall be exact and the two objects shall have 782 // qualified or unqualified versions of a compatible type." 783 // 784 // memcpy is not defined if the source and destination pointers are exactly 785 // equal, but other compilers do this optimization, and almost every memcpy 786 // implementation handles this case safely. If there is a libc that does not 787 // safely handle this, we can add a target hook. 788 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 789 if (DestPtr->getType() != BP) 790 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 791 if (SrcPtr->getType() != BP) 792 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 793 794 // Get size and alignment info for this aggregate. 795 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 796 797 // FIXME: Handle variable sized types. 798 const llvm::Type *IntPtr = 799 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 800 801 // FIXME: If we have a volatile struct, the optimizer can remove what might 802 // appear to be `extra' memory ops: 803 // 804 // volatile struct { int i; } a, b; 805 // 806 // int main() { 807 // a = b; 808 // a = b; 809 // } 810 // 811 // we need to use a different call here. We use isVolatile to indicate when 812 // either the source or the destination is volatile. 813 const llvm::Type *I1Ty = llvm::Type::getInt1Ty(VMContext); 814 const llvm::Type *I8Ty = llvm::Type::getInt8Ty(VMContext); 815 const llvm::Type *I32Ty = llvm::Type::getInt32Ty(VMContext); 816 817 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 818 const llvm::Type *DBP = llvm::PointerType::get(I8Ty, DPT->getAddressSpace()); 819 if (DestPtr->getType() != DBP) 820 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 821 822 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 823 const llvm::Type *SBP = llvm::PointerType::get(I8Ty, SPT->getAddressSpace()); 824 if (SrcPtr->getType() != SBP) 825 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 826 827 Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(), 828 IntPtr), 829 DestPtr, SrcPtr, 830 // TypeInfo.first describes size in bits. 831 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 832 llvm::ConstantInt::get(I32Ty, TypeInfo.second/8), 833 llvm::ConstantInt::get(I1Ty, isVolatile)); 834 } 835