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