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 public: 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) { 46 } 47 48 //===--------------------------------------------------------------------===// 49 // Utilities 50 //===--------------------------------------------------------------------===// 51 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); 56 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); 60 61 //===--------------------------------------------------------------------===// 62 // Visitor Methods 63 //===--------------------------------------------------------------------===// 64 65 void VisitStmt(Stmt *S) { 66 CGF.ErrorUnsupported(S, "aggregate expression"); 67 } 68 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 69 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 70 71 // l-values. 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); 78 } 79 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 80 EmitAggLoadOfLValue(E); 81 } 82 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 83 EmitAggLoadOfLValue(E); 84 } 85 void VisitPredefinedExpr(const PredefinedExpr *E) { 86 EmitAggLoadOfLValue(E); 87 } 88 89 // Operators. 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); 98 99 void VisitObjCMessageExpr(ObjCMessageExpr *E); 100 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 101 EmitAggLoadOfLValue(E); 102 } 103 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 104 void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E); 105 106 void VisitConditionalOperator(const ConditionalOperator *CO); 107 void VisitChooseExpr(const ChooseExpr *CE); 108 void VisitInitListExpr(InitListExpr *E); 109 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 110 Visit(DAE->getExpr()); 111 } 112 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 113 void VisitCXXConstructExpr(const CXXConstructExpr *E); 114 void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E); 115 void VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E); 116 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 117 118 void VisitVAArgExpr(VAArgExpr *E); 119 120 void EmitInitializationToLValue(Expr *E, LValue Address); 121 void EmitNullInitializationToLValue(LValue Address, QualType T); 122 // case Expr::ChooseExprClass: 123 124 }; 125 } // end anonymous namespace. 126 127 //===----------------------------------------------------------------------===// 128 // Utilities 129 //===----------------------------------------------------------------------===// 130 131 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 132 /// represents a value lvalue, this method emits the address of the lvalue, 133 /// then loads the result into DestPtr. 134 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 135 LValue LV = CGF.EmitLValue(E); 136 EmitFinalDestCopy(E, LV); 137 } 138 139 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 140 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 141 assert(Src.isAggregate() && "value must be aggregate value!"); 142 143 // If the result is ignored, don't copy from the value. 144 if (DestPtr == 0) { 145 if (!Src.isVolatileQualified() || (IgnoreResult && Ignore)) 146 return; 147 // If the source is volatile, we must read from it; to do that, we need 148 // some place to put it. 149 DestPtr = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "agg.tmp"); 150 } 151 152 if (RequiresGCollection) { 153 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 154 DestPtr, Src.getAggregateAddr(), 155 E->getType()); 156 return; 157 } 158 // If the result of the assignment is used, copy the LHS there also. 159 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 160 // from the source as well, as we can't eliminate it if either operand 161 // is volatile, unless copy has volatile for both source and destination.. 162 CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(), 163 VolatileDest|Src.isVolatileQualified()); 164 } 165 166 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 167 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 168 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 169 170 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 171 Src.isVolatileQualified()), 172 Ignore); 173 } 174 175 //===----------------------------------------------------------------------===// 176 // Visitor Methods 177 //===----------------------------------------------------------------------===// 178 179 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 180 switch (E->getCastKind()) { 181 default: assert(0 && "Unhandled cast kind!"); 182 183 case CastExpr::CK_ToUnion: { 184 // GCC union extension 185 QualType PtrTy = 186 CGF.getContext().getPointerType(E->getSubExpr()->getType()); 187 llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr, 188 CGF.ConvertType(PtrTy)); 189 EmitInitializationToLValue(E->getSubExpr(), 190 LValue::MakeAddr(CastPtr, Qualifiers())); 191 break; 192 } 193 194 // FIXME: Remove the CK_Unknown check here. 195 case CastExpr::CK_Unknown: 196 case CastExpr::CK_NoOp: 197 case CastExpr::CK_UserDefinedConversion: 198 case CastExpr::CK_ConstructorConversion: 199 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 200 E->getType()) && 201 "Implicit cast types must be compatible"); 202 Visit(E->getSubExpr()); 203 break; 204 205 case CastExpr::CK_NullToMemberPointer: { 206 const llvm::Type *PtrDiffTy = 207 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 208 209 llvm::Value *NullValue = llvm::Constant::getNullValue(PtrDiffTy); 210 llvm::Value *Ptr = Builder.CreateStructGEP(DestPtr, 0, "ptr"); 211 Builder.CreateStore(NullValue, Ptr, VolatileDest); 212 213 llvm::Value *Adj = Builder.CreateStructGEP(DestPtr, 1, "adj"); 214 Builder.CreateStore(NullValue, Adj, VolatileDest); 215 216 break; 217 } 218 219 case CastExpr::CK_BitCast: { 220 // This must be a member function pointer cast. 221 Visit(E->getSubExpr()); 222 break; 223 } 224 225 case CastExpr::CK_DerivedToBaseMemberPointer: 226 case CastExpr::CK_BaseToDerivedMemberPointer: { 227 QualType SrcType = E->getSubExpr()->getType(); 228 229 llvm::Value *Src = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(SrcType), 230 "tmp"); 231 CGF.EmitAggExpr(E->getSubExpr(), Src, SrcType.isVolatileQualified()); 232 233 llvm::Value *SrcPtr = Builder.CreateStructGEP(Src, 0, "src.ptr"); 234 SrcPtr = Builder.CreateLoad(SrcPtr); 235 236 llvm::Value *SrcAdj = Builder.CreateStructGEP(Src, 1, "src.adj"); 237 SrcAdj = Builder.CreateLoad(SrcAdj); 238 239 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 240 Builder.CreateStore(SrcPtr, DstPtr, VolatileDest); 241 242 llvm::Value *DstAdj = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 243 244 // Now See if we need to update the adjustment. 245 const CXXRecordDecl *BaseDecl = 246 cast<CXXRecordDecl>(SrcType->getAs<MemberPointerType>()-> 247 getClass()->getAs<RecordType>()->getDecl()); 248 const CXXRecordDecl *DerivedDecl = 249 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()-> 250 getClass()->getAs<RecordType>()->getDecl()); 251 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 252 std::swap(DerivedDecl, BaseDecl); 253 254 llvm::Constant *Adj = CGF.CGM.GetCXXBaseClassOffset(DerivedDecl, BaseDecl); 255 if (Adj) { 256 if (E->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer) 257 SrcAdj = Builder.CreateSub(SrcAdj, Adj, "adj"); 258 else 259 SrcAdj = Builder.CreateAdd(SrcAdj, Adj, "adj"); 260 } 261 262 Builder.CreateStore(SrcAdj, DstAdj, VolatileDest); 263 break; 264 } 265 } 266 } 267 268 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 269 if (E->getCallReturnType()->isReferenceType()) { 270 EmitAggLoadOfLValue(E); 271 return; 272 } 273 274 RValue RV = CGF.EmitCallExpr(E); 275 EmitFinalDestCopy(E, RV); 276 } 277 278 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 279 RValue RV = CGF.EmitObjCMessageExpr(E); 280 EmitFinalDestCopy(E, RV); 281 } 282 283 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 284 RValue RV = CGF.EmitObjCPropertyGet(E); 285 EmitFinalDestCopy(E, RV); 286 } 287 288 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr( 289 ObjCImplicitSetterGetterRefExpr *E) { 290 RValue RV = CGF.EmitObjCPropertyGet(E); 291 EmitFinalDestCopy(E, RV); 292 } 293 294 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 295 CGF.EmitAnyExpr(E->getLHS(), 0, false, true); 296 CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest, 297 /*IgnoreResult=*/false, IsInitializer); 298 } 299 300 void AggExprEmitter::VisitUnaryAddrOf(const UnaryOperator *E) { 301 // We have a member function pointer. 302 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>(); 303 (void) MPT; 304 assert(MPT->getPointeeType()->isFunctionProtoType() && 305 "Unexpected member pointer type!"); 306 307 const DeclRefExpr *DRE = cast<DeclRefExpr>(E->getSubExpr()); 308 const CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 309 310 const llvm::Type *PtrDiffTy = 311 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 312 313 llvm::Value *DstPtr = Builder.CreateStructGEP(DestPtr, 0, "dst.ptr"); 314 llvm::Value *FuncPtr; 315 316 if (MD->isVirtual()) { 317 int64_t Index = 318 CGF.CGM.getVtableInfo().getMethodVtableIndex(MD); 319 320 FuncPtr = llvm::ConstantInt::get(PtrDiffTy, Index + 1); 321 } else { 322 FuncPtr = llvm::ConstantExpr::getPtrToInt(CGF.CGM.GetAddrOfFunction(MD), 323 PtrDiffTy); 324 } 325 Builder.CreateStore(FuncPtr, DstPtr, VolatileDest); 326 327 llvm::Value *AdjPtr = Builder.CreateStructGEP(DestPtr, 1, "dst.adj"); 328 329 // The adjustment will always be 0. 330 Builder.CreateStore(llvm::ConstantInt::get(PtrDiffTy, 0), AdjPtr, 331 VolatileDest); 332 } 333 334 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 335 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 336 } 337 338 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 339 if (E->getOpcode() == BinaryOperator::PtrMemD || 340 E->getOpcode() == BinaryOperator::PtrMemI) 341 VisitPointerToDataMemberBinaryOperator(E); 342 else 343 CGF.ErrorUnsupported(E, "aggregate binary expression"); 344 } 345 346 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 347 const BinaryOperator *E) { 348 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 349 EmitFinalDestCopy(E, LV); 350 } 351 352 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 353 // For an assignment to work, the value on the right has 354 // to be compatible with the value on the left. 355 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 356 E->getRHS()->getType()) 357 && "Invalid assignment"); 358 LValue LHS = CGF.EmitLValue(E->getLHS()); 359 360 // We have to special case property setters, otherwise we must have 361 // a simple lvalue (no aggregates inside vectors, bitfields). 362 if (LHS.isPropertyRef()) { 363 llvm::Value *AggLoc = DestPtr; 364 if (!AggLoc) 365 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 366 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 367 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 368 RValue::getAggregate(AggLoc, VolatileDest)); 369 } else if (LHS.isKVCRef()) { 370 llvm::Value *AggLoc = DestPtr; 371 if (!AggLoc) 372 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 373 CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest); 374 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 375 RValue::getAggregate(AggLoc, VolatileDest)); 376 } else { 377 bool RequiresGCollection = false; 378 if (CGF.getContext().getLangOptions().NeXTRuntime) { 379 QualType LHSTy = E->getLHS()->getType(); 380 if (const RecordType *FDTTy = LHSTy.getTypePtr()->getAs<RecordType>()) 381 RequiresGCollection = FDTTy->getDecl()->hasObjectMember(); 382 } 383 // Codegen the RHS so that it stores directly into the LHS. 384 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(), 385 false, false, RequiresGCollection); 386 EmitFinalDestCopy(E, LHS, true); 387 } 388 } 389 390 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 391 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 392 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 393 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 394 395 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 396 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 397 398 CGF.StartConditionalBranch(); 399 CGF.EmitBlock(LHSBlock); 400 401 // Handle the GNU extension for missing LHS. 402 assert(E->getLHS() && "Must have LHS for aggregate value"); 403 404 Visit(E->getLHS()); 405 CGF.FinishConditionalBranch(); 406 CGF.EmitBranch(ContBlock); 407 408 CGF.StartConditionalBranch(); 409 CGF.EmitBlock(RHSBlock); 410 411 Visit(E->getRHS()); 412 CGF.FinishConditionalBranch(); 413 CGF.EmitBranch(ContBlock); 414 415 CGF.EmitBlock(ContBlock); 416 } 417 418 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 419 Visit(CE->getChosenSubExpr(CGF.getContext())); 420 } 421 422 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 423 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 424 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 425 426 if (!ArgPtr) { 427 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 428 return; 429 } 430 431 EmitFinalDestCopy(VE, LValue::MakeAddr(ArgPtr, Qualifiers())); 432 } 433 434 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 435 llvm::Value *Val = DestPtr; 436 437 if (!Val) { 438 // Create a temporary variable. 439 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 440 441 // FIXME: volatile 442 CGF.EmitAggExpr(E->getSubExpr(), Val, false); 443 } else 444 Visit(E->getSubExpr()); 445 446 // Don't make this a live temporary if we're emitting an initializer expr. 447 if (!IsInitializer) 448 CGF.PushCXXTemporary(E->getTemporary(), Val); 449 } 450 451 void 452 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 453 llvm::Value *Val = DestPtr; 454 455 if (!Val) { 456 // Create a temporary variable. 457 Val = CGF.CreateTempAlloca(CGF.ConvertTypeForMem(E->getType()), "tmp"); 458 } 459 460 CGF.EmitCXXConstructExpr(Val, E); 461 } 462 463 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) { 464 CGF.EmitCXXExprWithTemporaries(E, DestPtr, VolatileDest, IsInitializer); 465 } 466 467 void AggExprEmitter::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) { 468 LValue lvalue = LValue::MakeAddr(DestPtr, Qualifiers()); 469 EmitNullInitializationToLValue(lvalue, E->getType()); 470 } 471 472 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 473 // FIXME: Ignore result? 474 // FIXME: Are initializers affected by volatile? 475 if (isa<ImplicitValueInitExpr>(E)) { 476 EmitNullInitializationToLValue(LV, E->getType()); 477 } else if (E->getType()->isComplexType()) { 478 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 479 } else if (CGF.hasAggregateLLVMType(E->getType())) { 480 CGF.EmitAnyExpr(E, LV.getAddress(), false); 481 } else { 482 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 483 } 484 } 485 486 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 487 if (!CGF.hasAggregateLLVMType(T)) { 488 // For non-aggregates, we can store zero 489 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 490 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 491 } else { 492 // Otherwise, just memset the whole thing to zero. This is legal 493 // because in LLVM, all default initializers are guaranteed to have a 494 // bit pattern of all zeros. 495 // FIXME: That isn't true for member pointers! 496 // There's a potential optimization opportunity in combining 497 // memsets; that would be easy for arrays, but relatively 498 // difficult for structures with the current code. 499 CGF.EmitMemSetToZero(LV.getAddress(), T); 500 } 501 } 502 503 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 504 #if 0 505 // FIXME: Disabled while we figure out what to do about 506 // test/CodeGen/bitfield.c 507 // 508 // If we can, prefer a copy from a global; this is a lot less code for long 509 // globals, and it's easier for the current optimizers to analyze. 510 // FIXME: Should we really be doing this? Should we try to avoid cases where 511 // we emit a global with a lot of zeros? Should we try to avoid short 512 // globals? 513 if (E->isConstantInitializer(CGF.getContext(), 0)) { 514 llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF); 515 llvm::GlobalVariable* GV = 516 new llvm::GlobalVariable(C->getType(), true, 517 llvm::GlobalValue::InternalLinkage, 518 C, "", &CGF.CGM.getModule(), 0); 519 EmitFinalDestCopy(E, LValue::MakeAddr(GV, 0)); 520 return; 521 } 522 #endif 523 if (E->hadArrayRangeDesignator()) { 524 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 525 } 526 527 // Handle initialization of an array. 528 if (E->getType()->isArrayType()) { 529 const llvm::PointerType *APType = 530 cast<llvm::PointerType>(DestPtr->getType()); 531 const llvm::ArrayType *AType = 532 cast<llvm::ArrayType>(APType->getElementType()); 533 534 uint64_t NumInitElements = E->getNumInits(); 535 536 if (E->getNumInits() > 0) { 537 QualType T1 = E->getType(); 538 QualType T2 = E->getInit(0)->getType(); 539 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 540 EmitAggLoadOfLValue(E->getInit(0)); 541 return; 542 } 543 } 544 545 uint64_t NumArrayElements = AType->getNumElements(); 546 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 547 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 548 549 // FIXME: were we intentionally ignoring address spaces and GC attributes? 550 Qualifiers Quals = CGF.MakeQualifiers(ElementType); 551 552 for (uint64_t i = 0; i != NumArrayElements; ++i) { 553 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 554 if (i < NumInitElements) 555 EmitInitializationToLValue(E->getInit(i), 556 LValue::MakeAddr(NextVal, Quals)); 557 else 558 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, Quals), 559 ElementType); 560 } 561 return; 562 } 563 564 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 565 566 // Do struct initialization; this code just sets each individual member 567 // to the approprate value. This makes bitfield support automatic; 568 // the disadvantage is that the generated code is more difficult for 569 // the optimizer, especially with bitfields. 570 unsigned NumInitElements = E->getNumInits(); 571 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 572 unsigned CurInitVal = 0; 573 574 if (E->getType()->isUnionType()) { 575 // Only initialize one field of a union. The field itself is 576 // specified by the initializer list. 577 if (!E->getInitializedFieldInUnion()) { 578 // Empty union; we have nothing to do. 579 580 #ifndef NDEBUG 581 // Make sure that it's really an empty and not a failure of 582 // semantic analysis. 583 for (RecordDecl::field_iterator Field = SD->field_begin(), 584 FieldEnd = SD->field_end(); 585 Field != FieldEnd; ++Field) 586 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 587 #endif 588 return; 589 } 590 591 // FIXME: volatility 592 FieldDecl *Field = E->getInitializedFieldInUnion(); 593 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0); 594 595 if (NumInitElements) { 596 // Store the initializer into the field 597 EmitInitializationToLValue(E->getInit(0), FieldLoc); 598 } else { 599 // Default-initialize to null 600 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 601 } 602 603 return; 604 } 605 606 // Here we iterate over the fields; this makes it simpler to both 607 // default-initialize fields and skip over unnamed fields. 608 for (RecordDecl::field_iterator Field = SD->field_begin(), 609 FieldEnd = SD->field_end(); 610 Field != FieldEnd; ++Field) { 611 // We're done once we hit the flexible array member 612 if (Field->getType()->isIncompleteArrayType()) 613 break; 614 615 if (Field->isUnnamedBitfield()) 616 continue; 617 618 // FIXME: volatility 619 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0); 620 // We never generate write-barries for initialized fields. 621 LValue::SetObjCNonGC(FieldLoc, true); 622 if (CurInitVal < NumInitElements) { 623 // Store the initializer into the field 624 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 625 } else { 626 // We're out of initalizers; default-initialize to null 627 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 628 } 629 } 630 } 631 632 //===----------------------------------------------------------------------===// 633 // Entry Points into this File 634 //===----------------------------------------------------------------------===// 635 636 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 637 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 638 /// the value of the aggregate expression is not needed. If VolatileDest is 639 /// true, DestPtr cannot be 0. 640 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 641 bool VolatileDest, bool IgnoreResult, 642 bool IsInitializer, 643 bool RequiresGCollection) { 644 assert(E && hasAggregateLLVMType(E->getType()) && 645 "Invalid aggregate expression to emit"); 646 assert ((DestPtr != 0 || VolatileDest == false) 647 && "volatile aggregate can't be 0"); 648 649 AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer, 650 RequiresGCollection) 651 .Visit(const_cast<Expr*>(E)); 652 } 653 654 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 655 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 656 657 EmitMemSetToZero(DestPtr, Ty); 658 } 659 660 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 661 llvm::Value *SrcPtr, QualType Ty, 662 bool isVolatile) { 663 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 664 665 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 666 // C99 6.5.16.1p3, which states "If the value being stored in an object is 667 // read from another object that overlaps in anyway the storage of the first 668 // object, then the overlap shall be exact and the two objects shall have 669 // qualified or unqualified versions of a compatible type." 670 // 671 // memcpy is not defined if the source and destination pointers are exactly 672 // equal, but other compilers do this optimization, and almost every memcpy 673 // implementation handles this case safely. If there is a libc that does not 674 // safely handle this, we can add a target hook. 675 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext); 676 if (DestPtr->getType() != BP) 677 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 678 if (SrcPtr->getType() != BP) 679 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 680 681 // Get size and alignment info for this aggregate. 682 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 683 684 // FIXME: Handle variable sized types. 685 const llvm::Type *IntPtr = 686 llvm::IntegerType::get(VMContext, LLVMPointerWidth); 687 688 // FIXME: If we have a volatile struct, the optimizer can remove what might 689 // appear to be `extra' memory ops: 690 // 691 // volatile struct { int i; } a, b; 692 // 693 // int main() { 694 // a = b; 695 // a = b; 696 // } 697 // 698 // we need to use a differnt call here. We use isVolatile to indicate when 699 // either the source or the destination is volatile. 700 Builder.CreateCall4(CGM.getMemCpyFn(), 701 DestPtr, SrcPtr, 702 // TypeInfo.first describes size in bits. 703 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 704 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 705 TypeInfo.second/8)); 706 } 707