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 AggValueSlot Dest; 36 bool IgnoreResult; 37 38 /// We want to use 'dest' as the return slot except under two 39 /// conditions: 40 /// - The destination slot requires garbage collection, so we 41 /// need to use the GC API. 42 /// - The destination slot is potentially aliased. 43 bool shouldUseDestForReturnSlot() const { 44 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased()); 45 } 46 47 ReturnValueSlot getReturnValueSlot() const { 48 if (!shouldUseDestForReturnSlot()) 49 return ReturnValueSlot(); 50 51 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile()); 52 } 53 54 AggValueSlot EnsureSlot(QualType T) { 55 if (!Dest.isIgnored()) return Dest; 56 return CGF.CreateAggTemp(T, "agg.tmp.ensured"); 57 } 58 59 public: 60 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, 61 bool ignore) 62 : CGF(cgf), Builder(CGF.Builder), Dest(Dest), 63 IgnoreResult(ignore) { 64 } 65 66 //===--------------------------------------------------------------------===// 67 // Utilities 68 //===--------------------------------------------------------------------===// 69 70 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 71 /// represents a value lvalue, this method emits the address of the lvalue, 72 /// then loads the result into DestPtr. 73 void EmitAggLoadOfLValue(const Expr *E); 74 75 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 76 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 77 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 78 79 void EmitMoveFromReturnSlot(const Expr *E, RValue Src); 80 81 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) { 82 if (CGF.getLangOptions().getGC() && TypeRequiresGCollection(T)) 83 return AggValueSlot::NeedsGCBarriers; 84 return AggValueSlot::DoesNotNeedGCBarriers; 85 } 86 87 bool TypeRequiresGCollection(QualType T); 88 89 //===--------------------------------------------------------------------===// 90 // Visitor Methods 91 //===--------------------------------------------------------------------===// 92 93 void VisitStmt(Stmt *S) { 94 CGF.ErrorUnsupported(S, "aggregate expression"); 95 } 96 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 97 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 98 Visit(GE->getResultExpr()); 99 } 100 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 101 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) { 102 return Visit(E->getReplacement()); 103 } 104 105 // l-values. 106 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 107 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 108 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 109 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 110 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 111 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 112 EmitAggLoadOfLValue(E); 113 } 114 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 115 EmitAggLoadOfLValue(E); 116 } 117 void VisitPredefinedExpr(const PredefinedExpr *E) { 118 EmitAggLoadOfLValue(E); 119 } 120 121 // Operators. 122 void VisitCastExpr(CastExpr *E); 123 void VisitCallExpr(const CallExpr *E); 124 void VisitStmtExpr(const StmtExpr *E); 125 void VisitBinaryOperator(const BinaryOperator *BO); 126 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 127 void VisitBinAssign(const BinaryOperator *E); 128 void VisitBinComma(const BinaryOperator *E); 129 130 void VisitObjCMessageExpr(ObjCMessageExpr *E); 131 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 132 EmitAggLoadOfLValue(E); 133 } 134 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 135 136 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO); 137 void VisitChooseExpr(const ChooseExpr *CE); 138 void VisitInitListExpr(InitListExpr *E); 139 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 140 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 141 Visit(DAE->getExpr()); 142 } 143 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 144 void VisitCXXConstructExpr(const CXXConstructExpr *E); 145 void VisitExprWithCleanups(ExprWithCleanups *E); 146 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 147 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 148 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 149 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 150 151 void VisitPseudoObjectExpr(PseudoObjectExpr *E) { 152 if (E->isGLValue()) { 153 LValue LV = CGF.EmitPseudoObjectLValue(E); 154 return EmitFinalDestCopy(E, LV); 155 } 156 157 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType())); 158 } 159 160 void VisitVAArgExpr(VAArgExpr *E); 161 162 void EmitInitializationToLValue(Expr *E, LValue Address); 163 void EmitNullInitializationToLValue(LValue Address); 164 // case Expr::ChooseExprClass: 165 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 166 void VisitAtomicExpr(AtomicExpr *E) { 167 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr()); 168 } 169 }; 170 } // end anonymous namespace. 171 172 //===----------------------------------------------------------------------===// 173 // Utilities 174 //===----------------------------------------------------------------------===// 175 176 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 177 /// represents a value lvalue, this method emits the address of the lvalue, 178 /// then loads the result into DestPtr. 179 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 180 LValue LV = CGF.EmitLValue(E); 181 EmitFinalDestCopy(E, LV); 182 } 183 184 /// \brief True if the given aggregate type requires special GC API calls. 185 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 186 // Only record types have members that might require garbage collection. 187 const RecordType *RecordTy = T->getAs<RecordType>(); 188 if (!RecordTy) return false; 189 190 // Don't mess with non-trivial C++ types. 191 RecordDecl *Record = RecordTy->getDecl(); 192 if (isa<CXXRecordDecl>(Record) && 193 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() || 194 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 195 return false; 196 197 // Check whether the type has an object member. 198 return Record->hasObjectMember(); 199 } 200 201 /// \brief Perform the final move to DestPtr if for some reason 202 /// getReturnValueSlot() didn't use it directly. 203 /// 204 /// The idea is that you do something like this: 205 /// RValue Result = EmitSomething(..., getReturnValueSlot()); 206 /// EmitMoveFromReturnSlot(E, Result); 207 /// 208 /// If nothing interferes, this will cause the result to be emitted 209 /// directly into the return value slot. Otherwise, a final move 210 /// will be performed. 211 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) { 212 if (shouldUseDestForReturnSlot()) { 213 // Logically, Dest.getAddr() should equal Src.getAggregateAddr(). 214 // The possibility of undef rvalues complicates that a lot, 215 // though, so we can't really assert. 216 return; 217 } 218 219 // Otherwise, do a final copy, 220 assert(Dest.getAddr() != Src.getAggregateAddr()); 221 EmitFinalDestCopy(E, Src, /*Ignore*/ true); 222 } 223 224 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 225 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 226 assert(Src.isAggregate() && "value must be aggregate value!"); 227 228 // If Dest is ignored, then we're evaluating an aggregate expression 229 // in a context (like an expression statement) that doesn't care 230 // about the result. C says that an lvalue-to-rvalue conversion is 231 // performed in these cases; C++ says that it is not. In either 232 // case, we don't actually need to do anything unless the value is 233 // volatile. 234 if (Dest.isIgnored()) { 235 if (!Src.isVolatileQualified() || 236 CGF.CGM.getLangOptions().CPlusPlus || 237 (IgnoreResult && Ignore)) 238 return; 239 240 // If the source is volatile, we must read from it; to do that, we need 241 // some place to put it. 242 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp"); 243 } 244 245 if (Dest.requiresGCollection()) { 246 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType()); 247 llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 248 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity()); 249 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 250 Dest.getAddr(), 251 Src.getAggregateAddr(), 252 SizeVal); 253 return; 254 } 255 // If the result of the assignment is used, copy the LHS there also. 256 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 257 // from the source as well, as we can't eliminate it if either operand 258 // is volatile, unless copy has volatile for both source and destination.. 259 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(), 260 Dest.isVolatile()|Src.isVolatileQualified()); 261 } 262 263 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 264 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 265 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 266 267 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 268 Src.isVolatileQualified()), 269 Ignore); 270 } 271 272 //===----------------------------------------------------------------------===// 273 // Visitor Methods 274 //===----------------------------------------------------------------------===// 275 276 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){ 277 Visit(E->GetTemporaryExpr()); 278 } 279 280 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 281 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e)); 282 } 283 284 void 285 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 286 if (E->getType().isPODType(CGF.getContext())) { 287 // For a POD type, just emit a load of the lvalue + a copy, because our 288 // compound literal might alias the destination. 289 // FIXME: This is a band-aid; the real problem appears to be in our handling 290 // of assignments, where we store directly into the LHS without checking 291 // whether anything in the RHS aliases. 292 EmitAggLoadOfLValue(E); 293 return; 294 } 295 296 AggValueSlot Slot = EnsureSlot(E->getType()); 297 CGF.EmitAggExpr(E->getInitializer(), Slot); 298 } 299 300 301 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 302 switch (E->getCastKind()) { 303 case CK_Dynamic: { 304 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 305 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 306 // FIXME: Do we also need to handle property references here? 307 if (LV.isSimple()) 308 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 309 else 310 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 311 312 if (!Dest.isIgnored()) 313 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 314 break; 315 } 316 317 case CK_ToUnion: { 318 if (Dest.isIgnored()) break; 319 320 // GCC union extension 321 QualType Ty = E->getSubExpr()->getType(); 322 QualType PtrTy = CGF.getContext().getPointerType(Ty); 323 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(), 324 CGF.ConvertType(PtrTy)); 325 EmitInitializationToLValue(E->getSubExpr(), 326 CGF.MakeAddrLValue(CastPtr, Ty)); 327 break; 328 } 329 330 case CK_DerivedToBase: 331 case CK_BaseToDerived: 332 case CK_UncheckedDerivedToBase: { 333 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: " 334 "should have been unpacked before we got here"); 335 } 336 337 case CK_GetObjCProperty: { 338 LValue LV = 339 CGF.EmitObjCPropertyRefLValue(E->getSubExpr()->getObjCProperty()); 340 assert(LV.isPropertyRef()); 341 RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot()); 342 EmitMoveFromReturnSlot(E, RV); 343 break; 344 } 345 346 case CK_LValueToRValue: // hope for downstream optimization 347 case CK_NoOp: 348 case CK_UserDefinedConversion: 349 case CK_ConstructorConversion: 350 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 351 E->getType()) && 352 "Implicit cast types must be compatible"); 353 Visit(E->getSubExpr()); 354 break; 355 356 case CK_LValueBitCast: 357 llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); 358 break; 359 360 case CK_Dependent: 361 case CK_BitCast: 362 case CK_ArrayToPointerDecay: 363 case CK_FunctionToPointerDecay: 364 case CK_NullToPointer: 365 case CK_NullToMemberPointer: 366 case CK_BaseToDerivedMemberPointer: 367 case CK_DerivedToBaseMemberPointer: 368 case CK_MemberPointerToBoolean: 369 case CK_IntegralToPointer: 370 case CK_PointerToIntegral: 371 case CK_PointerToBoolean: 372 case CK_ToVoid: 373 case CK_VectorSplat: 374 case CK_IntegralCast: 375 case CK_IntegralToBoolean: 376 case CK_IntegralToFloating: 377 case CK_FloatingToIntegral: 378 case CK_FloatingToBoolean: 379 case CK_FloatingCast: 380 case CK_CPointerToObjCPointerCast: 381 case CK_BlockPointerToObjCPointerCast: 382 case CK_AnyPointerToBlockPointerCast: 383 case CK_ObjCObjectLValueCast: 384 case CK_FloatingRealToComplex: 385 case CK_FloatingComplexToReal: 386 case CK_FloatingComplexToBoolean: 387 case CK_FloatingComplexCast: 388 case CK_FloatingComplexToIntegralComplex: 389 case CK_IntegralRealToComplex: 390 case CK_IntegralComplexToReal: 391 case CK_IntegralComplexToBoolean: 392 case CK_IntegralComplexCast: 393 case CK_IntegralComplexToFloatingComplex: 394 case CK_ARCProduceObject: 395 case CK_ARCConsumeObject: 396 case CK_ARCReclaimReturnedObject: 397 case CK_ARCExtendBlockObject: 398 llvm_unreachable("cast kind invalid for aggregate types"); 399 } 400 } 401 402 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 403 if (E->getCallReturnType()->isReferenceType()) { 404 EmitAggLoadOfLValue(E); 405 return; 406 } 407 408 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot()); 409 EmitMoveFromReturnSlot(E, RV); 410 } 411 412 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 413 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 414 EmitMoveFromReturnSlot(E, RV); 415 } 416 417 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 418 llvm_unreachable("direct property access not surrounded by " 419 "lvalue-to-rvalue cast"); 420 } 421 422 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 423 CGF.EmitIgnoredExpr(E->getLHS()); 424 Visit(E->getRHS()); 425 } 426 427 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 428 CodeGenFunction::StmtExprEvaluation eval(CGF); 429 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest); 430 } 431 432 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 433 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI) 434 VisitPointerToDataMemberBinaryOperator(E); 435 else 436 CGF.ErrorUnsupported(E, "aggregate binary expression"); 437 } 438 439 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 440 const BinaryOperator *E) { 441 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 442 EmitFinalDestCopy(E, LV); 443 } 444 445 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 446 // For an assignment to work, the value on the right has 447 // to be compatible with the value on the left. 448 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 449 E->getRHS()->getType()) 450 && "Invalid assignment"); 451 452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS())) 453 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) 454 if (VD->hasAttr<BlocksAttr>() && 455 E->getRHS()->HasSideEffects(CGF.getContext())) { 456 // When __block variable on LHS, the RHS must be evaluated first 457 // as it may change the 'forwarding' field via call to Block_copy. 458 LValue RHS = CGF.EmitLValue(E->getRHS()); 459 LValue LHS = CGF.EmitLValue(E->getLHS()); 460 Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, 461 needsGC(E->getLHS()->getType()), 462 AggValueSlot::IsAliased); 463 EmitFinalDestCopy(E, RHS, true); 464 return; 465 } 466 467 LValue LHS = CGF.EmitLValue(E->getLHS()); 468 469 // We have to special case property setters, otherwise we must have 470 // a simple lvalue (no aggregates inside vectors, bitfields). 471 if (LHS.isPropertyRef()) { 472 const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr(); 473 QualType ArgType = RE->getSetterArgType(); 474 RValue Src; 475 if (ArgType->isReferenceType()) 476 Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0); 477 else { 478 AggValueSlot Slot = EnsureSlot(E->getRHS()->getType()); 479 CGF.EmitAggExpr(E->getRHS(), Slot); 480 Src = Slot.asRValue(); 481 } 482 CGF.EmitStoreThroughPropertyRefLValue(Src, LHS); 483 } else { 484 // Codegen the RHS so that it stores directly into the LHS. 485 AggValueSlot LHSSlot = 486 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, 487 needsGC(E->getLHS()->getType()), 488 AggValueSlot::IsAliased); 489 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false); 490 EmitFinalDestCopy(E, LHS, true); 491 } 492 } 493 494 void AggExprEmitter:: 495 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 496 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 497 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 498 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 499 500 // Bind the common expression if necessary. 501 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 502 503 CodeGenFunction::ConditionalEvaluation eval(CGF); 504 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 505 506 // Save whether the destination's lifetime is externally managed. 507 bool isExternallyDestructed = Dest.isExternallyDestructed(); 508 509 eval.begin(CGF); 510 CGF.EmitBlock(LHSBlock); 511 Visit(E->getTrueExpr()); 512 eval.end(CGF); 513 514 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!"); 515 CGF.Builder.CreateBr(ContBlock); 516 517 // If the result of an agg expression is unused, then the emission 518 // of the LHS might need to create a destination slot. That's fine 519 // with us, and we can safely emit the RHS into the same slot, but 520 // we shouldn't claim that it's already being destructed. 521 Dest.setExternallyDestructed(isExternallyDestructed); 522 523 eval.begin(CGF); 524 CGF.EmitBlock(RHSBlock); 525 Visit(E->getFalseExpr()); 526 eval.end(CGF); 527 528 CGF.EmitBlock(ContBlock); 529 } 530 531 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 532 Visit(CE->getChosenSubExpr(CGF.getContext())); 533 } 534 535 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 536 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 537 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 538 539 if (!ArgPtr) { 540 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 541 return; 542 } 543 544 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType())); 545 } 546 547 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 548 // Ensure that we have a slot, but if we already do, remember 549 // whether it was externally destructed. 550 bool wasExternallyDestructed = Dest.isExternallyDestructed(); 551 Dest = EnsureSlot(E->getType()); 552 553 // We're going to push a destructor if there isn't already one. 554 Dest.setExternallyDestructed(); 555 556 Visit(E->getSubExpr()); 557 558 // Push that destructor we promised. 559 if (!wasExternallyDestructed) 560 CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr()); 561 } 562 563 void 564 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 565 AggValueSlot Slot = EnsureSlot(E->getType()); 566 CGF.EmitCXXConstructExpr(E, Slot); 567 } 568 569 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 570 CGF.EmitExprWithCleanups(E, Dest); 571 } 572 573 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 574 QualType T = E->getType(); 575 AggValueSlot Slot = EnsureSlot(T); 576 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T)); 577 } 578 579 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 580 QualType T = E->getType(); 581 AggValueSlot Slot = EnsureSlot(T); 582 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T)); 583 } 584 585 /// isSimpleZero - If emitting this value will obviously just cause a store of 586 /// zero to memory, return true. This can return false if uncertain, so it just 587 /// handles simple cases. 588 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { 589 E = E->IgnoreParens(); 590 591 // 0 592 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) 593 return IL->getValue() == 0; 594 // +0.0 595 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) 596 return FL->getValue().isPosZero(); 597 // int() 598 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) && 599 CGF.getTypes().isZeroInitializable(E->getType())) 600 return true; 601 // (int*)0 - Null pointer expressions. 602 if (const CastExpr *ICE = dyn_cast<CastExpr>(E)) 603 return ICE->getCastKind() == CK_NullToPointer; 604 // '\0' 605 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) 606 return CL->getValue() == 0; 607 608 // Otherwise, hard case: conservatively return false. 609 return false; 610 } 611 612 613 void 614 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 615 QualType type = LV.getType(); 616 // FIXME: Ignore result? 617 // FIXME: Are initializers affected by volatile? 618 if (Dest.isZeroed() && isSimpleZero(E, CGF)) { 619 // Storing "i32 0" to a zero'd memory location is a noop. 620 } else if (isa<ImplicitValueInitExpr>(E)) { 621 EmitNullInitializationToLValue(LV); 622 } else if (type->isReferenceType()) { 623 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 624 CGF.EmitStoreThroughLValue(RV, LV); 625 } else if (type->isAnyComplexType()) { 626 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 627 } else if (CGF.hasAggregateLLVMType(type)) { 628 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV, 629 AggValueSlot::IsDestructed, 630 AggValueSlot::DoesNotNeedGCBarriers, 631 AggValueSlot::IsNotAliased, 632 Dest.isZeroed())); 633 } else if (LV.isSimple()) { 634 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false); 635 } else { 636 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV); 637 } 638 } 639 640 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) { 641 QualType type = lv.getType(); 642 643 // If the destination slot is already zeroed out before the aggregate is 644 // copied into it, we don't have to emit any zeros here. 645 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type)) 646 return; 647 648 if (!CGF.hasAggregateLLVMType(type)) { 649 // For non-aggregates, we can store zero 650 llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type)); 651 CGF.EmitStoreThroughLValue(RValue::get(null), lv); 652 } else { 653 // There's a potential optimization opportunity in combining 654 // memsets; that would be easy for arrays, but relatively 655 // difficult for structures with the current code. 656 CGF.EmitNullInitialization(lv.getAddress(), lv.getType()); 657 } 658 } 659 660 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 661 #if 0 662 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 663 // (Length of globals? Chunks of zeroed-out space?). 664 // 665 // If we can, prefer a copy from a global; this is a lot less code for long 666 // globals, and it's easier for the current optimizers to analyze. 667 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 668 llvm::GlobalVariable* GV = 669 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 670 llvm::GlobalValue::InternalLinkage, C, ""); 671 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType())); 672 return; 673 } 674 #endif 675 if (E->hadArrayRangeDesignator()) 676 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 677 678 llvm::Value *DestPtr = Dest.getAddr(); 679 680 // Handle initialization of an array. 681 if (E->getType()->isArrayType()) { 682 llvm::PointerType *APType = 683 cast<llvm::PointerType>(DestPtr->getType()); 684 llvm::ArrayType *AType = 685 cast<llvm::ArrayType>(APType->getElementType()); 686 687 uint64_t NumInitElements = E->getNumInits(); 688 689 if (E->getNumInits() > 0) { 690 QualType T1 = E->getType(); 691 QualType T2 = E->getInit(0)->getType(); 692 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 693 EmitAggLoadOfLValue(E->getInit(0)); 694 return; 695 } 696 } 697 698 uint64_t NumArrayElements = AType->getNumElements(); 699 assert(NumInitElements <= NumArrayElements); 700 701 QualType elementType = E->getType().getCanonicalType(); 702 elementType = CGF.getContext().getQualifiedType( 703 cast<ArrayType>(elementType)->getElementType(), 704 elementType.getQualifiers() + Dest.getQualifiers()); 705 706 // DestPtr is an array*. Construct an elementType* by drilling 707 // down a level. 708 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 709 llvm::Value *indices[] = { zero, zero }; 710 llvm::Value *begin = 711 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin"); 712 713 // Exception safety requires us to destroy all the 714 // already-constructed members if an initializer throws. 715 // For that, we'll need an EH cleanup. 716 QualType::DestructionKind dtorKind = elementType.isDestructedType(); 717 llvm::AllocaInst *endOfInit = 0; 718 EHScopeStack::stable_iterator cleanup; 719 if (CGF.needsEHCleanup(dtorKind)) { 720 // In principle we could tell the cleanup where we are more 721 // directly, but the control flow can get so varied here that it 722 // would actually be quite complex. Therefore we go through an 723 // alloca. 724 endOfInit = CGF.CreateTempAlloca(begin->getType(), 725 "arrayinit.endOfInit"); 726 Builder.CreateStore(begin, endOfInit); 727 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType, 728 CGF.getDestroyer(dtorKind)); 729 cleanup = CGF.EHStack.stable_begin(); 730 731 // Otherwise, remember that we didn't need a cleanup. 732 } else { 733 dtorKind = QualType::DK_none; 734 } 735 736 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1); 737 738 // The 'current element to initialize'. The invariants on this 739 // variable are complicated. Essentially, after each iteration of 740 // the loop, it points to the last initialized element, except 741 // that it points to the beginning of the array before any 742 // elements have been initialized. 743 llvm::Value *element = begin; 744 745 // Emit the explicit initializers. 746 for (uint64_t i = 0; i != NumInitElements; ++i) { 747 // Advance to the next element. 748 if (i > 0) { 749 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element"); 750 751 // Tell the cleanup that it needs to destroy up to this 752 // element. TODO: some of these stores can be trivially 753 // observed to be unnecessary. 754 if (endOfInit) Builder.CreateStore(element, endOfInit); 755 } 756 757 LValue elementLV = CGF.MakeAddrLValue(element, elementType); 758 EmitInitializationToLValue(E->getInit(i), elementLV); 759 } 760 761 // Check whether there's a non-trivial array-fill expression. 762 // Note that this will be a CXXConstructExpr even if the element 763 // type is an array (or array of array, etc.) of class type. 764 Expr *filler = E->getArrayFiller(); 765 bool hasTrivialFiller = true; 766 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) { 767 assert(cons->getConstructor()->isDefaultConstructor()); 768 hasTrivialFiller = cons->getConstructor()->isTrivial(); 769 } 770 771 // Any remaining elements need to be zero-initialized, possibly 772 // using the filler expression. We can skip this if the we're 773 // emitting to zeroed memory. 774 if (NumInitElements != NumArrayElements && 775 !(Dest.isZeroed() && hasTrivialFiller && 776 CGF.getTypes().isZeroInitializable(elementType))) { 777 778 // Use an actual loop. This is basically 779 // do { *array++ = filler; } while (array != end); 780 781 // Advance to the start of the rest of the array. 782 if (NumInitElements) { 783 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start"); 784 if (endOfInit) Builder.CreateStore(element, endOfInit); 785 } 786 787 // Compute the end of the array. 788 llvm::Value *end = Builder.CreateInBoundsGEP(begin, 789 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), 790 "arrayinit.end"); 791 792 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 793 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body"); 794 795 // Jump into the body. 796 CGF.EmitBlock(bodyBB); 797 llvm::PHINode *currentElement = 798 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur"); 799 currentElement->addIncoming(element, entryBB); 800 801 // Emit the actual filler expression. 802 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType); 803 if (filler) 804 EmitInitializationToLValue(filler, elementLV); 805 else 806 EmitNullInitializationToLValue(elementLV); 807 808 // Move on to the next element. 809 llvm::Value *nextElement = 810 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next"); 811 812 // Tell the EH cleanup that we finished with the last element. 813 if (endOfInit) Builder.CreateStore(nextElement, endOfInit); 814 815 // Leave the loop if we're done. 816 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end, 817 "arrayinit.done"); 818 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end"); 819 Builder.CreateCondBr(done, endBB, bodyBB); 820 currentElement->addIncoming(nextElement, Builder.GetInsertBlock()); 821 822 CGF.EmitBlock(endBB); 823 } 824 825 // Leave the partial-array cleanup if we entered one. 826 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup); 827 828 return; 829 } 830 831 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 832 833 // Do struct initialization; this code just sets each individual member 834 // to the approprate value. This makes bitfield support automatic; 835 // the disadvantage is that the generated code is more difficult for 836 // the optimizer, especially with bitfields. 837 unsigned NumInitElements = E->getNumInits(); 838 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl(); 839 840 if (record->isUnion()) { 841 // Only initialize one field of a union. The field itself is 842 // specified by the initializer list. 843 if (!E->getInitializedFieldInUnion()) { 844 // Empty union; we have nothing to do. 845 846 #ifndef NDEBUG 847 // Make sure that it's really an empty and not a failure of 848 // semantic analysis. 849 for (RecordDecl::field_iterator Field = record->field_begin(), 850 FieldEnd = record->field_end(); 851 Field != FieldEnd; ++Field) 852 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 853 #endif 854 return; 855 } 856 857 // FIXME: volatility 858 FieldDecl *Field = E->getInitializedFieldInUnion(); 859 860 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 861 if (NumInitElements) { 862 // Store the initializer into the field 863 EmitInitializationToLValue(E->getInit(0), FieldLoc); 864 } else { 865 // Default-initialize to null. 866 EmitNullInitializationToLValue(FieldLoc); 867 } 868 869 return; 870 } 871 872 // We'll need to enter cleanup scopes in case any of the member 873 // initializers throw an exception. 874 SmallVector<EHScopeStack::stable_iterator, 16> cleanups; 875 876 // Here we iterate over the fields; this makes it simpler to both 877 // default-initialize fields and skip over unnamed fields. 878 unsigned curInitIndex = 0; 879 for (RecordDecl::field_iterator field = record->field_begin(), 880 fieldEnd = record->field_end(); 881 field != fieldEnd; ++field) { 882 // We're done once we hit the flexible array member. 883 if (field->getType()->isIncompleteArrayType()) 884 break; 885 886 // Always skip anonymous bitfields. 887 if (field->isUnnamedBitfield()) 888 continue; 889 890 // We're done if we reach the end of the explicit initializers, we 891 // have a zeroed object, and the rest of the fields are 892 // zero-initializable. 893 if (curInitIndex == NumInitElements && Dest.isZeroed() && 894 CGF.getTypes().isZeroInitializable(E->getType())) 895 break; 896 897 // FIXME: volatility 898 LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0); 899 // We never generate write-barries for initialized fields. 900 LV.setNonGC(true); 901 902 if (curInitIndex < NumInitElements) { 903 // Store the initializer into the field. 904 EmitInitializationToLValue(E->getInit(curInitIndex++), LV); 905 } else { 906 // We're out of initalizers; default-initialize to null 907 EmitNullInitializationToLValue(LV); 908 } 909 910 // Push a destructor if necessary. 911 // FIXME: if we have an array of structures, all explicitly 912 // initialized, we can end up pushing a linear number of cleanups. 913 bool pushedCleanup = false; 914 if (QualType::DestructionKind dtorKind 915 = field->getType().isDestructedType()) { 916 assert(LV.isSimple()); 917 if (CGF.needsEHCleanup(dtorKind)) { 918 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(), 919 CGF.getDestroyer(dtorKind), false); 920 cleanups.push_back(CGF.EHStack.stable_begin()); 921 pushedCleanup = true; 922 } 923 } 924 925 // If the GEP didn't get used because of a dead zero init or something 926 // else, clean it up for -O0 builds and general tidiness. 927 if (!pushedCleanup && LV.isSimple()) 928 if (llvm::GetElementPtrInst *GEP = 929 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress())) 930 if (GEP->use_empty()) 931 GEP->eraseFromParent(); 932 } 933 934 // Deactivate all the partial cleanups in reverse order, which 935 // generally means popping them. 936 for (unsigned i = cleanups.size(); i != 0; --i) 937 CGF.DeactivateCleanupBlock(cleanups[i-1]); 938 } 939 940 //===----------------------------------------------------------------------===// 941 // Entry Points into this File 942 //===----------------------------------------------------------------------===// 943 944 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of 945 /// non-zero bytes that will be stored when outputting the initializer for the 946 /// specified initializer expression. 947 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { 948 E = E->IgnoreParens(); 949 950 // 0 and 0.0 won't require any non-zero stores! 951 if (isSimpleZero(E, CGF)) return CharUnits::Zero(); 952 953 // If this is an initlist expr, sum up the size of sizes of the (present) 954 // elements. If this is something weird, assume the whole thing is non-zero. 955 const InitListExpr *ILE = dyn_cast<InitListExpr>(E); 956 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType())) 957 return CGF.getContext().getTypeSizeInChars(E->getType()); 958 959 // InitListExprs for structs have to be handled carefully. If there are 960 // reference members, we need to consider the size of the reference, not the 961 // referencee. InitListExprs for unions and arrays can't have references. 962 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 963 if (!RT->isUnionType()) { 964 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 965 CharUnits NumNonZeroBytes = CharUnits::Zero(); 966 967 unsigned ILEElement = 0; 968 for (RecordDecl::field_iterator Field = SD->field_begin(), 969 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) { 970 // We're done once we hit the flexible array member or run out of 971 // InitListExpr elements. 972 if (Field->getType()->isIncompleteArrayType() || 973 ILEElement == ILE->getNumInits()) 974 break; 975 if (Field->isUnnamedBitfield()) 976 continue; 977 978 const Expr *E = ILE->getInit(ILEElement++); 979 980 // Reference values are always non-null and have the width of a pointer. 981 if (Field->getType()->isReferenceType()) 982 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits( 983 CGF.getContext().getTargetInfo().getPointerWidth(0)); 984 else 985 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); 986 } 987 988 return NumNonZeroBytes; 989 } 990 } 991 992 993 CharUnits NumNonZeroBytes = CharUnits::Zero(); 994 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 995 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); 996 return NumNonZeroBytes; 997 } 998 999 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of 1000 /// zeros in it, emit a memset and avoid storing the individual zeros. 1001 /// 1002 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, 1003 CodeGenFunction &CGF) { 1004 // If the slot is already known to be zeroed, nothing to do. Don't mess with 1005 // volatile stores. 1006 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return; 1007 1008 // C++ objects with a user-declared constructor don't need zero'ing. 1009 if (CGF.getContext().getLangOptions().CPlusPlus) 1010 if (const RecordType *RT = CGF.getContext() 1011 .getBaseElementType(E->getType())->getAs<RecordType>()) { 1012 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1013 if (RD->hasUserDeclaredConstructor()) 1014 return; 1015 } 1016 1017 // If the type is 16-bytes or smaller, prefer individual stores over memset. 1018 std::pair<CharUnits, CharUnits> TypeInfo = 1019 CGF.getContext().getTypeInfoInChars(E->getType()); 1020 if (TypeInfo.first <= CharUnits::fromQuantity(16)) 1021 return; 1022 1023 // Check to see if over 3/4 of the initializer are known to be zero. If so, 1024 // we prefer to emit memset + individual stores for the rest. 1025 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); 1026 if (NumNonZeroBytes*4 > TypeInfo.first) 1027 return; 1028 1029 // Okay, it seems like a good idea to use an initial memset, emit the call. 1030 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity()); 1031 CharUnits Align = TypeInfo.second; 1032 1033 llvm::Value *Loc = Slot.getAddr(); 1034 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); 1035 1036 Loc = CGF.Builder.CreateBitCast(Loc, BP); 1037 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, 1038 Align.getQuantity(), false); 1039 1040 // Tell the AggExprEmitter that the slot is known zero. 1041 Slot.setZeroed(); 1042 } 1043 1044 1045 1046 1047 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 1048 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 1049 /// the value of the aggregate expression is not needed. If VolatileDest is 1050 /// true, DestPtr cannot be 0. 1051 /// 1052 /// \param IsInitializer - true if this evaluation is initializing an 1053 /// object whose lifetime is already being managed. 1054 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot, 1055 bool IgnoreResult) { 1056 assert(E && hasAggregateLLVMType(E->getType()) && 1057 "Invalid aggregate expression to emit"); 1058 assert((Slot.getAddr() != 0 || Slot.isIgnored()) && 1059 "slot has bits but no address"); 1060 1061 // Optimize the slot if possible. 1062 CheckAggExprForMemSetUse(Slot, E, *this); 1063 1064 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E)); 1065 } 1066 1067 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 1068 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 1069 llvm::Value *Temp = CreateMemTemp(E->getType()); 1070 LValue LV = MakeAddrLValue(Temp, E->getType()); 1071 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed, 1072 AggValueSlot::DoesNotNeedGCBarriers, 1073 AggValueSlot::IsNotAliased)); 1074 return LV; 1075 } 1076 1077 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 1078 llvm::Value *SrcPtr, QualType Ty, 1079 bool isVolatile) { 1080 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 1081 1082 if (getContext().getLangOptions().CPlusPlus) { 1083 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1084 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 1085 assert((Record->hasTrivialCopyConstructor() || 1086 Record->hasTrivialCopyAssignment() || 1087 Record->hasTrivialMoveConstructor() || 1088 Record->hasTrivialMoveAssignment()) && 1089 "Trying to aggregate-copy a type without a trivial copy " 1090 "constructor or assignment operator"); 1091 // Ignore empty classes in C++. 1092 if (Record->isEmpty()) 1093 return; 1094 } 1095 } 1096 1097 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 1098 // C99 6.5.16.1p3, which states "If the value being stored in an object is 1099 // read from another object that overlaps in anyway the storage of the first 1100 // object, then the overlap shall be exact and the two objects shall have 1101 // qualified or unqualified versions of a compatible type." 1102 // 1103 // memcpy is not defined if the source and destination pointers are exactly 1104 // equal, but other compilers do this optimization, and almost every memcpy 1105 // implementation handles this case safely. If there is a libc that does not 1106 // safely handle this, we can add a target hook. 1107 1108 // Get size and alignment info for this aggregate. 1109 std::pair<CharUnits, CharUnits> TypeInfo = 1110 getContext().getTypeInfoInChars(Ty); 1111 1112 // FIXME: Handle variable sized types. 1113 1114 // FIXME: If we have a volatile struct, the optimizer can remove what might 1115 // appear to be `extra' memory ops: 1116 // 1117 // volatile struct { int i; } a, b; 1118 // 1119 // int main() { 1120 // a = b; 1121 // a = b; 1122 // } 1123 // 1124 // we need to use a different call here. We use isVolatile to indicate when 1125 // either the source or the destination is volatile. 1126 1127 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 1128 llvm::Type *DBP = 1129 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace()); 1130 DestPtr = Builder.CreateBitCast(DestPtr, DBP); 1131 1132 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 1133 llvm::Type *SBP = 1134 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace()); 1135 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP); 1136 1137 // Don't do any of the memmove_collectable tests if GC isn't set. 1138 if (CGM.getLangOptions().getGC() == LangOptions::NonGC) { 1139 // fall through 1140 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1141 RecordDecl *Record = RecordTy->getDecl(); 1142 if (Record->hasObjectMember()) { 1143 CharUnits size = TypeInfo.first; 1144 llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 1145 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1146 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 1147 SizeVal); 1148 return; 1149 } 1150 } else if (Ty->isArrayType()) { 1151 QualType BaseType = getContext().getBaseElementType(Ty); 1152 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 1153 if (RecordTy->getDecl()->hasObjectMember()) { 1154 CharUnits size = TypeInfo.first; 1155 llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 1156 llvm::Value *SizeVal = 1157 llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1158 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 1159 SizeVal); 1160 return; 1161 } 1162 } 1163 } 1164 1165 Builder.CreateMemCpy(DestPtr, SrcPtr, 1166 llvm::ConstantInt::get(IntPtrTy, 1167 TypeInfo.first.getQuantity()), 1168 TypeInfo.second.getQuantity(), isVolatile); 1169 } 1170