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 ReturnValueSlot getReturnValueSlot() const { 39 // If the destination slot requires garbage collection, we can't 40 // use the real return value slot, because we have to use the GC 41 // API. 42 if (Dest.requiresGCollection()) return ReturnValueSlot(); 43 44 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile()); 45 } 46 47 AggValueSlot EnsureSlot(QualType T) { 48 if (!Dest.isIgnored()) return Dest; 49 return CGF.CreateAggTemp(T, "agg.tmp.ensured"); 50 } 51 52 public: 53 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, 54 bool ignore) 55 : CGF(cgf), Builder(CGF.Builder), Dest(Dest), 56 IgnoreResult(ignore) { 57 } 58 59 //===--------------------------------------------------------------------===// 60 // Utilities 61 //===--------------------------------------------------------------------===// 62 63 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 64 /// represents a value lvalue, this method emits the address of the lvalue, 65 /// then loads the result into DestPtr. 66 void EmitAggLoadOfLValue(const Expr *E); 67 68 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 69 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false); 70 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false); 71 72 void EmitGCMove(const Expr *E, RValue Src); 73 74 bool TypeRequiresGCollection(QualType T); 75 76 //===--------------------------------------------------------------------===// 77 // Visitor Methods 78 //===--------------------------------------------------------------------===// 79 80 void VisitStmt(Stmt *S) { 81 CGF.ErrorUnsupported(S, "aggregate expression"); 82 } 83 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 84 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 85 86 // l-values. 87 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 88 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 89 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 90 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 91 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 92 EmitAggLoadOfLValue(E); 93 } 94 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 95 EmitAggLoadOfLValue(E); 96 } 97 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) { 98 EmitAggLoadOfLValue(E); 99 } 100 void VisitPredefinedExpr(const PredefinedExpr *E) { 101 EmitAggLoadOfLValue(E); 102 } 103 104 // Operators. 105 void VisitCastExpr(CastExpr *E); 106 void VisitCallExpr(const CallExpr *E); 107 void VisitStmtExpr(const StmtExpr *E); 108 void VisitBinaryOperator(const BinaryOperator *BO); 109 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO); 110 void VisitBinAssign(const BinaryOperator *E); 111 void VisitBinComma(const BinaryOperator *E); 112 113 void VisitObjCMessageExpr(ObjCMessageExpr *E); 114 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 115 EmitAggLoadOfLValue(E); 116 } 117 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 118 119 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO); 120 void VisitChooseExpr(const ChooseExpr *CE); 121 void VisitInitListExpr(InitListExpr *E); 122 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 123 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 124 Visit(DAE->getExpr()); 125 } 126 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 127 void VisitCXXConstructExpr(const CXXConstructExpr *E); 128 void VisitExprWithCleanups(ExprWithCleanups *E); 129 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 130 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); } 131 132 void VisitOpaqueValueExpr(OpaqueValueExpr *E); 133 134 void VisitVAArgExpr(VAArgExpr *E); 135 136 void EmitInitializationToLValue(Expr *E, LValue Address, QualType T); 137 void EmitNullInitializationToLValue(LValue Address, QualType T); 138 // case Expr::ChooseExprClass: 139 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); } 140 }; 141 } // end anonymous namespace. 142 143 //===----------------------------------------------------------------------===// 144 // Utilities 145 //===----------------------------------------------------------------------===// 146 147 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 148 /// represents a value lvalue, this method emits the address of the lvalue, 149 /// then loads the result into DestPtr. 150 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 151 LValue LV = CGF.EmitLValue(E); 152 EmitFinalDestCopy(E, LV); 153 } 154 155 /// \brief True if the given aggregate type requires special GC API calls. 156 bool AggExprEmitter::TypeRequiresGCollection(QualType T) { 157 // Only record types have members that might require garbage collection. 158 const RecordType *RecordTy = T->getAs<RecordType>(); 159 if (!RecordTy) return false; 160 161 // Don't mess with non-trivial C++ types. 162 RecordDecl *Record = RecordTy->getDecl(); 163 if (isa<CXXRecordDecl>(Record) && 164 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() || 165 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor())) 166 return false; 167 168 // Check whether the type has an object member. 169 return Record->hasObjectMember(); 170 } 171 172 /// \brief Perform the final move to DestPtr if RequiresGCollection is set. 173 /// 174 /// The idea is that you do something like this: 175 /// RValue Result = EmitSomething(..., getReturnValueSlot()); 176 /// EmitGCMove(E, Result); 177 /// If GC doesn't interfere, this will cause the result to be emitted 178 /// directly into the return value slot. If GC does interfere, a final 179 /// move will be performed. 180 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) { 181 if (Dest.requiresGCollection()) { 182 std::pair<uint64_t, unsigned> TypeInfo = 183 CGF.getContext().getTypeInfo(E->getType()); 184 unsigned long size = TypeInfo.first/8; 185 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 186 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 187 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(), 188 Src.getAggregateAddr(), 189 SizeVal); 190 } 191 } 192 193 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 194 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) { 195 assert(Src.isAggregate() && "value must be aggregate value!"); 196 197 // If Dest is ignored, then we're evaluating an aggregate expression 198 // in a context (like an expression statement) that doesn't care 199 // about the result. C says that an lvalue-to-rvalue conversion is 200 // performed in these cases; C++ says that it is not. In either 201 // case, we don't actually need to do anything unless the value is 202 // volatile. 203 if (Dest.isIgnored()) { 204 if (!Src.isVolatileQualified() || 205 CGF.CGM.getLangOptions().CPlusPlus || 206 (IgnoreResult && Ignore)) 207 return; 208 209 // If the source is volatile, we must read from it; to do that, we need 210 // some place to put it. 211 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp"); 212 } 213 214 if (Dest.requiresGCollection()) { 215 std::pair<uint64_t, unsigned> TypeInfo = 216 CGF.getContext().getTypeInfo(E->getType()); 217 unsigned long size = TypeInfo.first/8; 218 const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType()); 219 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 220 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, 221 Dest.getAddr(), 222 Src.getAggregateAddr(), 223 SizeVal); 224 return; 225 } 226 // If the result of the assignment is used, copy the LHS there also. 227 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile 228 // from the source as well, as we can't eliminate it if either operand 229 // is volatile, unless copy has volatile for both source and destination.. 230 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(), 231 Dest.isVolatile()|Src.isVolatileQualified()); 232 } 233 234 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired. 235 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) { 236 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc"); 237 238 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(), 239 Src.isVolatileQualified()), 240 Ignore); 241 } 242 243 //===----------------------------------------------------------------------===// 244 // Visitor Methods 245 //===----------------------------------------------------------------------===// 246 247 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) { 248 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e)); 249 } 250 251 void AggExprEmitter::VisitCastExpr(CastExpr *E) { 252 switch (E->getCastKind()) { 253 case CK_Dynamic: { 254 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?"); 255 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr()); 256 // FIXME: Do we also need to handle property references here? 257 if (LV.isSimple()) 258 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E)); 259 else 260 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast"); 261 262 if (!Dest.isIgnored()) 263 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination"); 264 break; 265 } 266 267 case CK_ToUnion: { 268 if (Dest.isIgnored()) break; 269 270 // GCC union extension 271 QualType Ty = E->getSubExpr()->getType(); 272 QualType PtrTy = CGF.getContext().getPointerType(Ty); 273 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(), 274 CGF.ConvertType(PtrTy)); 275 EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty), 276 Ty); 277 break; 278 } 279 280 case CK_DerivedToBase: 281 case CK_BaseToDerived: 282 case CK_UncheckedDerivedToBase: { 283 assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: " 284 "should have been unpacked before we got here"); 285 break; 286 } 287 288 case CK_GetObjCProperty: { 289 LValue LV = CGF.EmitLValue(E->getSubExpr()); 290 assert(LV.isPropertyRef()); 291 RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot()); 292 EmitGCMove(E, RV); 293 break; 294 } 295 296 case CK_LValueToRValue: // hope for downstream optimization 297 case CK_NoOp: 298 case CK_UserDefinedConversion: 299 case CK_ConstructorConversion: 300 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(), 301 E->getType()) && 302 "Implicit cast types must be compatible"); 303 Visit(E->getSubExpr()); 304 break; 305 306 case CK_LValueBitCast: 307 llvm_unreachable("should not be emitting lvalue bitcast as rvalue"); 308 break; 309 310 case CK_Dependent: 311 case CK_BitCast: 312 case CK_ArrayToPointerDecay: 313 case CK_FunctionToPointerDecay: 314 case CK_NullToPointer: 315 case CK_NullToMemberPointer: 316 case CK_BaseToDerivedMemberPointer: 317 case CK_DerivedToBaseMemberPointer: 318 case CK_MemberPointerToBoolean: 319 case CK_IntegralToPointer: 320 case CK_PointerToIntegral: 321 case CK_PointerToBoolean: 322 case CK_ToVoid: 323 case CK_VectorSplat: 324 case CK_IntegralCast: 325 case CK_IntegralToBoolean: 326 case CK_IntegralToFloating: 327 case CK_FloatingToIntegral: 328 case CK_FloatingToBoolean: 329 case CK_FloatingCast: 330 case CK_AnyPointerToObjCPointerCast: 331 case CK_AnyPointerToBlockPointerCast: 332 case CK_ObjCObjectLValueCast: 333 case CK_FloatingRealToComplex: 334 case CK_FloatingComplexToReal: 335 case CK_FloatingComplexToBoolean: 336 case CK_FloatingComplexCast: 337 case CK_FloatingComplexToIntegralComplex: 338 case CK_IntegralRealToComplex: 339 case CK_IntegralComplexToReal: 340 case CK_IntegralComplexToBoolean: 341 case CK_IntegralComplexCast: 342 case CK_IntegralComplexToFloatingComplex: 343 llvm_unreachable("cast kind invalid for aggregate types"); 344 } 345 } 346 347 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 348 if (E->getCallReturnType()->isReferenceType()) { 349 EmitAggLoadOfLValue(E); 350 return; 351 } 352 353 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot()); 354 EmitGCMove(E, RV); 355 } 356 357 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 358 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot()); 359 EmitGCMove(E, RV); 360 } 361 362 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 363 llvm_unreachable("direct property access not surrounded by " 364 "lvalue-to-rvalue cast"); 365 } 366 367 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 368 CGF.EmitIgnoredExpr(E->getLHS()); 369 Visit(E->getRHS()); 370 } 371 372 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 373 CodeGenFunction::StmtExprEvaluation eval(CGF); 374 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest); 375 } 376 377 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 378 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI) 379 VisitPointerToDataMemberBinaryOperator(E); 380 else 381 CGF.ErrorUnsupported(E, "aggregate binary expression"); 382 } 383 384 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator( 385 const BinaryOperator *E) { 386 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E); 387 EmitFinalDestCopy(E, LV); 388 } 389 390 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 391 // For an assignment to work, the value on the right has 392 // to be compatible with the value on the left. 393 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(), 394 E->getRHS()->getType()) 395 && "Invalid assignment"); 396 397 // FIXME: __block variables need the RHS evaluated first! 398 LValue LHS = CGF.EmitLValue(E->getLHS()); 399 400 // We have to special case property setters, otherwise we must have 401 // a simple lvalue (no aggregates inside vectors, bitfields). 402 if (LHS.isPropertyRef()) { 403 const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr(); 404 QualType ArgType = RE->getSetterArgType(); 405 RValue Src; 406 if (ArgType->isReferenceType()) 407 Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0); 408 else { 409 AggValueSlot Slot = EnsureSlot(E->getRHS()->getType()); 410 CGF.EmitAggExpr(E->getRHS(), Slot); 411 Src = Slot.asRValue(); 412 } 413 CGF.EmitStoreThroughPropertyRefLValue(Src, LHS); 414 } else { 415 bool GCollection = false; 416 if (CGF.getContext().getLangOptions().getGCMode()) 417 GCollection = TypeRequiresGCollection(E->getLHS()->getType()); 418 419 // Codegen the RHS so that it stores directly into the LHS. 420 AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true, 421 GCollection); 422 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false); 423 EmitFinalDestCopy(E, LHS, true); 424 } 425 } 426 427 void AggExprEmitter:: 428 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 429 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 430 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 431 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 432 433 // Bind the common expression if necessary. 434 CodeGenFunction::OpaqueValueMapping binding(CGF, E); 435 436 CodeGenFunction::ConditionalEvaluation eval(CGF); 437 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock); 438 439 // Save whether the destination's lifetime is externally managed. 440 bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged(); 441 442 eval.begin(CGF); 443 CGF.EmitBlock(LHSBlock); 444 Visit(E->getTrueExpr()); 445 eval.end(CGF); 446 447 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!"); 448 CGF.Builder.CreateBr(ContBlock); 449 450 // If the result of an agg expression is unused, then the emission 451 // of the LHS might need to create a destination slot. That's fine 452 // with us, and we can safely emit the RHS into the same slot, but 453 // we shouldn't claim that its lifetime is externally managed. 454 Dest.setLifetimeExternallyManaged(DestLifetimeManaged); 455 456 eval.begin(CGF); 457 CGF.EmitBlock(RHSBlock); 458 Visit(E->getFalseExpr()); 459 eval.end(CGF); 460 461 CGF.EmitBlock(ContBlock); 462 } 463 464 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) { 465 Visit(CE->getChosenSubExpr(CGF.getContext())); 466 } 467 468 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 469 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 470 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 471 472 if (!ArgPtr) { 473 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 474 return; 475 } 476 477 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType())); 478 } 479 480 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 481 // Ensure that we have a slot, but if we already do, remember 482 // whether its lifetime was externally managed. 483 bool WasManaged = Dest.isLifetimeExternallyManaged(); 484 Dest = EnsureSlot(E->getType()); 485 Dest.setLifetimeExternallyManaged(); 486 487 Visit(E->getSubExpr()); 488 489 // Set up the temporary's destructor if its lifetime wasn't already 490 // being managed. 491 if (!WasManaged) 492 CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr()); 493 } 494 495 void 496 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) { 497 AggValueSlot Slot = EnsureSlot(E->getType()); 498 CGF.EmitCXXConstructExpr(E, Slot); 499 } 500 501 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) { 502 CGF.EmitExprWithCleanups(E, Dest); 503 } 504 505 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 506 QualType T = E->getType(); 507 AggValueSlot Slot = EnsureSlot(T); 508 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T); 509 } 510 511 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 512 QualType T = E->getType(); 513 AggValueSlot Slot = EnsureSlot(T); 514 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T), T); 515 } 516 517 /// isSimpleZero - If emitting this value will obviously just cause a store of 518 /// zero to memory, return true. This can return false if uncertain, so it just 519 /// handles simple cases. 520 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) { 521 // (0) 522 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 523 return isSimpleZero(PE->getSubExpr(), CGF); 524 // 0 525 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) 526 return IL->getValue() == 0; 527 // +0.0 528 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) 529 return FL->getValue().isPosZero(); 530 // int() 531 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) && 532 CGF.getTypes().isZeroInitializable(E->getType())) 533 return true; 534 // (int*)0 - Null pointer expressions. 535 if (const CastExpr *ICE = dyn_cast<CastExpr>(E)) 536 return ICE->getCastKind() == CK_NullToPointer; 537 // '\0' 538 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) 539 return CL->getValue() == 0; 540 541 // Otherwise, hard case: conservatively return false. 542 return false; 543 } 544 545 546 void 547 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) { 548 // FIXME: Ignore result? 549 // FIXME: Are initializers affected by volatile? 550 if (Dest.isZeroed() && isSimpleZero(E, CGF)) { 551 // Storing "i32 0" to a zero'd memory location is a noop. 552 } else if (isa<ImplicitValueInitExpr>(E)) { 553 EmitNullInitializationToLValue(LV, T); 554 } else if (T->isReferenceType()) { 555 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0); 556 CGF.EmitStoreThroughLValue(RV, LV, T); 557 } else if (T->isAnyComplexType()) { 558 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 559 } else if (CGF.hasAggregateLLVMType(T)) { 560 CGF.EmitAggExpr(E, AggValueSlot::forAddr(LV.getAddress(), false, true, 561 false, Dest.isZeroed())); 562 } else { 563 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, T); 564 } 565 } 566 567 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 568 // If the destination slot is already zeroed out before the aggregate is 569 // copied into it, we don't have to emit any zeros here. 570 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(T)) 571 return; 572 573 if (!CGF.hasAggregateLLVMType(T)) { 574 // For non-aggregates, we can store zero 575 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 576 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 577 } else { 578 // There's a potential optimization opportunity in combining 579 // memsets; that would be easy for arrays, but relatively 580 // difficult for structures with the current code. 581 CGF.EmitNullInitialization(LV.getAddress(), T); 582 } 583 } 584 585 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 586 #if 0 587 // FIXME: Assess perf here? Figure out what cases are worth optimizing here 588 // (Length of globals? Chunks of zeroed-out space?). 589 // 590 // If we can, prefer a copy from a global; this is a lot less code for long 591 // globals, and it's easier for the current optimizers to analyze. 592 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) { 593 llvm::GlobalVariable* GV = 594 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true, 595 llvm::GlobalValue::InternalLinkage, C, ""); 596 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType())); 597 return; 598 } 599 #endif 600 if (E->hadArrayRangeDesignator()) 601 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 602 603 llvm::Value *DestPtr = Dest.getAddr(); 604 605 // Handle initialization of an array. 606 if (E->getType()->isArrayType()) { 607 const llvm::PointerType *APType = 608 cast<llvm::PointerType>(DestPtr->getType()); 609 const llvm::ArrayType *AType = 610 cast<llvm::ArrayType>(APType->getElementType()); 611 612 uint64_t NumInitElements = E->getNumInits(); 613 614 if (E->getNumInits() > 0) { 615 QualType T1 = E->getType(); 616 QualType T2 = E->getInit(0)->getType(); 617 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) { 618 EmitAggLoadOfLValue(E->getInit(0)); 619 return; 620 } 621 } 622 623 uint64_t NumArrayElements = AType->getNumElements(); 624 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 625 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 626 627 // FIXME: were we intentionally ignoring address spaces and GC attributes? 628 629 for (uint64_t i = 0; i != NumArrayElements; ++i) { 630 // If we're done emitting initializers and the destination is known-zeroed 631 // then we're done. 632 if (i == NumInitElements && 633 Dest.isZeroed() && 634 CGF.getTypes().isZeroInitializable(ElementType)) 635 break; 636 637 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 638 LValue LV = CGF.MakeAddrLValue(NextVal, ElementType); 639 640 if (i < NumInitElements) 641 EmitInitializationToLValue(E->getInit(i), LV, ElementType); 642 else 643 EmitNullInitializationToLValue(LV, ElementType); 644 645 // If the GEP didn't get used because of a dead zero init or something 646 // else, clean it up for -O0 builds and general tidiness. 647 if (llvm::GetElementPtrInst *GEP = 648 dyn_cast<llvm::GetElementPtrInst>(NextVal)) 649 if (GEP->use_empty()) 650 GEP->eraseFromParent(); 651 } 652 return; 653 } 654 655 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 656 657 // Do struct initialization; this code just sets each individual member 658 // to the approprate value. This makes bitfield support automatic; 659 // the disadvantage is that the generated code is more difficult for 660 // the optimizer, especially with bitfields. 661 unsigned NumInitElements = E->getNumInits(); 662 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 663 664 if (E->getType()->isUnionType()) { 665 // Only initialize one field of a union. The field itself is 666 // specified by the initializer list. 667 if (!E->getInitializedFieldInUnion()) { 668 // Empty union; we have nothing to do. 669 670 #ifndef NDEBUG 671 // Make sure that it's really an empty and not a failure of 672 // semantic analysis. 673 for (RecordDecl::field_iterator Field = SD->field_begin(), 674 FieldEnd = SD->field_end(); 675 Field != FieldEnd; ++Field) 676 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 677 #endif 678 return; 679 } 680 681 // FIXME: volatility 682 FieldDecl *Field = E->getInitializedFieldInUnion(); 683 684 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0); 685 if (NumInitElements) { 686 // Store the initializer into the field 687 EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType()); 688 } else { 689 // Default-initialize to null. 690 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 691 } 692 693 return; 694 } 695 696 // Here we iterate over the fields; this makes it simpler to both 697 // default-initialize fields and skip over unnamed fields. 698 unsigned CurInitVal = 0; 699 for (RecordDecl::field_iterator Field = SD->field_begin(), 700 FieldEnd = SD->field_end(); 701 Field != FieldEnd; ++Field) { 702 // We're done once we hit the flexible array member 703 if (Field->getType()->isIncompleteArrayType()) 704 break; 705 706 if (Field->isUnnamedBitfield()) 707 continue; 708 709 // Don't emit GEP before a noop store of zero. 710 if (CurInitVal == NumInitElements && Dest.isZeroed() && 711 CGF.getTypes().isZeroInitializable(E->getType())) 712 break; 713 714 // FIXME: volatility 715 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0); 716 // We never generate write-barries for initialized fields. 717 FieldLoc.setNonGC(true); 718 719 if (CurInitVal < NumInitElements) { 720 // Store the initializer into the field. 721 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc, 722 Field->getType()); 723 } else { 724 // We're out of initalizers; default-initialize to null 725 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 726 } 727 728 // If the GEP didn't get used because of a dead zero init or something 729 // else, clean it up for -O0 builds and general tidiness. 730 if (FieldLoc.isSimple()) 731 if (llvm::GetElementPtrInst *GEP = 732 dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress())) 733 if (GEP->use_empty()) 734 GEP->eraseFromParent(); 735 } 736 } 737 738 //===----------------------------------------------------------------------===// 739 // Entry Points into this File 740 //===----------------------------------------------------------------------===// 741 742 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of 743 /// non-zero bytes that will be stored when outputting the initializer for the 744 /// specified initializer expression. 745 static uint64_t GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) { 746 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 747 return GetNumNonZeroBytesInInit(PE->getSubExpr(), CGF); 748 749 // 0 and 0.0 won't require any non-zero stores! 750 if (isSimpleZero(E, CGF)) return 0; 751 752 // If this is an initlist expr, sum up the size of sizes of the (present) 753 // elements. If this is something weird, assume the whole thing is non-zero. 754 const InitListExpr *ILE = dyn_cast<InitListExpr>(E); 755 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType())) 756 return CGF.getContext().getTypeSize(E->getType())/8; 757 758 // InitListExprs for structs have to be handled carefully. If there are 759 // reference members, we need to consider the size of the reference, not the 760 // referencee. InitListExprs for unions and arrays can't have references. 761 if (const RecordType *RT = E->getType()->getAs<RecordType>()) { 762 if (!RT->isUnionType()) { 763 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl(); 764 uint64_t NumNonZeroBytes = 0; 765 766 unsigned ILEElement = 0; 767 for (RecordDecl::field_iterator Field = SD->field_begin(), 768 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) { 769 // We're done once we hit the flexible array member or run out of 770 // InitListExpr elements. 771 if (Field->getType()->isIncompleteArrayType() || 772 ILEElement == ILE->getNumInits()) 773 break; 774 if (Field->isUnnamedBitfield()) 775 continue; 776 777 const Expr *E = ILE->getInit(ILEElement++); 778 779 // Reference values are always non-null and have the width of a pointer. 780 if (Field->getType()->isReferenceType()) 781 NumNonZeroBytes += CGF.getContext().Target.getPointerWidth(0); 782 else 783 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF); 784 } 785 786 return NumNonZeroBytes; 787 } 788 } 789 790 791 uint64_t NumNonZeroBytes = 0; 792 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 793 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF); 794 return NumNonZeroBytes; 795 } 796 797 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of 798 /// zeros in it, emit a memset and avoid storing the individual zeros. 799 /// 800 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, 801 CodeGenFunction &CGF) { 802 // If the slot is already known to be zeroed, nothing to do. Don't mess with 803 // volatile stores. 804 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return; 805 806 // If the type is 16-bytes or smaller, prefer individual stores over memset. 807 std::pair<uint64_t, unsigned> TypeInfo = 808 CGF.getContext().getTypeInfo(E->getType()); 809 if (TypeInfo.first/8 <= 16) 810 return; 811 812 // Check to see if over 3/4 of the initializer are known to be zero. If so, 813 // we prefer to emit memset + individual stores for the rest. 814 uint64_t NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF); 815 if (NumNonZeroBytes*4 > TypeInfo.first/8) 816 return; 817 818 // Okay, it seems like a good idea to use an initial memset, emit the call. 819 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first/8); 820 unsigned Align = TypeInfo.second/8; 821 822 llvm::Value *Loc = Slot.getAddr(); 823 const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); 824 825 Loc = CGF.Builder.CreateBitCast(Loc, BP); 826 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, Align, false); 827 828 // Tell the AggExprEmitter that the slot is known zero. 829 Slot.setZeroed(); 830 } 831 832 833 834 835 /// EmitAggExpr - Emit the computation of the specified expression of aggregate 836 /// type. The result is computed into DestPtr. Note that if DestPtr is null, 837 /// the value of the aggregate expression is not needed. If VolatileDest is 838 /// true, DestPtr cannot be 0. 839 /// 840 /// \param IsInitializer - true if this evaluation is initializing an 841 /// object whose lifetime is already being managed. 842 // 843 // FIXME: Take Qualifiers object. 844 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot, 845 bool IgnoreResult) { 846 assert(E && hasAggregateLLVMType(E->getType()) && 847 "Invalid aggregate expression to emit"); 848 assert((Slot.getAddr() != 0 || Slot.isIgnored()) && 849 "slot has bits but no address"); 850 851 // Optimize the slot if possible. 852 CheckAggExprForMemSetUse(Slot, E, *this); 853 854 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E)); 855 } 856 857 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) { 858 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!"); 859 llvm::Value *Temp = CreateMemTemp(E->getType()); 860 LValue LV = MakeAddrLValue(Temp, E->getType()); 861 EmitAggExpr(E, AggValueSlot::forAddr(Temp, LV.isVolatileQualified(), false)); 862 return LV; 863 } 864 865 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 866 llvm::Value *SrcPtr, QualType Ty, 867 bool isVolatile) { 868 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 869 870 if (getContext().getLangOptions().CPlusPlus) { 871 if (const RecordType *RT = Ty->getAs<RecordType>()) { 872 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 873 assert((Record->hasTrivialCopyConstructor() || 874 Record->hasTrivialCopyAssignment()) && 875 "Trying to aggregate-copy a type without a trivial copy " 876 "constructor or assignment operator"); 877 // Ignore empty classes in C++. 878 if (Record->isEmpty()) 879 return; 880 } 881 } 882 883 // Aggregate assignment turns into llvm.memcpy. This is almost valid per 884 // C99 6.5.16.1p3, which states "If the value being stored in an object is 885 // read from another object that overlaps in anyway the storage of the first 886 // object, then the overlap shall be exact and the two objects shall have 887 // qualified or unqualified versions of a compatible type." 888 // 889 // memcpy is not defined if the source and destination pointers are exactly 890 // equal, but other compilers do this optimization, and almost every memcpy 891 // implementation handles this case safely. If there is a libc that does not 892 // safely handle this, we can add a target hook. 893 894 // Get size and alignment info for this aggregate. 895 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 896 897 // FIXME: Handle variable sized types. 898 899 // FIXME: If we have a volatile struct, the optimizer can remove what might 900 // appear to be `extra' memory ops: 901 // 902 // volatile struct { int i; } a, b; 903 // 904 // int main() { 905 // a = b; 906 // a = b; 907 // } 908 // 909 // we need to use a different call here. We use isVolatile to indicate when 910 // either the source or the destination is volatile. 911 912 const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType()); 913 const llvm::Type *DBP = 914 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace()); 915 DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp"); 916 917 const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType()); 918 const llvm::Type *SBP = 919 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace()); 920 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp"); 921 922 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 923 RecordDecl *Record = RecordTy->getDecl(); 924 if (Record->hasObjectMember()) { 925 unsigned long size = TypeInfo.first/8; 926 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 927 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 928 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 929 SizeVal); 930 return; 931 } 932 } else if (getContext().getAsArrayType(Ty)) { 933 QualType BaseType = getContext().getBaseElementType(Ty); 934 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 935 if (RecordTy->getDecl()->hasObjectMember()) { 936 unsigned long size = TypeInfo.first/8; 937 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 938 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size); 939 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 940 SizeVal); 941 return; 942 } 943 } 944 } 945 946 Builder.CreateMemCpy(DestPtr, SrcPtr, 947 llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8), 948 TypeInfo.second/8, isVolatile); 949 } 950