CGExprAgg.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Aggregate Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGObjCRuntime.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "ConstantEmitter.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/GlobalVariable.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. //===----------------------------------------------------------------------===//
  31. // Aggregate Expression Emitter
  32. //===----------------------------------------------------------------------===//
  33. namespace {
  34. class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
  35. CodeGenFunction &CGF;
  36. CGBuilderTy &Builder;
  37. AggValueSlot Dest;
  38. bool IsResultUnused;
  39. AggValueSlot EnsureSlot(QualType T) {
  40. if (!Dest.isIgnored()) return Dest;
  41. return CGF.CreateAggTemp(T, "agg.tmp.ensured");
  42. }
  43. void EnsureDest(QualType T) {
  44. if (!Dest.isIgnored()) return;
  45. Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
  46. }
  47. // Calls `Fn` with a valid return value slot, potentially creating a temporary
  48. // to do so. If a temporary is created, an appropriate copy into `Dest` will
  49. // be emitted, as will lifetime markers.
  50. //
  51. // The given function should take a ReturnValueSlot, and return an RValue that
  52. // points to said slot.
  53. void withReturnValueSlot(const Expr *E,
  54. llvm::function_ref<RValue(ReturnValueSlot)> Fn);
  55. public:
  56. AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
  57. : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
  58. IsResultUnused(IsResultUnused) { }
  59. //===--------------------------------------------------------------------===//
  60. // Utilities
  61. //===--------------------------------------------------------------------===//
  62. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  63. /// represents a value lvalue, this method emits the address of the lvalue,
  64. /// then loads the result into DestPtr.
  65. void EmitAggLoadOfLValue(const Expr *E);
  66. enum ExprValueKind {
  67. EVK_RValue,
  68. EVK_NonRValue
  69. };
  70. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  71. /// SrcIsRValue is true if source comes from an RValue.
  72. void EmitFinalDestCopy(QualType type, const LValue &src,
  73. ExprValueKind SrcValueKind = EVK_NonRValue);
  74. void EmitFinalDestCopy(QualType type, RValue src);
  75. void EmitCopy(QualType type, const AggValueSlot &dest,
  76. const AggValueSlot &src);
  77. void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
  78. void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,
  79. Expr *ExprToVisit, ArrayRef<Expr *> Args,
  80. Expr *ArrayFiller);
  81. AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
  82. if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
  83. return AggValueSlot::NeedsGCBarriers;
  84. return AggValueSlot::DoesNotNeedGCBarriers;
  85. }
  86. bool TypeRequiresGCollection(QualType T);
  87. //===--------------------------------------------------------------------===//
  88. // Visitor Methods
  89. //===--------------------------------------------------------------------===//
  90. void Visit(Expr *E) {
  91. ApplyDebugLocation DL(CGF, E);
  92. StmtVisitor<AggExprEmitter>::Visit(E);
  93. }
  94. void VisitStmt(Stmt *S) {
  95. CGF.ErrorUnsupported(S, "aggregate expression");
  96. }
  97. void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
  98. void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  99. Visit(GE->getResultExpr());
  100. }
  101. void VisitCoawaitExpr(CoawaitExpr *E) {
  102. CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
  103. }
  104. void VisitCoyieldExpr(CoyieldExpr *E) {
  105. CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
  106. }
  107. void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
  108. void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
  109. void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  110. return Visit(E->getReplacement());
  111. }
  112. void VisitConstantExpr(ConstantExpr *E) {
  113. EnsureDest(E->getType());
  114. if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
  115. CGF.EmitAggregateStore(Result, Dest.getAddress(),
  116. E->getType().isVolatileQualified());
  117. return;
  118. }
  119. return Visit(E->getSubExpr());
  120. }
  121. // l-values.
  122. void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
  123. void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
  124. void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
  125. void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
  126. void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
  127. void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  128. EmitAggLoadOfLValue(E);
  129. }
  130. void VisitPredefinedExpr(const PredefinedExpr *E) {
  131. EmitAggLoadOfLValue(E);
  132. }
  133. // Operators.
  134. void VisitCastExpr(CastExpr *E);
  135. void VisitCallExpr(const CallExpr *E);
  136. void VisitStmtExpr(const StmtExpr *E);
  137. void VisitBinaryOperator(const BinaryOperator *BO);
  138. void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
  139. void VisitBinAssign(const BinaryOperator *E);
  140. void VisitBinComma(const BinaryOperator *E);
  141. void VisitBinCmp(const BinaryOperator *E);
  142. void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
  143. Visit(E->getSemanticForm());
  144. }
  145. void VisitObjCMessageExpr(ObjCMessageExpr *E);
  146. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  147. EmitAggLoadOfLValue(E);
  148. }
  149. void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
  150. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
  151. void VisitChooseExpr(const ChooseExpr *CE);
  152. void VisitInitListExpr(InitListExpr *E);
  153. void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
  154. FieldDecl *InitializedFieldInUnion,
  155. Expr *ArrayFiller);
  156. void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
  157. llvm::Value *outerBegin = nullptr);
  158. void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
  159. void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
  160. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  161. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  162. Visit(DAE->getExpr());
  163. }
  164. void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  165. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  166. Visit(DIE->getExpr());
  167. }
  168. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
  169. void VisitCXXConstructExpr(const CXXConstructExpr *E);
  170. void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  171. void VisitLambdaExpr(LambdaExpr *E);
  172. void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
  173. void VisitExprWithCleanups(ExprWithCleanups *E);
  174. void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
  175. void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
  176. void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
  177. void VisitOpaqueValueExpr(OpaqueValueExpr *E);
  178. void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  179. if (E->isGLValue()) {
  180. LValue LV = CGF.EmitPseudoObjectLValue(E);
  181. return EmitFinalDestCopy(E->getType(), LV);
  182. }
  183. AggValueSlot Slot = EnsureSlot(E->getType());
  184. bool NeedsDestruction =
  185. !Slot.isExternallyDestructed() &&
  186. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
  187. if (NeedsDestruction)
  188. Slot.setExternallyDestructed();
  189. CGF.EmitPseudoObjectRValue(E, Slot);
  190. if (NeedsDestruction)
  191. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Slot.getAddress(),
  192. E->getType());
  193. }
  194. void VisitVAArgExpr(VAArgExpr *E);
  195. void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);
  196. void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
  197. Expr *ArrayFiller);
  198. void EmitInitializationToLValue(Expr *E, LValue Address);
  199. void EmitNullInitializationToLValue(LValue Address);
  200. // case Expr::ChooseExprClass:
  201. void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
  202. void VisitAtomicExpr(AtomicExpr *E) {
  203. RValue Res = CGF.EmitAtomicExpr(E);
  204. EmitFinalDestCopy(E->getType(), Res);
  205. }
  206. };
  207. } // end anonymous namespace.
  208. //===----------------------------------------------------------------------===//
  209. // Utilities
  210. //===----------------------------------------------------------------------===//
  211. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  212. /// represents a value lvalue, this method emits the address of the lvalue,
  213. /// then loads the result into DestPtr.
  214. void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
  215. LValue LV = CGF.EmitLValue(E);
  216. // If the type of the l-value is atomic, then do an atomic load.
  217. if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
  218. CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
  219. return;
  220. }
  221. EmitFinalDestCopy(E->getType(), LV);
  222. }
  223. /// True if the given aggregate type requires special GC API calls.
  224. bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
  225. // Only record types have members that might require garbage collection.
  226. const RecordType *RecordTy = T->getAs<RecordType>();
  227. if (!RecordTy) return false;
  228. // Don't mess with non-trivial C++ types.
  229. RecordDecl *Record = RecordTy->getDecl();
  230. if (isa<CXXRecordDecl>(Record) &&
  231. (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
  232. !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
  233. return false;
  234. // Check whether the type has an object member.
  235. return Record->hasObjectMember();
  236. }
  237. void AggExprEmitter::withReturnValueSlot(
  238. const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
  239. QualType RetTy = E->getType();
  240. bool RequiresDestruction =
  241. !Dest.isExternallyDestructed() &&
  242. RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
  243. // If it makes no observable difference, save a memcpy + temporary.
  244. //
  245. // We need to always provide our own temporary if destruction is required.
  246. // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
  247. // its lifetime before we have the chance to emit a proper destructor call.
  248. bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
  249. (RequiresDestruction && !Dest.getAddress().isValid());
  250. Address RetAddr = Address::invalid();
  251. Address RetAllocaAddr = Address::invalid();
  252. EHScopeStack::stable_iterator LifetimeEndBlock;
  253. llvm::Value *LifetimeSizePtr = nullptr;
  254. llvm::IntrinsicInst *LifetimeStartInst = nullptr;
  255. if (!UseTemp) {
  256. RetAddr = Dest.getAddress();
  257. } else {
  258. RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);
  259. llvm::TypeSize Size =
  260. CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
  261. LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());
  262. if (LifetimeSizePtr) {
  263. LifetimeStartInst =
  264. cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
  265. assert(LifetimeStartInst->getIntrinsicID() ==
  266. llvm::Intrinsic::lifetime_start &&
  267. "Last insertion wasn't a lifetime.start?");
  268. CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
  269. NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);
  270. LifetimeEndBlock = CGF.EHStack.stable_begin();
  271. }
  272. }
  273. RValue Src =
  274. EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
  275. Dest.isExternallyDestructed()));
  276. if (!UseTemp)
  277. return;
  278. assert(Dest.isIgnored() || Dest.getPointer() != Src.getAggregatePointer());
  279. EmitFinalDestCopy(E->getType(), Src);
  280. if (!RequiresDestruction && LifetimeStartInst) {
  281. // If there's no dtor to run, the copy was the last use of our temporary.
  282. // Since we're not guaranteed to be in an ExprWithCleanups, clean up
  283. // eagerly.
  284. CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
  285. CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());
  286. }
  287. }
  288. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  289. void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
  290. assert(src.isAggregate() && "value must be aggregate value!");
  291. LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
  292. EmitFinalDestCopy(type, srcLV, EVK_RValue);
  293. }
  294. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  295. void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
  296. ExprValueKind SrcValueKind) {
  297. // If Dest is ignored, then we're evaluating an aggregate expression
  298. // in a context that doesn't care about the result. Note that loads
  299. // from volatile l-values force the existence of a non-ignored
  300. // destination.
  301. if (Dest.isIgnored())
  302. return;
  303. // Copy non-trivial C structs here.
  304. LValue DstLV = CGF.MakeAddrLValue(
  305. Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
  306. if (SrcValueKind == EVK_RValue) {
  307. if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
  308. if (Dest.isPotentiallyAliased())
  309. CGF.callCStructMoveAssignmentOperator(DstLV, src);
  310. else
  311. CGF.callCStructMoveConstructor(DstLV, src);
  312. return;
  313. }
  314. } else {
  315. if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
  316. if (Dest.isPotentiallyAliased())
  317. CGF.callCStructCopyAssignmentOperator(DstLV, src);
  318. else
  319. CGF.callCStructCopyConstructor(DstLV, src);
  320. return;
  321. }
  322. }
  323. AggValueSlot srcAgg = AggValueSlot::forLValue(
  324. src, CGF, AggValueSlot::IsDestructed, needsGC(type),
  325. AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
  326. EmitCopy(type, Dest, srcAgg);
  327. }
  328. /// Perform a copy from the source into the destination.
  329. ///
  330. /// \param type - the type of the aggregate being copied; qualifiers are
  331. /// ignored
  332. void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
  333. const AggValueSlot &src) {
  334. if (dest.requiresGCollection()) {
  335. CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
  336. llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
  337. CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
  338. dest.getAddress(),
  339. src.getAddress(),
  340. size);
  341. return;
  342. }
  343. // If the result of the assignment is used, copy the LHS there also.
  344. // It's volatile if either side is. Use the minimum alignment of
  345. // the two sides.
  346. LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
  347. LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
  348. CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
  349. dest.isVolatile() || src.isVolatile());
  350. }
  351. /// Emit the initializer for a std::initializer_list initialized with a
  352. /// real initializer list.
  353. void
  354. AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
  355. // Emit an array containing the elements. The array is externally destructed
  356. // if the std::initializer_list object is.
  357. ASTContext &Ctx = CGF.getContext();
  358. LValue Array = CGF.EmitLValue(E->getSubExpr());
  359. assert(Array.isSimple() && "initializer_list array not a simple lvalue");
  360. Address ArrayPtr = Array.getAddress(CGF);
  361. const ConstantArrayType *ArrayType =
  362. Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  363. assert(ArrayType && "std::initializer_list constructed from non-array");
  364. // FIXME: Perform the checks on the field types in SemaInit.
  365. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  366. RecordDecl::field_iterator Field = Record->field_begin();
  367. if (Field == Record->field_end()) {
  368. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  369. return;
  370. }
  371. // Start pointer.
  372. if (!Field->getType()->isPointerType() ||
  373. !Ctx.hasSameType(Field->getType()->getPointeeType(),
  374. ArrayType->getElementType())) {
  375. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  376. return;
  377. }
  378. AggValueSlot Dest = EnsureSlot(E->getType());
  379. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  380. LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
  381. llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
  382. llvm::Value *IdxStart[] = { Zero, Zero };
  383. llvm::Value *ArrayStart = Builder.CreateInBoundsGEP(
  384. ArrayPtr.getElementType(), ArrayPtr.getPointer(), IdxStart, "arraystart");
  385. CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
  386. ++Field;
  387. if (Field == Record->field_end()) {
  388. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  389. return;
  390. }
  391. llvm::Value *Size = Builder.getInt(ArrayType->getSize());
  392. LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
  393. if (Field->getType()->isPointerType() &&
  394. Ctx.hasSameType(Field->getType()->getPointeeType(),
  395. ArrayType->getElementType())) {
  396. // End pointer.
  397. llvm::Value *IdxEnd[] = { Zero, Size };
  398. llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
  399. ArrayPtr.getElementType(), ArrayPtr.getPointer(), IdxEnd, "arrayend");
  400. CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
  401. } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
  402. // Length.
  403. CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
  404. } else {
  405. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  406. return;
  407. }
  408. }
  409. /// Determine if E is a trivial array filler, that is, one that is
  410. /// equivalent to zero-initialization.
  411. static bool isTrivialFiller(Expr *E) {
  412. if (!E)
  413. return true;
  414. if (isa<ImplicitValueInitExpr>(E))
  415. return true;
  416. if (auto *ILE = dyn_cast<InitListExpr>(E)) {
  417. if (ILE->getNumInits())
  418. return false;
  419. return isTrivialFiller(ILE->getArrayFiller());
  420. }
  421. if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
  422. return Cons->getConstructor()->isDefaultConstructor() &&
  423. Cons->getConstructor()->isTrivial();
  424. // FIXME: Are there other cases where we can avoid emitting an initializer?
  425. return false;
  426. }
  427. /// Emit initialization of an array from an initializer list. ExprToVisit must
  428. /// be either an InitListEpxr a CXXParenInitListExpr.
  429. void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
  430. QualType ArrayQTy, Expr *ExprToVisit,
  431. ArrayRef<Expr *> Args, Expr *ArrayFiller) {
  432. uint64_t NumInitElements = Args.size();
  433. uint64_t NumArrayElements = AType->getNumElements();
  434. assert(NumInitElements <= NumArrayElements);
  435. QualType elementType =
  436. CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
  437. // DestPtr is an array*. Construct an elementType* by drilling
  438. // down a level.
  439. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  440. llvm::Value *indices[] = { zero, zero };
  441. llvm::Value *begin = Builder.CreateInBoundsGEP(
  442. DestPtr.getElementType(), DestPtr.getPointer(), indices,
  443. "arrayinit.begin");
  444. CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  445. CharUnits elementAlign =
  446. DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
  447. llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
  448. // Consider initializing the array by copying from a global. For this to be
  449. // more efficient than per-element initialization, the size of the elements
  450. // with explicit initializers should be large enough.
  451. if (NumInitElements * elementSize.getQuantity() > 16 &&
  452. elementType.isTriviallyCopyableType(CGF.getContext())) {
  453. CodeGen::CodeGenModule &CGM = CGF.CGM;
  454. ConstantEmitter Emitter(CGF);
  455. LangAS AS = ArrayQTy.getAddressSpace();
  456. if (llvm::Constant *C =
  457. Emitter.tryEmitForInitializer(ExprToVisit, AS, ArrayQTy)) {
  458. auto GV = new llvm::GlobalVariable(
  459. CGM.getModule(), C->getType(),
  460. CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
  461. llvm::GlobalValue::PrivateLinkage, C, "constinit",
  462. /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
  463. CGM.getContext().getTargetAddressSpace(AS));
  464. Emitter.finalize(GV);
  465. CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
  466. GV->setAlignment(Align.getAsAlign());
  467. Address GVAddr(GV, GV->getValueType(), Align);
  468. EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, ArrayQTy));
  469. return;
  470. }
  471. }
  472. // Exception safety requires us to destroy all the
  473. // already-constructed members if an initializer throws.
  474. // For that, we'll need an EH cleanup.
  475. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  476. Address endOfInit = Address::invalid();
  477. EHScopeStack::stable_iterator cleanup;
  478. llvm::Instruction *cleanupDominator = nullptr;
  479. if (CGF.needsEHCleanup(dtorKind)) {
  480. // In principle we could tell the cleanup where we are more
  481. // directly, but the control flow can get so varied here that it
  482. // would actually be quite complex. Therefore we go through an
  483. // alloca.
  484. endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
  485. "arrayinit.endOfInit");
  486. cleanupDominator = Builder.CreateStore(begin, endOfInit);
  487. CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
  488. elementAlign,
  489. CGF.getDestroyer(dtorKind));
  490. cleanup = CGF.EHStack.stable_begin();
  491. // Otherwise, remember that we didn't need a cleanup.
  492. } else {
  493. dtorKind = QualType::DK_none;
  494. }
  495. llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
  496. // The 'current element to initialize'. The invariants on this
  497. // variable are complicated. Essentially, after each iteration of
  498. // the loop, it points to the last initialized element, except
  499. // that it points to the beginning of the array before any
  500. // elements have been initialized.
  501. llvm::Value *element = begin;
  502. // Emit the explicit initializers.
  503. for (uint64_t i = 0; i != NumInitElements; ++i) {
  504. // Advance to the next element.
  505. if (i > 0) {
  506. element = Builder.CreateInBoundsGEP(
  507. llvmElementType, element, one, "arrayinit.element");
  508. // Tell the cleanup that it needs to destroy up to this
  509. // element. TODO: some of these stores can be trivially
  510. // observed to be unnecessary.
  511. if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
  512. }
  513. LValue elementLV = CGF.MakeAddrLValue(
  514. Address(element, llvmElementType, elementAlign), elementType);
  515. EmitInitializationToLValue(Args[i], elementLV);
  516. }
  517. // Check whether there's a non-trivial array-fill expression.
  518. bool hasTrivialFiller = isTrivialFiller(ArrayFiller);
  519. // Any remaining elements need to be zero-initialized, possibly
  520. // using the filler expression. We can skip this if the we're
  521. // emitting to zeroed memory.
  522. if (NumInitElements != NumArrayElements &&
  523. !(Dest.isZeroed() && hasTrivialFiller &&
  524. CGF.getTypes().isZeroInitializable(elementType))) {
  525. // Use an actual loop. This is basically
  526. // do { *array++ = filler; } while (array != end);
  527. // Advance to the start of the rest of the array.
  528. if (NumInitElements) {
  529. element = Builder.CreateInBoundsGEP(
  530. llvmElementType, element, one, "arrayinit.start");
  531. if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
  532. }
  533. // Compute the end of the array.
  534. llvm::Value *end = Builder.CreateInBoundsGEP(
  535. llvmElementType, begin,
  536. llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
  537. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  538. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  539. // Jump into the body.
  540. CGF.EmitBlock(bodyBB);
  541. llvm::PHINode *currentElement =
  542. Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
  543. currentElement->addIncoming(element, entryBB);
  544. // Emit the actual filler expression.
  545. {
  546. // C++1z [class.temporary]p5:
  547. // when a default constructor is called to initialize an element of
  548. // an array with no corresponding initializer [...] the destruction of
  549. // every temporary created in a default argument is sequenced before
  550. // the construction of the next array element, if any
  551. CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
  552. LValue elementLV = CGF.MakeAddrLValue(
  553. Address(currentElement, llvmElementType, elementAlign), elementType);
  554. if (ArrayFiller)
  555. EmitInitializationToLValue(ArrayFiller, elementLV);
  556. else
  557. EmitNullInitializationToLValue(elementLV);
  558. }
  559. // Move on to the next element.
  560. llvm::Value *nextElement = Builder.CreateInBoundsGEP(
  561. llvmElementType, currentElement, one, "arrayinit.next");
  562. // Tell the EH cleanup that we finished with the last element.
  563. if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
  564. // Leave the loop if we're done.
  565. llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
  566. "arrayinit.done");
  567. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  568. Builder.CreateCondBr(done, endBB, bodyBB);
  569. currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
  570. CGF.EmitBlock(endBB);
  571. }
  572. // Leave the partial-array cleanup if we entered one.
  573. if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
  574. }
  575. //===----------------------------------------------------------------------===//
  576. // Visitor Methods
  577. //===----------------------------------------------------------------------===//
  578. void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
  579. Visit(E->getSubExpr());
  580. }
  581. void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
  582. // If this is a unique OVE, just visit its source expression.
  583. if (e->isUnique())
  584. Visit(e->getSourceExpr());
  585. else
  586. EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
  587. }
  588. void
  589. AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  590. if (Dest.isPotentiallyAliased() &&
  591. E->getType().isPODType(CGF.getContext())) {
  592. // For a POD type, just emit a load of the lvalue + a copy, because our
  593. // compound literal might alias the destination.
  594. EmitAggLoadOfLValue(E);
  595. return;
  596. }
  597. AggValueSlot Slot = EnsureSlot(E->getType());
  598. // Block-scope compound literals are destroyed at the end of the enclosing
  599. // scope in C.
  600. bool Destruct =
  601. !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
  602. if (Destruct)
  603. Slot.setExternallyDestructed();
  604. CGF.EmitAggExpr(E->getInitializer(), Slot);
  605. if (Destruct)
  606. if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
  607. CGF.pushLifetimeExtendedDestroy(
  608. CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
  609. CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
  610. }
  611. /// Attempt to look through various unimportant expressions to find a
  612. /// cast of the given kind.
  613. static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
  614. op = op->IgnoreParenNoopCasts(ctx);
  615. if (auto castE = dyn_cast<CastExpr>(op)) {
  616. if (castE->getCastKind() == kind)
  617. return castE->getSubExpr();
  618. }
  619. return nullptr;
  620. }
  621. void AggExprEmitter::VisitCastExpr(CastExpr *E) {
  622. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
  623. CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
  624. switch (E->getCastKind()) {
  625. case CK_Dynamic: {
  626. // FIXME: Can this actually happen? We have no test coverage for it.
  627. assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
  628. LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
  629. CodeGenFunction::TCK_Load);
  630. // FIXME: Do we also need to handle property references here?
  631. if (LV.isSimple())
  632. CGF.EmitDynamicCast(LV.getAddress(CGF), cast<CXXDynamicCastExpr>(E));
  633. else
  634. CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
  635. if (!Dest.isIgnored())
  636. CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
  637. break;
  638. }
  639. case CK_ToUnion: {
  640. // Evaluate even if the destination is ignored.
  641. if (Dest.isIgnored()) {
  642. CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
  643. /*ignoreResult=*/true);
  644. break;
  645. }
  646. // GCC union extension
  647. QualType Ty = E->getSubExpr()->getType();
  648. Address CastPtr =
  649. Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
  650. EmitInitializationToLValue(E->getSubExpr(),
  651. CGF.MakeAddrLValue(CastPtr, Ty));
  652. break;
  653. }
  654. case CK_LValueToRValueBitCast: {
  655. if (Dest.isIgnored()) {
  656. CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
  657. /*ignoreResult=*/true);
  658. break;
  659. }
  660. LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
  661. Address SourceAddress =
  662. Builder.CreateElementBitCast(SourceLV.getAddress(CGF), CGF.Int8Ty);
  663. Address DestAddress =
  664. Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty);
  665. llvm::Value *SizeVal = llvm::ConstantInt::get(
  666. CGF.SizeTy,
  667. CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
  668. Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
  669. break;
  670. }
  671. case CK_DerivedToBase:
  672. case CK_BaseToDerived:
  673. case CK_UncheckedDerivedToBase: {
  674. llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
  675. "should have been unpacked before we got here");
  676. }
  677. case CK_NonAtomicToAtomic:
  678. case CK_AtomicToNonAtomic: {
  679. bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
  680. // Determine the atomic and value types.
  681. QualType atomicType = E->getSubExpr()->getType();
  682. QualType valueType = E->getType();
  683. if (isToAtomic) std::swap(atomicType, valueType);
  684. assert(atomicType->isAtomicType());
  685. assert(CGF.getContext().hasSameUnqualifiedType(valueType,
  686. atomicType->castAs<AtomicType>()->getValueType()));
  687. // Just recurse normally if we're ignoring the result or the
  688. // atomic type doesn't change representation.
  689. if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
  690. return Visit(E->getSubExpr());
  691. }
  692. CastKind peepholeTarget =
  693. (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
  694. // These two cases are reverses of each other; try to peephole them.
  695. if (Expr *op =
  696. findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
  697. assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
  698. E->getType()) &&
  699. "peephole significantly changed types?");
  700. return Visit(op);
  701. }
  702. // If we're converting an r-value of non-atomic type to an r-value
  703. // of atomic type, just emit directly into the relevant sub-object.
  704. if (isToAtomic) {
  705. AggValueSlot valueDest = Dest;
  706. if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
  707. // Zero-initialize. (Strictly speaking, we only need to initialize
  708. // the padding at the end, but this is simpler.)
  709. if (!Dest.isZeroed())
  710. CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
  711. // Build a GEP to refer to the subobject.
  712. Address valueAddr =
  713. CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
  714. valueDest = AggValueSlot::forAddr(valueAddr,
  715. valueDest.getQualifiers(),
  716. valueDest.isExternallyDestructed(),
  717. valueDest.requiresGCollection(),
  718. valueDest.isPotentiallyAliased(),
  719. AggValueSlot::DoesNotOverlap,
  720. AggValueSlot::IsZeroed);
  721. }
  722. CGF.EmitAggExpr(E->getSubExpr(), valueDest);
  723. return;
  724. }
  725. // Otherwise, we're converting an atomic type to a non-atomic type.
  726. // Make an atomic temporary, emit into that, and then copy the value out.
  727. AggValueSlot atomicSlot =
  728. CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
  729. CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
  730. Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
  731. RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
  732. return EmitFinalDestCopy(valueType, rvalue);
  733. }
  734. case CK_AddressSpaceConversion:
  735. return Visit(E->getSubExpr());
  736. case CK_LValueToRValue:
  737. // If we're loading from a volatile type, force the destination
  738. // into existence.
  739. if (E->getSubExpr()->getType().isVolatileQualified()) {
  740. bool Destruct =
  741. !Dest.isExternallyDestructed() &&
  742. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
  743. if (Destruct)
  744. Dest.setExternallyDestructed();
  745. EnsureDest(E->getType());
  746. Visit(E->getSubExpr());
  747. if (Destruct)
  748. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  749. E->getType());
  750. return;
  751. }
  752. [[fallthrough]];
  753. case CK_NoOp:
  754. case CK_UserDefinedConversion:
  755. case CK_ConstructorConversion:
  756. assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
  757. E->getType()) &&
  758. "Implicit cast types must be compatible");
  759. Visit(E->getSubExpr());
  760. break;
  761. case CK_LValueBitCast:
  762. llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
  763. case CK_Dependent:
  764. case CK_BitCast:
  765. case CK_ArrayToPointerDecay:
  766. case CK_FunctionToPointerDecay:
  767. case CK_NullToPointer:
  768. case CK_NullToMemberPointer:
  769. case CK_BaseToDerivedMemberPointer:
  770. case CK_DerivedToBaseMemberPointer:
  771. case CK_MemberPointerToBoolean:
  772. case CK_ReinterpretMemberPointer:
  773. case CK_IntegralToPointer:
  774. case CK_PointerToIntegral:
  775. case CK_PointerToBoolean:
  776. case CK_ToVoid:
  777. case CK_VectorSplat:
  778. case CK_IntegralCast:
  779. case CK_BooleanToSignedIntegral:
  780. case CK_IntegralToBoolean:
  781. case CK_IntegralToFloating:
  782. case CK_FloatingToIntegral:
  783. case CK_FloatingToBoolean:
  784. case CK_FloatingCast:
  785. case CK_CPointerToObjCPointerCast:
  786. case CK_BlockPointerToObjCPointerCast:
  787. case CK_AnyPointerToBlockPointerCast:
  788. case CK_ObjCObjectLValueCast:
  789. case CK_FloatingRealToComplex:
  790. case CK_FloatingComplexToReal:
  791. case CK_FloatingComplexToBoolean:
  792. case CK_FloatingComplexCast:
  793. case CK_FloatingComplexToIntegralComplex:
  794. case CK_IntegralRealToComplex:
  795. case CK_IntegralComplexToReal:
  796. case CK_IntegralComplexToBoolean:
  797. case CK_IntegralComplexCast:
  798. case CK_IntegralComplexToFloatingComplex:
  799. case CK_ARCProduceObject:
  800. case CK_ARCConsumeObject:
  801. case CK_ARCReclaimReturnedObject:
  802. case CK_ARCExtendBlockObject:
  803. case CK_CopyAndAutoreleaseBlockObject:
  804. case CK_BuiltinFnToFnPtr:
  805. case CK_ZeroToOCLOpaqueType:
  806. case CK_MatrixCast:
  807. case CK_IntToOCLSampler:
  808. case CK_FloatingToFixedPoint:
  809. case CK_FixedPointToFloating:
  810. case CK_FixedPointCast:
  811. case CK_FixedPointToBoolean:
  812. case CK_FixedPointToIntegral:
  813. case CK_IntegralToFixedPoint:
  814. llvm_unreachable("cast kind invalid for aggregate types");
  815. }
  816. }
  817. void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
  818. if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
  819. EmitAggLoadOfLValue(E);
  820. return;
  821. }
  822. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  823. return CGF.EmitCallExpr(E, Slot);
  824. });
  825. }
  826. void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  827. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  828. return CGF.EmitObjCMessageExpr(E, Slot);
  829. });
  830. }
  831. void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
  832. CGF.EmitIgnoredExpr(E->getLHS());
  833. Visit(E->getRHS());
  834. }
  835. void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  836. CodeGenFunction::StmtExprEvaluation eval(CGF);
  837. CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
  838. }
  839. enum CompareKind {
  840. CK_Less,
  841. CK_Greater,
  842. CK_Equal,
  843. };
  844. static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
  845. const BinaryOperator *E, llvm::Value *LHS,
  846. llvm::Value *RHS, CompareKind Kind,
  847. const char *NameSuffix = "") {
  848. QualType ArgTy = E->getLHS()->getType();
  849. if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
  850. ArgTy = CT->getElementType();
  851. if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
  852. assert(Kind == CK_Equal &&
  853. "member pointers may only be compared for equality");
  854. return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  855. CGF, LHS, RHS, MPT, /*IsInequality*/ false);
  856. }
  857. // Compute the comparison instructions for the specified comparison kind.
  858. struct CmpInstInfo {
  859. const char *Name;
  860. llvm::CmpInst::Predicate FCmp;
  861. llvm::CmpInst::Predicate SCmp;
  862. llvm::CmpInst::Predicate UCmp;
  863. };
  864. CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
  865. using FI = llvm::FCmpInst;
  866. using II = llvm::ICmpInst;
  867. switch (Kind) {
  868. case CK_Less:
  869. return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
  870. case CK_Greater:
  871. return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
  872. case CK_Equal:
  873. return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
  874. }
  875. llvm_unreachable("Unrecognised CompareKind enum");
  876. }();
  877. if (ArgTy->hasFloatingRepresentation())
  878. return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
  879. llvm::Twine(InstInfo.Name) + NameSuffix);
  880. if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
  881. auto Inst =
  882. ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
  883. return Builder.CreateICmp(Inst, LHS, RHS,
  884. llvm::Twine(InstInfo.Name) + NameSuffix);
  885. }
  886. llvm_unreachable("unsupported aggregate binary expression should have "
  887. "already been handled");
  888. }
  889. void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
  890. using llvm::BasicBlock;
  891. using llvm::PHINode;
  892. using llvm::Value;
  893. assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
  894. E->getRHS()->getType()));
  895. const ComparisonCategoryInfo &CmpInfo =
  896. CGF.getContext().CompCategories.getInfoForType(E->getType());
  897. assert(CmpInfo.Record->isTriviallyCopyable() &&
  898. "cannot copy non-trivially copyable aggregate");
  899. QualType ArgTy = E->getLHS()->getType();
  900. if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
  901. !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
  902. !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
  903. return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
  904. }
  905. bool IsComplex = ArgTy->isAnyComplexType();
  906. // Evaluate the operands to the expression and extract their values.
  907. auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
  908. RValue RV = CGF.EmitAnyExpr(E);
  909. if (RV.isScalar())
  910. return {RV.getScalarVal(), nullptr};
  911. if (RV.isAggregate())
  912. return {RV.getAggregatePointer(), nullptr};
  913. assert(RV.isComplex());
  914. return RV.getComplexVal();
  915. };
  916. auto LHSValues = EmitOperand(E->getLHS()),
  917. RHSValues = EmitOperand(E->getRHS());
  918. auto EmitCmp = [&](CompareKind K) {
  919. Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
  920. K, IsComplex ? ".r" : "");
  921. if (!IsComplex)
  922. return Cmp;
  923. assert(K == CompareKind::CK_Equal);
  924. Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
  925. RHSValues.second, K, ".i");
  926. return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
  927. };
  928. auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
  929. return Builder.getInt(VInfo->getIntValue());
  930. };
  931. Value *Select;
  932. if (ArgTy->isNullPtrType()) {
  933. Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
  934. } else if (!CmpInfo.isPartial()) {
  935. Value *SelectOne =
  936. Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
  937. EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
  938. Select = Builder.CreateSelect(EmitCmp(CK_Equal),
  939. EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  940. SelectOne, "sel.eq");
  941. } else {
  942. Value *SelectEq = Builder.CreateSelect(
  943. EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  944. EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
  945. Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
  946. EmitCmpRes(CmpInfo.getGreater()),
  947. SelectEq, "sel.gt");
  948. Select = Builder.CreateSelect(
  949. EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
  950. }
  951. // Create the return value in the destination slot.
  952. EnsureDest(E->getType());
  953. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  954. // Emit the address of the first (and only) field in the comparison category
  955. // type, and initialize it from the constant integer value selected above.
  956. LValue FieldLV = CGF.EmitLValueForFieldInitialization(
  957. DestLV, *CmpInfo.Record->field_begin());
  958. CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
  959. // All done! The result is in the Dest slot.
  960. }
  961. void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  962. if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
  963. VisitPointerToDataMemberBinaryOperator(E);
  964. else
  965. CGF.ErrorUnsupported(E, "aggregate binary expression");
  966. }
  967. void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
  968. const BinaryOperator *E) {
  969. LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
  970. EmitFinalDestCopy(E->getType(), LV);
  971. }
  972. /// Is the value of the given expression possibly a reference to or
  973. /// into a __block variable?
  974. static bool isBlockVarRef(const Expr *E) {
  975. // Make sure we look through parens.
  976. E = E->IgnoreParens();
  977. // Check for a direct reference to a __block variable.
  978. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  979. const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  980. return (var && var->hasAttr<BlocksAttr>());
  981. }
  982. // More complicated stuff.
  983. // Binary operators.
  984. if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
  985. // For an assignment or pointer-to-member operation, just care
  986. // about the LHS.
  987. if (op->isAssignmentOp() || op->isPtrMemOp())
  988. return isBlockVarRef(op->getLHS());
  989. // For a comma, just care about the RHS.
  990. if (op->getOpcode() == BO_Comma)
  991. return isBlockVarRef(op->getRHS());
  992. // FIXME: pointer arithmetic?
  993. return false;
  994. // Check both sides of a conditional operator.
  995. } else if (const AbstractConditionalOperator *op
  996. = dyn_cast<AbstractConditionalOperator>(E)) {
  997. return isBlockVarRef(op->getTrueExpr())
  998. || isBlockVarRef(op->getFalseExpr());
  999. // OVEs are required to support BinaryConditionalOperators.
  1000. } else if (const OpaqueValueExpr *op
  1001. = dyn_cast<OpaqueValueExpr>(E)) {
  1002. if (const Expr *src = op->getSourceExpr())
  1003. return isBlockVarRef(src);
  1004. // Casts are necessary to get things like (*(int*)&var) = foo().
  1005. // We don't really care about the kind of cast here, except
  1006. // we don't want to look through l2r casts, because it's okay
  1007. // to get the *value* in a __block variable.
  1008. } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
  1009. if (cast->getCastKind() == CK_LValueToRValue)
  1010. return false;
  1011. return isBlockVarRef(cast->getSubExpr());
  1012. // Handle unary operators. Again, just aggressively look through
  1013. // it, ignoring the operation.
  1014. } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
  1015. return isBlockVarRef(uop->getSubExpr());
  1016. // Look into the base of a field access.
  1017. } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  1018. return isBlockVarRef(mem->getBase());
  1019. // Look into the base of a subscript.
  1020. } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
  1021. return isBlockVarRef(sub->getBase());
  1022. }
  1023. return false;
  1024. }
  1025. void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  1026. // For an assignment to work, the value on the right has
  1027. // to be compatible with the value on the left.
  1028. assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
  1029. E->getRHS()->getType())
  1030. && "Invalid assignment");
  1031. // If the LHS might be a __block variable, and the RHS can
  1032. // potentially cause a block copy, we need to evaluate the RHS first
  1033. // so that the assignment goes the right place.
  1034. // This is pretty semantically fragile.
  1035. if (isBlockVarRef(E->getLHS()) &&
  1036. E->getRHS()->HasSideEffects(CGF.getContext())) {
  1037. // Ensure that we have a destination, and evaluate the RHS into that.
  1038. EnsureDest(E->getRHS()->getType());
  1039. Visit(E->getRHS());
  1040. // Now emit the LHS and copy into it.
  1041. LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  1042. // That copy is an atomic copy if the LHS is atomic.
  1043. if (LHS.getType()->isAtomicType() ||
  1044. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1045. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1046. return;
  1047. }
  1048. EmitCopy(E->getLHS()->getType(),
  1049. AggValueSlot::forLValue(LHS, CGF, AggValueSlot::IsDestructed,
  1050. needsGC(E->getLHS()->getType()),
  1051. AggValueSlot::IsAliased,
  1052. AggValueSlot::MayOverlap),
  1053. Dest);
  1054. return;
  1055. }
  1056. LValue LHS = CGF.EmitLValue(E->getLHS());
  1057. // If we have an atomic type, evaluate into the destination and then
  1058. // do an atomic copy.
  1059. if (LHS.getType()->isAtomicType() ||
  1060. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1061. EnsureDest(E->getRHS()->getType());
  1062. Visit(E->getRHS());
  1063. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1064. return;
  1065. }
  1066. // Codegen the RHS so that it stores directly into the LHS.
  1067. AggValueSlot LHSSlot = AggValueSlot::forLValue(
  1068. LHS, CGF, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
  1069. AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
  1070. // A non-volatile aggregate destination might have volatile member.
  1071. if (!LHSSlot.isVolatile() &&
  1072. CGF.hasVolatileMember(E->getLHS()->getType()))
  1073. LHSSlot.setVolatile(true);
  1074. CGF.EmitAggExpr(E->getRHS(), LHSSlot);
  1075. // Copy into the destination if the assignment isn't ignored.
  1076. EmitFinalDestCopy(E->getType(), LHS);
  1077. if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
  1078. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  1079. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  1080. E->getType());
  1081. }
  1082. void AggExprEmitter::
  1083. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  1084. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  1085. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  1086. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  1087. // Bind the common expression if necessary.
  1088. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  1089. CodeGenFunction::ConditionalEvaluation eval(CGF);
  1090. CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
  1091. CGF.getProfileCount(E));
  1092. // Save whether the destination's lifetime is externally managed.
  1093. bool isExternallyDestructed = Dest.isExternallyDestructed();
  1094. bool destructNonTrivialCStruct =
  1095. !isExternallyDestructed &&
  1096. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
  1097. isExternallyDestructed |= destructNonTrivialCStruct;
  1098. Dest.setExternallyDestructed(isExternallyDestructed);
  1099. eval.begin(CGF);
  1100. CGF.EmitBlock(LHSBlock);
  1101. CGF.incrementProfileCounter(E);
  1102. Visit(E->getTrueExpr());
  1103. eval.end(CGF);
  1104. assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
  1105. CGF.Builder.CreateBr(ContBlock);
  1106. // If the result of an agg expression is unused, then the emission
  1107. // of the LHS might need to create a destination slot. That's fine
  1108. // with us, and we can safely emit the RHS into the same slot, but
  1109. // we shouldn't claim that it's already being destructed.
  1110. Dest.setExternallyDestructed(isExternallyDestructed);
  1111. eval.begin(CGF);
  1112. CGF.EmitBlock(RHSBlock);
  1113. Visit(E->getFalseExpr());
  1114. eval.end(CGF);
  1115. if (destructNonTrivialCStruct)
  1116. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  1117. E->getType());
  1118. CGF.EmitBlock(ContBlock);
  1119. }
  1120. void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
  1121. Visit(CE->getChosenSubExpr());
  1122. }
  1123. void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  1124. Address ArgValue = Address::invalid();
  1125. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  1126. // If EmitVAArg fails, emit an error.
  1127. if (!ArgPtr.isValid()) {
  1128. CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
  1129. return;
  1130. }
  1131. EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
  1132. }
  1133. void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1134. // Ensure that we have a slot, but if we already do, remember
  1135. // whether it was externally destructed.
  1136. bool wasExternallyDestructed = Dest.isExternallyDestructed();
  1137. EnsureDest(E->getType());
  1138. // We're going to push a destructor if there isn't already one.
  1139. Dest.setExternallyDestructed();
  1140. Visit(E->getSubExpr());
  1141. // Push that destructor we promised.
  1142. if (!wasExternallyDestructed)
  1143. CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
  1144. }
  1145. void
  1146. AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  1147. AggValueSlot Slot = EnsureSlot(E->getType());
  1148. CGF.EmitCXXConstructExpr(E, Slot);
  1149. }
  1150. void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
  1151. const CXXInheritedCtorInitExpr *E) {
  1152. AggValueSlot Slot = EnsureSlot(E->getType());
  1153. CGF.EmitInheritedCXXConstructorCall(
  1154. E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
  1155. E->inheritedFromVBase(), E);
  1156. }
  1157. void
  1158. AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
  1159. AggValueSlot Slot = EnsureSlot(E->getType());
  1160. LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
  1161. // We'll need to enter cleanup scopes in case any of the element
  1162. // initializers throws an exception.
  1163. SmallVector<EHScopeStack::stable_iterator, 16> Cleanups;
  1164. llvm::Instruction *CleanupDominator = nullptr;
  1165. CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
  1166. for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
  1167. e = E->capture_init_end();
  1168. i != e; ++i, ++CurField) {
  1169. // Emit initialization
  1170. LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
  1171. if (CurField->hasCapturedVLAType()) {
  1172. CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
  1173. continue;
  1174. }
  1175. EmitInitializationToLValue(*i, LV);
  1176. // Push a destructor if necessary.
  1177. if (QualType::DestructionKind DtorKind =
  1178. CurField->getType().isDestructedType()) {
  1179. assert(LV.isSimple());
  1180. if (CGF.needsEHCleanup(DtorKind)) {
  1181. if (!CleanupDominator)
  1182. CleanupDominator = CGF.Builder.CreateAlignedLoad(
  1183. CGF.Int8Ty,
  1184. llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1185. CharUnits::One()); // placeholder
  1186. CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(),
  1187. CGF.getDestroyer(DtorKind), false);
  1188. Cleanups.push_back(CGF.EHStack.stable_begin());
  1189. }
  1190. }
  1191. }
  1192. // Deactivate all the partial cleanups in reverse order, which
  1193. // generally means popping them.
  1194. for (unsigned i = Cleanups.size(); i != 0; --i)
  1195. CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
  1196. // Destroy the placeholder if we made one.
  1197. if (CleanupDominator)
  1198. CleanupDominator->eraseFromParent();
  1199. }
  1200. void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  1201. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  1202. Visit(E->getSubExpr());
  1203. }
  1204. void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  1205. QualType T = E->getType();
  1206. AggValueSlot Slot = EnsureSlot(T);
  1207. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1208. }
  1209. void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  1210. QualType T = E->getType();
  1211. AggValueSlot Slot = EnsureSlot(T);
  1212. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1213. }
  1214. /// Determine whether the given cast kind is known to always convert values
  1215. /// with all zero bits in their value representation to values with all zero
  1216. /// bits in their value representation.
  1217. static bool castPreservesZero(const CastExpr *CE) {
  1218. switch (CE->getCastKind()) {
  1219. // No-ops.
  1220. case CK_NoOp:
  1221. case CK_UserDefinedConversion:
  1222. case CK_ConstructorConversion:
  1223. case CK_BitCast:
  1224. case CK_ToUnion:
  1225. case CK_ToVoid:
  1226. // Conversions between (possibly-complex) integral, (possibly-complex)
  1227. // floating-point, and bool.
  1228. case CK_BooleanToSignedIntegral:
  1229. case CK_FloatingCast:
  1230. case CK_FloatingComplexCast:
  1231. case CK_FloatingComplexToBoolean:
  1232. case CK_FloatingComplexToIntegralComplex:
  1233. case CK_FloatingComplexToReal:
  1234. case CK_FloatingRealToComplex:
  1235. case CK_FloatingToBoolean:
  1236. case CK_FloatingToIntegral:
  1237. case CK_IntegralCast:
  1238. case CK_IntegralComplexCast:
  1239. case CK_IntegralComplexToBoolean:
  1240. case CK_IntegralComplexToFloatingComplex:
  1241. case CK_IntegralComplexToReal:
  1242. case CK_IntegralRealToComplex:
  1243. case CK_IntegralToBoolean:
  1244. case CK_IntegralToFloating:
  1245. // Reinterpreting integers as pointers and vice versa.
  1246. case CK_IntegralToPointer:
  1247. case CK_PointerToIntegral:
  1248. // Language extensions.
  1249. case CK_VectorSplat:
  1250. case CK_MatrixCast:
  1251. case CK_NonAtomicToAtomic:
  1252. case CK_AtomicToNonAtomic:
  1253. return true;
  1254. case CK_BaseToDerivedMemberPointer:
  1255. case CK_DerivedToBaseMemberPointer:
  1256. case CK_MemberPointerToBoolean:
  1257. case CK_NullToMemberPointer:
  1258. case CK_ReinterpretMemberPointer:
  1259. // FIXME: ABI-dependent.
  1260. return false;
  1261. case CK_AnyPointerToBlockPointerCast:
  1262. case CK_BlockPointerToObjCPointerCast:
  1263. case CK_CPointerToObjCPointerCast:
  1264. case CK_ObjCObjectLValueCast:
  1265. case CK_IntToOCLSampler:
  1266. case CK_ZeroToOCLOpaqueType:
  1267. // FIXME: Check these.
  1268. return false;
  1269. case CK_FixedPointCast:
  1270. case CK_FixedPointToBoolean:
  1271. case CK_FixedPointToFloating:
  1272. case CK_FixedPointToIntegral:
  1273. case CK_FloatingToFixedPoint:
  1274. case CK_IntegralToFixedPoint:
  1275. // FIXME: Do all fixed-point types represent zero as all 0 bits?
  1276. return false;
  1277. case CK_AddressSpaceConversion:
  1278. case CK_BaseToDerived:
  1279. case CK_DerivedToBase:
  1280. case CK_Dynamic:
  1281. case CK_NullToPointer:
  1282. case CK_PointerToBoolean:
  1283. // FIXME: Preserves zeroes only if zero pointers and null pointers have the
  1284. // same representation in all involved address spaces.
  1285. return false;
  1286. case CK_ARCConsumeObject:
  1287. case CK_ARCExtendBlockObject:
  1288. case CK_ARCProduceObject:
  1289. case CK_ARCReclaimReturnedObject:
  1290. case CK_CopyAndAutoreleaseBlockObject:
  1291. case CK_ArrayToPointerDecay:
  1292. case CK_FunctionToPointerDecay:
  1293. case CK_BuiltinFnToFnPtr:
  1294. case CK_Dependent:
  1295. case CK_LValueBitCast:
  1296. case CK_LValueToRValue:
  1297. case CK_LValueToRValueBitCast:
  1298. case CK_UncheckedDerivedToBase:
  1299. return false;
  1300. }
  1301. llvm_unreachable("Unhandled clang::CastKind enum");
  1302. }
  1303. /// isSimpleZero - If emitting this value will obviously just cause a store of
  1304. /// zero to memory, return true. This can return false if uncertain, so it just
  1305. /// handles simple cases.
  1306. static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
  1307. E = E->IgnoreParens();
  1308. while (auto *CE = dyn_cast<CastExpr>(E)) {
  1309. if (!castPreservesZero(CE))
  1310. break;
  1311. E = CE->getSubExpr()->IgnoreParens();
  1312. }
  1313. // 0
  1314. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
  1315. return IL->getValue() == 0;
  1316. // +0.0
  1317. if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
  1318. return FL->getValue().isPosZero();
  1319. // int()
  1320. if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
  1321. CGF.getTypes().isZeroInitializable(E->getType()))
  1322. return true;
  1323. // (int*)0 - Null pointer expressions.
  1324. if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
  1325. return ICE->getCastKind() == CK_NullToPointer &&
  1326. CGF.getTypes().isPointerZeroInitializable(E->getType()) &&
  1327. !E->HasSideEffects(CGF.getContext());
  1328. // '\0'
  1329. if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
  1330. return CL->getValue() == 0;
  1331. // Otherwise, hard case: conservatively return false.
  1332. return false;
  1333. }
  1334. void
  1335. AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
  1336. QualType type = LV.getType();
  1337. // FIXME: Ignore result?
  1338. // FIXME: Are initializers affected by volatile?
  1339. if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
  1340. // Storing "i32 0" to a zero'd memory location is a noop.
  1341. return;
  1342. } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
  1343. return EmitNullInitializationToLValue(LV);
  1344. } else if (isa<NoInitExpr>(E)) {
  1345. // Do nothing.
  1346. return;
  1347. } else if (type->isReferenceType()) {
  1348. RValue RV = CGF.EmitReferenceBindingToExpr(E);
  1349. return CGF.EmitStoreThroughLValue(RV, LV);
  1350. }
  1351. switch (CGF.getEvaluationKind(type)) {
  1352. case TEK_Complex:
  1353. CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
  1354. return;
  1355. case TEK_Aggregate:
  1356. CGF.EmitAggExpr(
  1357. E, AggValueSlot::forLValue(LV, CGF, AggValueSlot::IsDestructed,
  1358. AggValueSlot::DoesNotNeedGCBarriers,
  1359. AggValueSlot::IsNotAliased,
  1360. AggValueSlot::MayOverlap, Dest.isZeroed()));
  1361. return;
  1362. case TEK_Scalar:
  1363. if (LV.isSimple()) {
  1364. CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
  1365. } else {
  1366. CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
  1367. }
  1368. return;
  1369. }
  1370. llvm_unreachable("bad evaluation kind");
  1371. }
  1372. void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
  1373. QualType type = lv.getType();
  1374. // If the destination slot is already zeroed out before the aggregate is
  1375. // copied into it, we don't have to emit any zeros here.
  1376. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
  1377. return;
  1378. if (CGF.hasScalarEvaluationKind(type)) {
  1379. // For non-aggregates, we can store the appropriate null constant.
  1380. llvm::Value *null = CGF.CGM.EmitNullConstant(type);
  1381. // Note that the following is not equivalent to
  1382. // EmitStoreThroughBitfieldLValue for ARC types.
  1383. if (lv.isBitField()) {
  1384. CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
  1385. } else {
  1386. assert(lv.isSimple());
  1387. CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
  1388. }
  1389. } else {
  1390. // There's a potential optimization opportunity in combining
  1391. // memsets; that would be easy for arrays, but relatively
  1392. // difficult for structures with the current code.
  1393. CGF.EmitNullInitialization(lv.getAddress(CGF), lv.getType());
  1394. }
  1395. }
  1396. void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
  1397. VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
  1398. E->getInitializedFieldInUnion(),
  1399. E->getArrayFiller());
  1400. }
  1401. void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1402. if (E->hadArrayRangeDesignator())
  1403. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1404. if (E->isTransparent())
  1405. return Visit(E->getInit(0));
  1406. VisitCXXParenListOrInitListExpr(
  1407. E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());
  1408. }
  1409. void AggExprEmitter::VisitCXXParenListOrInitListExpr(
  1410. Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,
  1411. FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {
  1412. #if 0
  1413. // FIXME: Assess perf here? Figure out what cases are worth optimizing here
  1414. // (Length of globals? Chunks of zeroed-out space?).
  1415. //
  1416. // If we can, prefer a copy from a global; this is a lot less code for long
  1417. // globals, and it's easier for the current optimizers to analyze.
  1418. if (llvm::Constant *C =
  1419. CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {
  1420. llvm::GlobalVariable* GV =
  1421. new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
  1422. llvm::GlobalValue::InternalLinkage, C, "");
  1423. EmitFinalDestCopy(ExprToVisit->getType(),
  1424. CGF.MakeAddrLValue(GV, ExprToVisit->getType()));
  1425. return;
  1426. }
  1427. #endif
  1428. AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());
  1429. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());
  1430. // Handle initialization of an array.
  1431. if (ExprToVisit->getType()->isArrayType()) {
  1432. auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
  1433. EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,
  1434. InitExprs, ArrayFiller);
  1435. return;
  1436. }
  1437. assert(ExprToVisit->getType()->isRecordType() &&
  1438. "Only support structs/unions here!");
  1439. // Do struct initialization; this code just sets each individual member
  1440. // to the approprate value. This makes bitfield support automatic;
  1441. // the disadvantage is that the generated code is more difficult for
  1442. // the optimizer, especially with bitfields.
  1443. unsigned NumInitElements = InitExprs.size();
  1444. RecordDecl *record = ExprToVisit->getType()->castAs<RecordType>()->getDecl();
  1445. // We'll need to enter cleanup scopes in case any of the element
  1446. // initializers throws an exception.
  1447. SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
  1448. llvm::Instruction *cleanupDominator = nullptr;
  1449. auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) {
  1450. cleanups.push_back(cleanup);
  1451. if (!cleanupDominator) // create placeholder once needed
  1452. cleanupDominator = CGF.Builder.CreateAlignedLoad(
  1453. CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1454. CharUnits::One());
  1455. };
  1456. unsigned curInitIndex = 0;
  1457. // Emit initialization of base classes.
  1458. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
  1459. assert(NumInitElements >= CXXRD->getNumBases() &&
  1460. "missing initializer for base class");
  1461. for (auto &Base : CXXRD->bases()) {
  1462. assert(!Base.isVirtual() && "should not see vbases here");
  1463. auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
  1464. Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
  1465. Dest.getAddress(), CXXRD, BaseRD,
  1466. /*isBaseVirtual*/ false);
  1467. AggValueSlot AggSlot = AggValueSlot::forAddr(
  1468. V, Qualifiers(),
  1469. AggValueSlot::IsDestructed,
  1470. AggValueSlot::DoesNotNeedGCBarriers,
  1471. AggValueSlot::IsNotAliased,
  1472. CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
  1473. CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);
  1474. if (QualType::DestructionKind dtorKind =
  1475. Base.getType().isDestructedType()) {
  1476. CGF.pushDestroy(dtorKind, V, Base.getType());
  1477. addCleanup(CGF.EHStack.stable_begin());
  1478. }
  1479. }
  1480. }
  1481. // Prepare a 'this' for CXXDefaultInitExprs.
  1482. CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
  1483. if (record->isUnion()) {
  1484. // Only initialize one field of a union. The field itself is
  1485. // specified by the initializer list.
  1486. if (!InitializedFieldInUnion) {
  1487. // Empty union; we have nothing to do.
  1488. #ifndef NDEBUG
  1489. // Make sure that it's really an empty and not a failure of
  1490. // semantic analysis.
  1491. for (const auto *Field : record->fields())
  1492. assert((Field->isUnnamedBitfield() || Field->isAnonymousStructOrUnion()) && "Only unnamed bitfields or ananymous class allowed");
  1493. #endif
  1494. return;
  1495. }
  1496. // FIXME: volatility
  1497. FieldDecl *Field = InitializedFieldInUnion;
  1498. LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
  1499. if (NumInitElements) {
  1500. // Store the initializer into the field
  1501. EmitInitializationToLValue(InitExprs[0], FieldLoc);
  1502. } else {
  1503. // Default-initialize to null.
  1504. EmitNullInitializationToLValue(FieldLoc);
  1505. }
  1506. return;
  1507. }
  1508. // Here we iterate over the fields; this makes it simpler to both
  1509. // default-initialize fields and skip over unnamed fields.
  1510. for (const auto *field : record->fields()) {
  1511. // We're done once we hit the flexible array member.
  1512. if (field->getType()->isIncompleteArrayType())
  1513. break;
  1514. // Always skip anonymous bitfields.
  1515. if (field->isUnnamedBitfield())
  1516. continue;
  1517. // We're done if we reach the end of the explicit initializers, we
  1518. // have a zeroed object, and the rest of the fields are
  1519. // zero-initializable.
  1520. if (curInitIndex == NumInitElements && Dest.isZeroed() &&
  1521. CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))
  1522. break;
  1523. LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
  1524. // We never generate write-barries for initialized fields.
  1525. LV.setNonGC(true);
  1526. if (curInitIndex < NumInitElements) {
  1527. // Store the initializer into the field.
  1528. EmitInitializationToLValue(InitExprs[curInitIndex++], LV);
  1529. } else {
  1530. // We're out of initializers; default-initialize to null
  1531. EmitNullInitializationToLValue(LV);
  1532. }
  1533. // Push a destructor if necessary.
  1534. // FIXME: if we have an array of structures, all explicitly
  1535. // initialized, we can end up pushing a linear number of cleanups.
  1536. bool pushedCleanup = false;
  1537. if (QualType::DestructionKind dtorKind
  1538. = field->getType().isDestructedType()) {
  1539. assert(LV.isSimple());
  1540. if (CGF.needsEHCleanup(dtorKind)) {
  1541. CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(),
  1542. CGF.getDestroyer(dtorKind), false);
  1543. addCleanup(CGF.EHStack.stable_begin());
  1544. pushedCleanup = true;
  1545. }
  1546. }
  1547. // If the GEP didn't get used because of a dead zero init or something
  1548. // else, clean it up for -O0 builds and general tidiness.
  1549. if (!pushedCleanup && LV.isSimple())
  1550. if (llvm::GetElementPtrInst *GEP =
  1551. dyn_cast<llvm::GetElementPtrInst>(LV.getPointer(CGF)))
  1552. if (GEP->use_empty())
  1553. GEP->eraseFromParent();
  1554. }
  1555. // Deactivate all the partial cleanups in reverse order, which
  1556. // generally means popping them.
  1557. assert((cleanupDominator || cleanups.empty()) &&
  1558. "Missing cleanupDominator before deactivating cleanup blocks");
  1559. for (unsigned i = cleanups.size(); i != 0; --i)
  1560. CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
  1561. // Destroy the placeholder if we made one.
  1562. if (cleanupDominator)
  1563. cleanupDominator->eraseFromParent();
  1564. }
  1565. void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
  1566. llvm::Value *outerBegin) {
  1567. // Emit the common subexpression.
  1568. CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
  1569. Address destPtr = EnsureSlot(E->getType()).getAddress();
  1570. uint64_t numElements = E->getArraySize().getZExtValue();
  1571. if (!numElements)
  1572. return;
  1573. // destPtr is an array*. Construct an elementType* by drilling down a level.
  1574. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1575. llvm::Value *indices[] = {zero, zero};
  1576. llvm::Value *begin = Builder.CreateInBoundsGEP(
  1577. destPtr.getElementType(), destPtr.getPointer(), indices,
  1578. "arrayinit.begin");
  1579. // Prepare to special-case multidimensional array initialization: we avoid
  1580. // emitting multiple destructor loops in that case.
  1581. if (!outerBegin)
  1582. outerBegin = begin;
  1583. ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
  1584. QualType elementType =
  1585. CGF.getContext().getAsArrayType(E->getType())->getElementType();
  1586. CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  1587. CharUnits elementAlign =
  1588. destPtr.getAlignment().alignmentOfArrayElement(elementSize);
  1589. llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
  1590. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1591. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  1592. // Jump into the body.
  1593. CGF.EmitBlock(bodyBB);
  1594. llvm::PHINode *index =
  1595. Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
  1596. index->addIncoming(zero, entryBB);
  1597. llvm::Value *element =
  1598. Builder.CreateInBoundsGEP(llvmElementType, begin, index);
  1599. // Prepare for a cleanup.
  1600. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  1601. EHScopeStack::stable_iterator cleanup;
  1602. if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
  1603. if (outerBegin->getType() != element->getType())
  1604. outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
  1605. CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
  1606. elementAlign,
  1607. CGF.getDestroyer(dtorKind));
  1608. cleanup = CGF.EHStack.stable_begin();
  1609. } else {
  1610. dtorKind = QualType::DK_none;
  1611. }
  1612. // Emit the actual filler expression.
  1613. {
  1614. // Temporaries created in an array initialization loop are destroyed
  1615. // at the end of each iteration.
  1616. CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
  1617. CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
  1618. LValue elementLV = CGF.MakeAddrLValue(
  1619. Address(element, llvmElementType, elementAlign), elementType);
  1620. if (InnerLoop) {
  1621. // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
  1622. auto elementSlot = AggValueSlot::forLValue(
  1623. elementLV, CGF, AggValueSlot::IsDestructed,
  1624. AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
  1625. AggValueSlot::DoesNotOverlap);
  1626. AggExprEmitter(CGF, elementSlot, false)
  1627. .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
  1628. } else
  1629. EmitInitializationToLValue(E->getSubExpr(), elementLV);
  1630. }
  1631. // Move on to the next element.
  1632. llvm::Value *nextIndex = Builder.CreateNUWAdd(
  1633. index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
  1634. index->addIncoming(nextIndex, Builder.GetInsertBlock());
  1635. // Leave the loop if we're done.
  1636. llvm::Value *done = Builder.CreateICmpEQ(
  1637. nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
  1638. "arrayinit.done");
  1639. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  1640. Builder.CreateCondBr(done, endBB, bodyBB);
  1641. CGF.EmitBlock(endBB);
  1642. // Leave the partial-array cleanup if we entered one.
  1643. if (dtorKind)
  1644. CGF.DeactivateCleanupBlock(cleanup, index);
  1645. }
  1646. void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
  1647. AggValueSlot Dest = EnsureSlot(E->getType());
  1648. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  1649. EmitInitializationToLValue(E->getBase(), DestLV);
  1650. VisitInitListExpr(E->getUpdater());
  1651. }
  1652. //===----------------------------------------------------------------------===//
  1653. // Entry Points into this File
  1654. //===----------------------------------------------------------------------===//
  1655. /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
  1656. /// non-zero bytes that will be stored when outputting the initializer for the
  1657. /// specified initializer expression.
  1658. static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
  1659. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  1660. E = MTE->getSubExpr();
  1661. E = E->IgnoreParenNoopCasts(CGF.getContext());
  1662. // 0 and 0.0 won't require any non-zero stores!
  1663. if (isSimpleZero(E, CGF)) return CharUnits::Zero();
  1664. // If this is an initlist expr, sum up the size of sizes of the (present)
  1665. // elements. If this is something weird, assume the whole thing is non-zero.
  1666. const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  1667. while (ILE && ILE->isTransparent())
  1668. ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
  1669. if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
  1670. return CGF.getContext().getTypeSizeInChars(E->getType());
  1671. // InitListExprs for structs have to be handled carefully. If there are
  1672. // reference members, we need to consider the size of the reference, not the
  1673. // referencee. InitListExprs for unions and arrays can't have references.
  1674. if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
  1675. if (!RT->isUnionType()) {
  1676. RecordDecl *SD = RT->getDecl();
  1677. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1678. unsigned ILEElement = 0;
  1679. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
  1680. while (ILEElement != CXXRD->getNumBases())
  1681. NumNonZeroBytes +=
  1682. GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
  1683. for (const auto *Field : SD->fields()) {
  1684. // We're done once we hit the flexible array member or run out of
  1685. // InitListExpr elements.
  1686. if (Field->getType()->isIncompleteArrayType() ||
  1687. ILEElement == ILE->getNumInits())
  1688. break;
  1689. if (Field->isUnnamedBitfield())
  1690. continue;
  1691. const Expr *E = ILE->getInit(ILEElement++);
  1692. // Reference values are always non-null and have the width of a pointer.
  1693. if (Field->getType()->isReferenceType())
  1694. NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
  1695. CGF.getTarget().getPointerWidth(LangAS::Default));
  1696. else
  1697. NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
  1698. }
  1699. return NumNonZeroBytes;
  1700. }
  1701. }
  1702. // FIXME: This overestimates the number of non-zero bytes for bit-fields.
  1703. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1704. for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
  1705. NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
  1706. return NumNonZeroBytes;
  1707. }
  1708. /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
  1709. /// zeros in it, emit a memset and avoid storing the individual zeros.
  1710. ///
  1711. static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
  1712. CodeGenFunction &CGF) {
  1713. // If the slot is already known to be zeroed, nothing to do. Don't mess with
  1714. // volatile stores.
  1715. if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
  1716. return;
  1717. // C++ objects with a user-declared constructor don't need zero'ing.
  1718. if (CGF.getLangOpts().CPlusPlus)
  1719. if (const RecordType *RT = CGF.getContext()
  1720. .getBaseElementType(E->getType())->getAs<RecordType>()) {
  1721. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  1722. if (RD->hasUserDeclaredConstructor())
  1723. return;
  1724. }
  1725. // If the type is 16-bytes or smaller, prefer individual stores over memset.
  1726. CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
  1727. if (Size <= CharUnits::fromQuantity(16))
  1728. return;
  1729. // Check to see if over 3/4 of the initializer are known to be zero. If so,
  1730. // we prefer to emit memset + individual stores for the rest.
  1731. CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
  1732. if (NumNonZeroBytes*4 > Size)
  1733. return;
  1734. // Okay, it seems like a good idea to use an initial memset, emit the call.
  1735. llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
  1736. Address Loc = Slot.getAddress();
  1737. Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
  1738. CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
  1739. // Tell the AggExprEmitter that the slot is known zero.
  1740. Slot.setZeroed();
  1741. }
  1742. /// EmitAggExpr - Emit the computation of the specified expression of aggregate
  1743. /// type. The result is computed into DestPtr. Note that if DestPtr is null,
  1744. /// the value of the aggregate expression is not needed. If VolatileDest is
  1745. /// true, DestPtr cannot be 0.
  1746. void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
  1747. assert(E && hasAggregateEvaluationKind(E->getType()) &&
  1748. "Invalid aggregate expression to emit");
  1749. assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
  1750. "slot has bits but no address");
  1751. // Optimize the slot if possible.
  1752. CheckAggExprForMemSetUse(Slot, E, *this);
  1753. AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
  1754. }
  1755. LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
  1756. assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
  1757. Address Temp = CreateMemTemp(E->getType());
  1758. LValue LV = MakeAddrLValue(Temp, E->getType());
  1759. EmitAggExpr(E, AggValueSlot::forLValue(
  1760. LV, *this, AggValueSlot::IsNotDestructed,
  1761. AggValueSlot::DoesNotNeedGCBarriers,
  1762. AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));
  1763. return LV;
  1764. }
  1765. AggValueSlot::Overlap_t
  1766. CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
  1767. if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
  1768. return AggValueSlot::DoesNotOverlap;
  1769. // If the field lies entirely within the enclosing class's nvsize, its tail
  1770. // padding cannot overlap any already-initialized object. (The only subobjects
  1771. // with greater addresses that might already be initialized are vbases.)
  1772. const RecordDecl *ClassRD = FD->getParent();
  1773. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
  1774. if (Layout.getFieldOffset(FD->getFieldIndex()) +
  1775. getContext().getTypeSize(FD->getType()) <=
  1776. (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
  1777. return AggValueSlot::DoesNotOverlap;
  1778. // The tail padding may contain values we need to preserve.
  1779. return AggValueSlot::MayOverlap;
  1780. }
  1781. AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
  1782. const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
  1783. // If the most-derived object is a field declared with [[no_unique_address]],
  1784. // the tail padding of any virtual base could be reused for other subobjects
  1785. // of that field's class.
  1786. if (IsVirtual)
  1787. return AggValueSlot::MayOverlap;
  1788. // If the base class is laid out entirely within the nvsize of the derived
  1789. // class, its tail padding cannot yet be initialized, so we can issue
  1790. // stores at the full width of the base class.
  1791. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1792. if (Layout.getBaseClassOffset(BaseRD) +
  1793. getContext().getASTRecordLayout(BaseRD).getSize() <=
  1794. Layout.getNonVirtualSize())
  1795. return AggValueSlot::DoesNotOverlap;
  1796. // The tail padding may contain values we need to preserve.
  1797. return AggValueSlot::MayOverlap;
  1798. }
  1799. void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
  1800. AggValueSlot::Overlap_t MayOverlap,
  1801. bool isVolatile) {
  1802. assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
  1803. Address DestPtr = Dest.getAddress(*this);
  1804. Address SrcPtr = Src.getAddress(*this);
  1805. if (getLangOpts().CPlusPlus) {
  1806. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1807. CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
  1808. assert((Record->hasTrivialCopyConstructor() ||
  1809. Record->hasTrivialCopyAssignment() ||
  1810. Record->hasTrivialMoveConstructor() ||
  1811. Record->hasTrivialMoveAssignment() ||
  1812. Record->hasAttr<TrivialABIAttr>() || Record->isUnion()) &&
  1813. "Trying to aggregate-copy a type without a trivial copy/move "
  1814. "constructor or assignment operator");
  1815. // Ignore empty classes in C++.
  1816. if (Record->isEmpty())
  1817. return;
  1818. }
  1819. }
  1820. if (getLangOpts().CUDAIsDevice) {
  1821. if (Ty->isCUDADeviceBuiltinSurfaceType()) {
  1822. if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
  1823. Src))
  1824. return;
  1825. } else if (Ty->isCUDADeviceBuiltinTextureType()) {
  1826. if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
  1827. Src))
  1828. return;
  1829. }
  1830. }
  1831. // Aggregate assignment turns into llvm.memcpy. This is almost valid per
  1832. // C99 6.5.16.1p3, which states "If the value being stored in an object is
  1833. // read from another object that overlaps in anyway the storage of the first
  1834. // object, then the overlap shall be exact and the two objects shall have
  1835. // qualified or unqualified versions of a compatible type."
  1836. //
  1837. // memcpy is not defined if the source and destination pointers are exactly
  1838. // equal, but other compilers do this optimization, and almost every memcpy
  1839. // implementation handles this case safely. If there is a libc that does not
  1840. // safely handle this, we can add a target hook.
  1841. // Get data size info for this aggregate. Don't copy the tail padding if this
  1842. // might be a potentially-overlapping subobject, since the tail padding might
  1843. // be occupied by a different object. Otherwise, copying it is fine.
  1844. TypeInfoChars TypeInfo;
  1845. if (MayOverlap)
  1846. TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
  1847. else
  1848. TypeInfo = getContext().getTypeInfoInChars(Ty);
  1849. llvm::Value *SizeVal = nullptr;
  1850. if (TypeInfo.Width.isZero()) {
  1851. // But note that getTypeInfo returns 0 for a VLA.
  1852. if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
  1853. getContext().getAsArrayType(Ty))) {
  1854. QualType BaseEltTy;
  1855. SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
  1856. TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
  1857. assert(!TypeInfo.Width.isZero());
  1858. SizeVal = Builder.CreateNUWMul(
  1859. SizeVal,
  1860. llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
  1861. }
  1862. }
  1863. if (!SizeVal) {
  1864. SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
  1865. }
  1866. // FIXME: If we have a volatile struct, the optimizer can remove what might
  1867. // appear to be `extra' memory ops:
  1868. //
  1869. // volatile struct { int i; } a, b;
  1870. //
  1871. // int main() {
  1872. // a = b;
  1873. // a = b;
  1874. // }
  1875. //
  1876. // we need to use a different call here. We use isVolatile to indicate when
  1877. // either the source or the destination is volatile.
  1878. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1879. SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
  1880. // Don't do any of the memmove_collectable tests if GC isn't set.
  1881. if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
  1882. // fall through
  1883. } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1884. RecordDecl *Record = RecordTy->getDecl();
  1885. if (Record->hasObjectMember()) {
  1886. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1887. SizeVal);
  1888. return;
  1889. }
  1890. } else if (Ty->isArrayType()) {
  1891. QualType BaseType = getContext().getBaseElementType(Ty);
  1892. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  1893. if (RecordTy->getDecl()->hasObjectMember()) {
  1894. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1895. SizeVal);
  1896. return;
  1897. }
  1898. }
  1899. }
  1900. auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
  1901. // Determine the metadata to describe the position of any padding in this
  1902. // memcpy, as well as the TBAA tags for the members of the struct, in case
  1903. // the optimizer wishes to expand it in to scalar memory operations.
  1904. if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
  1905. Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
  1906. if (CGM.getCodeGenOpts().NewStructPathTBAA) {
  1907. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
  1908. Dest.getTBAAInfo(), Src.getTBAAInfo());
  1909. CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
  1910. }
  1911. }