CGExprAgg.cpp 52 KB

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