CGClass.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code dealing with C++ code generation of classes
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/EvaluatedExprVisitor.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/AST/StmtCXX.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. static CharUnits
  23. ComputeNonVirtualBaseClassOffset(ASTContext &Context,
  24. const CXXRecordDecl *DerivedClass,
  25. CastExpr::path_const_iterator Start,
  26. CastExpr::path_const_iterator End) {
  27. CharUnits Offset = CharUnits::Zero();
  28. const CXXRecordDecl *RD = DerivedClass;
  29. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  30. const CXXBaseSpecifier *Base = *I;
  31. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  32. // Get the layout.
  33. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  34. const CXXRecordDecl *BaseDecl =
  35. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  36. // Add the offset.
  37. Offset += Layout.getBaseClassOffset(BaseDecl);
  38. RD = BaseDecl;
  39. }
  40. return Offset;
  41. }
  42. llvm::Constant *
  43. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  44. CastExpr::path_const_iterator PathBegin,
  45. CastExpr::path_const_iterator PathEnd) {
  46. assert(PathBegin != PathEnd && "Base path should not be empty!");
  47. CharUnits Offset =
  48. ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
  49. PathBegin, PathEnd);
  50. if (Offset.isZero())
  51. return 0;
  52. llvm::Type *PtrDiffTy =
  53. Types.ConvertType(getContext().getPointerDiffType());
  54. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  55. }
  56. /// Gets the address of a direct base class within a complete object.
  57. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  58. /// when the type is known to be complete (e.g. in complete destructors).
  59. ///
  60. /// The object pointed to by 'This' is assumed to be non-null.
  61. llvm::Value *
  62. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
  63. const CXXRecordDecl *Derived,
  64. const CXXRecordDecl *Base,
  65. bool BaseIsVirtual) {
  66. // 'this' must be a pointer (in some address space) to Derived.
  67. assert(This->getType()->isPointerTy() &&
  68. cast<llvm::PointerType>(This->getType())->getElementType()
  69. == ConvertType(Derived));
  70. // Compute the offset of the virtual base.
  71. CharUnits Offset;
  72. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  73. if (BaseIsVirtual)
  74. Offset = Layout.getVBaseClassOffset(Base);
  75. else
  76. Offset = Layout.getBaseClassOffset(Base);
  77. // Shift and cast down to the base type.
  78. // TODO: for complete types, this should be possible with a GEP.
  79. llvm::Value *V = This;
  80. if (Offset.isPositive()) {
  81. V = Builder.CreateBitCast(V, Int8PtrTy);
  82. V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
  83. }
  84. V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
  85. return V;
  86. }
  87. static llvm::Value *
  88. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
  89. CharUnits NonVirtual, llvm::Value *Virtual) {
  90. llvm::Type *PtrDiffTy =
  91. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  92. llvm::Value *NonVirtualOffset = 0;
  93. if (!NonVirtual.isZero())
  94. NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
  95. NonVirtual.getQuantity());
  96. llvm::Value *BaseOffset;
  97. if (Virtual) {
  98. if (NonVirtualOffset)
  99. BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
  100. else
  101. BaseOffset = Virtual;
  102. } else
  103. BaseOffset = NonVirtualOffset;
  104. // Apply the base offset.
  105. ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
  106. ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
  107. return ThisPtr;
  108. }
  109. llvm::Value *
  110. CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
  111. const CXXRecordDecl *Derived,
  112. CastExpr::path_const_iterator PathBegin,
  113. CastExpr::path_const_iterator PathEnd,
  114. bool NullCheckValue) {
  115. assert(PathBegin != PathEnd && "Base path should not be empty!");
  116. CastExpr::path_const_iterator Start = PathBegin;
  117. const CXXRecordDecl *VBase = 0;
  118. // Get the virtual base.
  119. if ((*Start)->isVirtual()) {
  120. VBase =
  121. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  122. ++Start;
  123. }
  124. CharUnits NonVirtualOffset =
  125. ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
  126. Start, PathEnd);
  127. // Get the base pointer type.
  128. llvm::Type *BasePtrTy =
  129. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  130. if (NonVirtualOffset.isZero() && !VBase) {
  131. // Just cast back.
  132. return Builder.CreateBitCast(Value, BasePtrTy);
  133. }
  134. llvm::BasicBlock *CastNull = 0;
  135. llvm::BasicBlock *CastNotNull = 0;
  136. llvm::BasicBlock *CastEnd = 0;
  137. if (NullCheckValue) {
  138. CastNull = createBasicBlock("cast.null");
  139. CastNotNull = createBasicBlock("cast.notnull");
  140. CastEnd = createBasicBlock("cast.end");
  141. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  142. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  143. EmitBlock(CastNotNull);
  144. }
  145. llvm::Value *VirtualOffset = 0;
  146. if (VBase) {
  147. if (Derived->hasAttr<FinalAttr>()) {
  148. VirtualOffset = 0;
  149. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  150. CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
  151. NonVirtualOffset += VBaseOffset;
  152. } else
  153. VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
  154. }
  155. // Apply the offsets.
  156. Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
  157. NonVirtualOffset,
  158. VirtualOffset);
  159. // Cast back.
  160. Value = Builder.CreateBitCast(Value, BasePtrTy);
  161. if (NullCheckValue) {
  162. Builder.CreateBr(CastEnd);
  163. EmitBlock(CastNull);
  164. Builder.CreateBr(CastEnd);
  165. EmitBlock(CastEnd);
  166. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  167. PHI->addIncoming(Value, CastNotNull);
  168. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  169. CastNull);
  170. Value = PHI;
  171. }
  172. return Value;
  173. }
  174. llvm::Value *
  175. CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
  176. const CXXRecordDecl *Derived,
  177. CastExpr::path_const_iterator PathBegin,
  178. CastExpr::path_const_iterator PathEnd,
  179. bool NullCheckValue) {
  180. assert(PathBegin != PathEnd && "Base path should not be empty!");
  181. QualType DerivedTy =
  182. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  183. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  184. llvm::Value *NonVirtualOffset =
  185. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  186. if (!NonVirtualOffset) {
  187. // No offset, we can just cast back.
  188. return Builder.CreateBitCast(Value, DerivedPtrTy);
  189. }
  190. llvm::BasicBlock *CastNull = 0;
  191. llvm::BasicBlock *CastNotNull = 0;
  192. llvm::BasicBlock *CastEnd = 0;
  193. if (NullCheckValue) {
  194. CastNull = createBasicBlock("cast.null");
  195. CastNotNull = createBasicBlock("cast.notnull");
  196. CastEnd = createBasicBlock("cast.end");
  197. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  198. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  199. EmitBlock(CastNotNull);
  200. }
  201. // Apply the offset.
  202. Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
  203. Value = Builder.CreateSub(Value, NonVirtualOffset);
  204. Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
  205. // Just cast.
  206. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  207. if (NullCheckValue) {
  208. Builder.CreateBr(CastEnd);
  209. EmitBlock(CastNull);
  210. Builder.CreateBr(CastEnd);
  211. EmitBlock(CastEnd);
  212. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  213. PHI->addIncoming(Value, CastNotNull);
  214. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  215. CastNull);
  216. Value = PHI;
  217. }
  218. return Value;
  219. }
  220. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  221. /// base constructor/destructor with virtual bases.
  222. static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
  223. bool ForVirtualBase) {
  224. if (!CodeGenVTables::needsVTTParameter(GD)) {
  225. // This constructor/destructor does not need a VTT parameter.
  226. return 0;
  227. }
  228. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
  229. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  230. llvm::Value *VTT;
  231. uint64_t SubVTTIndex;
  232. // If the record matches the base, this is the complete ctor/dtor
  233. // variant calling the base variant in a class with virtual bases.
  234. if (RD == Base) {
  235. assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
  236. "doing no-op VTT offset in base dtor/ctor?");
  237. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  238. SubVTTIndex = 0;
  239. } else {
  240. const ASTRecordLayout &Layout =
  241. CGF.getContext().getASTRecordLayout(RD);
  242. CharUnits BaseOffset = ForVirtualBase ?
  243. Layout.getVBaseClassOffset(Base) :
  244. Layout.getBaseClassOffset(Base);
  245. SubVTTIndex =
  246. CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  247. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  248. }
  249. if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
  250. // A VTT parameter was passed to the constructor, use it.
  251. VTT = CGF.LoadCXXVTT();
  252. VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  253. } else {
  254. // We're the complete constructor, so get the VTT by name.
  255. VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
  256. VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  257. }
  258. return VTT;
  259. }
  260. namespace {
  261. /// Call the destructor for a direct base class.
  262. struct CallBaseDtor : EHScopeStack::Cleanup {
  263. const CXXRecordDecl *BaseClass;
  264. bool BaseIsVirtual;
  265. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  266. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  267. void Emit(CodeGenFunction &CGF, Flags flags) {
  268. const CXXRecordDecl *DerivedClass =
  269. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  270. const CXXDestructorDecl *D = BaseClass->getDestructor();
  271. llvm::Value *Addr =
  272. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
  273. DerivedClass, BaseClass,
  274. BaseIsVirtual);
  275. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
  276. }
  277. };
  278. /// A visitor which checks whether an initializer uses 'this' in a
  279. /// way which requires the vtable to be properly set.
  280. struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
  281. typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
  282. bool UsesThis;
  283. DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
  284. // Black-list all explicit and implicit references to 'this'.
  285. //
  286. // Do we need to worry about external references to 'this' derived
  287. // from arbitrary code? If so, then anything which runs arbitrary
  288. // external code might potentially access the vtable.
  289. void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
  290. };
  291. }
  292. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  293. DynamicThisUseChecker Checker(C);
  294. Checker.Visit(const_cast<Expr*>(Init));
  295. return Checker.UsesThis;
  296. }
  297. static void EmitBaseInitializer(CodeGenFunction &CGF,
  298. const CXXRecordDecl *ClassDecl,
  299. CXXCtorInitializer *BaseInit,
  300. CXXCtorType CtorType) {
  301. assert(BaseInit->isBaseInitializer() &&
  302. "Must have base initializer!");
  303. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  304. const Type *BaseType = BaseInit->getBaseClass();
  305. CXXRecordDecl *BaseClassDecl =
  306. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  307. bool isBaseVirtual = BaseInit->isBaseVirtual();
  308. // The base constructor doesn't construct virtual bases.
  309. if (CtorType == Ctor_Base && isBaseVirtual)
  310. return;
  311. // If the initializer for the base (other than the constructor
  312. // itself) accesses 'this' in any way, we need to initialize the
  313. // vtables.
  314. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  315. CGF.InitializeVTablePointers(ClassDecl);
  316. // We can pretend to be a complete class because it only matters for
  317. // virtual bases, and we only do virtual bases for complete ctors.
  318. llvm::Value *V =
  319. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  320. BaseClassDecl,
  321. isBaseVirtual);
  322. CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
  323. AggValueSlot AggSlot =
  324. AggValueSlot::forAddr(V, Alignment, Qualifiers(),
  325. AggValueSlot::IsDestructed,
  326. AggValueSlot::DoesNotNeedGCBarriers,
  327. AggValueSlot::IsNotAliased);
  328. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  329. if (CGF.CGM.getLangOptions().Exceptions &&
  330. !BaseClassDecl->hasTrivialDestructor())
  331. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  332. isBaseVirtual);
  333. }
  334. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  335. LValue LHS,
  336. Expr *Init,
  337. llvm::Value *ArrayIndexVar,
  338. QualType T,
  339. ArrayRef<VarDecl *> ArrayIndexes,
  340. unsigned Index) {
  341. if (Index == ArrayIndexes.size()) {
  342. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  343. LValue LV = LHS;
  344. if (ArrayIndexVar) {
  345. // If we have an array index variable, load it and use it as an offset.
  346. // Then, increment the value.
  347. llvm::Value *Dest = LHS.getAddress();
  348. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  349. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  350. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  351. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  352. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  353. // Update the LValue.
  354. LV.setAddress(Dest);
  355. CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
  356. LV.setAlignment(std::min(Align, LV.getAlignment()));
  357. }
  358. if (!CGF.hasAggregateLLVMType(T)) {
  359. CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
  360. } else if (T->isAnyComplexType()) {
  361. CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
  362. LV.isVolatileQualified());
  363. } else {
  364. AggValueSlot Slot =
  365. AggValueSlot::forLValue(LV,
  366. AggValueSlot::IsDestructed,
  367. AggValueSlot::DoesNotNeedGCBarriers,
  368. AggValueSlot::IsNotAliased);
  369. CGF.EmitAggExpr(Init, Slot);
  370. }
  371. return;
  372. }
  373. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  374. assert(Array && "Array initialization without the array type?");
  375. llvm::Value *IndexVar
  376. = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
  377. assert(IndexVar && "Array index variable not loaded");
  378. // Initialize this index variable to zero.
  379. llvm::Value* Zero
  380. = llvm::Constant::getNullValue(
  381. CGF.ConvertType(CGF.getContext().getSizeType()));
  382. CGF.Builder.CreateStore(Zero, IndexVar);
  383. // Start the loop with a block that tests the condition.
  384. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  385. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  386. CGF.EmitBlock(CondBlock);
  387. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  388. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  389. // otherwise, go to the block after the for-loop.
  390. uint64_t NumElements = Array->getSize().getZExtValue();
  391. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  392. llvm::Value *NumElementsPtr =
  393. llvm::ConstantInt::get(Counter->getType(), NumElements);
  394. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  395. "isless");
  396. // If the condition is true, execute the body.
  397. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  398. CGF.EmitBlock(ForBody);
  399. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  400. {
  401. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  402. // Inside the loop body recurse to emit the inner loop or, eventually, the
  403. // constructor call.
  404. EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
  405. Array->getElementType(), ArrayIndexes, Index + 1);
  406. }
  407. CGF.EmitBlock(ContinueBlock);
  408. // Emit the increment of the loop counter.
  409. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  410. Counter = CGF.Builder.CreateLoad(IndexVar);
  411. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  412. CGF.Builder.CreateStore(NextVal, IndexVar);
  413. // Finally, branch back up to the condition for the next iteration.
  414. CGF.EmitBranch(CondBlock);
  415. // Emit the fall-through block.
  416. CGF.EmitBlock(AfterFor, true);
  417. }
  418. namespace {
  419. struct CallMemberDtor : EHScopeStack::Cleanup {
  420. llvm::Value *V;
  421. CXXDestructorDecl *Dtor;
  422. CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
  423. : V(V), Dtor(Dtor) {}
  424. void Emit(CodeGenFunction &CGF, Flags flags) {
  425. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  426. V);
  427. }
  428. };
  429. }
  430. static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
  431. bool Moving) {
  432. return Moving ? Record->hasTrivialMoveConstructor() :
  433. Record->hasTrivialCopyConstructor();
  434. }
  435. static void EmitMemberInitializer(CodeGenFunction &CGF,
  436. const CXXRecordDecl *ClassDecl,
  437. CXXCtorInitializer *MemberInit,
  438. const CXXConstructorDecl *Constructor,
  439. FunctionArgList &Args) {
  440. assert(MemberInit->isAnyMemberInitializer() &&
  441. "Must have member initializer!");
  442. assert(MemberInit->getInit() && "Must have initializer!");
  443. // non-static data member initializers.
  444. FieldDecl *Field = MemberInit->getAnyMember();
  445. QualType FieldType = Field->getType();
  446. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  447. LValue LHS;
  448. // If we are initializing an anonymous union field, drill down to the field.
  449. if (MemberInit->isIndirectMemberInitializer()) {
  450. LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
  451. MemberInit->getIndirectMember(), 0);
  452. FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
  453. } else {
  454. LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
  455. }
  456. // Special case: if we are in a copy or move constructor, and we are copying
  457. // an array of PODs or classes with trivial copy constructors, ignore the
  458. // AST and perform the copy we know is equivalent.
  459. // FIXME: This is hacky at best... if we had a bit more explicit information
  460. // in the AST, we could generalize it more easily.
  461. const ConstantArrayType *Array
  462. = CGF.getContext().getAsConstantArrayType(FieldType);
  463. if (Array && Constructor->isImplicitlyDefined() &&
  464. Constructor->isCopyOrMoveConstructor()) {
  465. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  466. const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
  467. if (BaseElementTy.isPODType(CGF.getContext()) ||
  468. (Record && hasTrivialCopyOrMoveConstructor(Record,
  469. Constructor->isMoveConstructor()))) {
  470. // Find the source pointer. We knows it's the last argument because
  471. // we know we're in a copy constructor.
  472. unsigned SrcArgIndex = Args.size() - 1;
  473. llvm::Value *SrcPtr
  474. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  475. LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
  476. // Copy the aggregate.
  477. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  478. LHS.isVolatileQualified());
  479. return;
  480. }
  481. }
  482. ArrayRef<VarDecl *> ArrayIndexes;
  483. if (MemberInit->getNumArrayIndices())
  484. ArrayIndexes = MemberInit->getArrayIndexes();
  485. CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
  486. }
  487. void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
  488. LValue LHS, Expr *Init,
  489. ArrayRef<VarDecl *> ArrayIndexes) {
  490. QualType FieldType = Field->getType();
  491. if (!hasAggregateLLVMType(FieldType)) {
  492. if (LHS.isSimple()) {
  493. EmitExprAsInit(Init, Field, LHS, false);
  494. } else {
  495. RValue RHS = RValue::get(EmitScalarExpr(Init));
  496. EmitStoreThroughLValue(RHS, LHS);
  497. }
  498. } else if (FieldType->isAnyComplexType()) {
  499. EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
  500. } else {
  501. llvm::Value *ArrayIndexVar = 0;
  502. if (ArrayIndexes.size()) {
  503. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  504. // The LHS is a pointer to the first object we'll be constructing, as
  505. // a flat array.
  506. QualType BaseElementTy = getContext().getBaseElementType(FieldType);
  507. llvm::Type *BasePtr = ConvertType(BaseElementTy);
  508. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  509. llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
  510. BasePtr);
  511. LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  512. // Create an array index that will be used to walk over all of the
  513. // objects we're constructing.
  514. ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
  515. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  516. Builder.CreateStore(Zero, ArrayIndexVar);
  517. // Emit the block variables for the array indices, if any.
  518. for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
  519. EmitAutoVarDecl(*ArrayIndexes[I]);
  520. }
  521. EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
  522. ArrayIndexes, 0);
  523. if (!CGM.getLangOptions().Exceptions)
  524. return;
  525. // FIXME: If we have an array of classes w/ non-trivial destructors,
  526. // we need to destroy in reverse order of construction along the exception
  527. // path.
  528. const RecordType *RT = FieldType->getAs<RecordType>();
  529. if (!RT)
  530. return;
  531. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  532. if (!RD->hasTrivialDestructor())
  533. EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
  534. RD->getDestructor());
  535. }
  536. }
  537. /// Checks whether the given constructor is a valid subject for the
  538. /// complete-to-base constructor delegation optimization, i.e.
  539. /// emitting the complete constructor as a simple call to the base
  540. /// constructor.
  541. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  542. // Currently we disable the optimization for classes with virtual
  543. // bases because (1) the addresses of parameter variables need to be
  544. // consistent across all initializers but (2) the delegate function
  545. // call necessarily creates a second copy of the parameter variable.
  546. //
  547. // The limiting example (purely theoretical AFAIK):
  548. // struct A { A(int &c) { c++; } };
  549. // struct B : virtual A {
  550. // B(int count) : A(count) { printf("%d\n", count); }
  551. // };
  552. // ...although even this example could in principle be emitted as a
  553. // delegation since the address of the parameter doesn't escape.
  554. if (Ctor->getParent()->getNumVBases()) {
  555. // TODO: white-list trivial vbase initializers. This case wouldn't
  556. // be subject to the restrictions below.
  557. // TODO: white-list cases where:
  558. // - there are no non-reference parameters to the constructor
  559. // - the initializers don't access any non-reference parameters
  560. // - the initializers don't take the address of non-reference
  561. // parameters
  562. // - etc.
  563. // If we ever add any of the above cases, remember that:
  564. // - function-try-blocks will always blacklist this optimization
  565. // - we need to perform the constructor prologue and cleanup in
  566. // EmitConstructorBody.
  567. return false;
  568. }
  569. // We also disable the optimization for variadic functions because
  570. // it's impossible to "re-pass" varargs.
  571. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  572. return false;
  573. // FIXME: Decide if we can do a delegation of a delegating constructor.
  574. if (Ctor->isDelegatingConstructor())
  575. return false;
  576. return true;
  577. }
  578. /// EmitConstructorBody - Emits the body of the current constructor.
  579. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  580. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  581. CXXCtorType CtorType = CurGD.getCtorType();
  582. // Before we go any further, try the complete->base constructor
  583. // delegation optimization.
  584. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
  585. if (CGDebugInfo *DI = getDebugInfo())
  586. DI->EmitLocation(Builder, Ctor->getLocEnd());
  587. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
  588. return;
  589. }
  590. Stmt *Body = Ctor->getBody();
  591. // Enter the function-try-block before the constructor prologue if
  592. // applicable.
  593. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  594. if (IsTryBody)
  595. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  596. EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
  597. // Emit the constructor prologue, i.e. the base and member
  598. // initializers.
  599. EmitCtorPrologue(Ctor, CtorType, Args);
  600. // Emit the body of the statement.
  601. if (IsTryBody)
  602. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  603. else if (Body)
  604. EmitStmt(Body);
  605. // Emit any cleanup blocks associated with the member or base
  606. // initializers, which includes (along the exceptional path) the
  607. // destructors for those members and bases that were fully
  608. // constructed.
  609. PopCleanupBlocks(CleanupDepth);
  610. if (IsTryBody)
  611. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  612. }
  613. /// EmitCtorPrologue - This routine generates necessary code to initialize
  614. /// base classes and non-static data members belonging to this constructor.
  615. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  616. CXXCtorType CtorType,
  617. FunctionArgList &Args) {
  618. if (CD->isDelegatingConstructor())
  619. return EmitDelegatingCXXConstructorCall(CD, Args);
  620. const CXXRecordDecl *ClassDecl = CD->getParent();
  621. SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
  622. for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  623. E = CD->init_end();
  624. B != E; ++B) {
  625. CXXCtorInitializer *Member = (*B);
  626. if (Member->isBaseInitializer()) {
  627. EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
  628. } else {
  629. assert(Member->isAnyMemberInitializer() &&
  630. "Delegating initializer on non-delegating constructor");
  631. MemberInitializers.push_back(Member);
  632. }
  633. }
  634. InitializeVTablePointers(ClassDecl);
  635. for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
  636. EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
  637. }
  638. static bool
  639. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  640. static bool
  641. HasTrivialDestructorBody(ASTContext &Context,
  642. const CXXRecordDecl *BaseClassDecl,
  643. const CXXRecordDecl *MostDerivedClassDecl)
  644. {
  645. // If the destructor is trivial we don't have to check anything else.
  646. if (BaseClassDecl->hasTrivialDestructor())
  647. return true;
  648. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  649. return false;
  650. // Check fields.
  651. for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
  652. E = BaseClassDecl->field_end(); I != E; ++I) {
  653. const FieldDecl *Field = *I;
  654. if (!FieldHasTrivialDestructorBody(Context, Field))
  655. return false;
  656. }
  657. // Check non-virtual bases.
  658. for (CXXRecordDecl::base_class_const_iterator I =
  659. BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
  660. I != E; ++I) {
  661. if (I->isVirtual())
  662. continue;
  663. const CXXRecordDecl *NonVirtualBase =
  664. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  665. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  666. MostDerivedClassDecl))
  667. return false;
  668. }
  669. if (BaseClassDecl == MostDerivedClassDecl) {
  670. // Check virtual bases.
  671. for (CXXRecordDecl::base_class_const_iterator I =
  672. BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
  673. I != E; ++I) {
  674. const CXXRecordDecl *VirtualBase =
  675. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  676. if (!HasTrivialDestructorBody(Context, VirtualBase,
  677. MostDerivedClassDecl))
  678. return false;
  679. }
  680. }
  681. return true;
  682. }
  683. static bool
  684. FieldHasTrivialDestructorBody(ASTContext &Context,
  685. const FieldDecl *Field)
  686. {
  687. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  688. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  689. if (!RT)
  690. return true;
  691. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  692. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  693. }
  694. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  695. /// any vtable pointers before calling this destructor.
  696. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  697. const CXXDestructorDecl *Dtor) {
  698. if (!Dtor->hasTrivialBody())
  699. return false;
  700. // Check the fields.
  701. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  702. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  703. E = ClassDecl->field_end(); I != E; ++I) {
  704. const FieldDecl *Field = *I;
  705. if (!FieldHasTrivialDestructorBody(Context, Field))
  706. return false;
  707. }
  708. return true;
  709. }
  710. /// EmitDestructorBody - Emits the body of the current destructor.
  711. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  712. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  713. CXXDtorType DtorType = CurGD.getDtorType();
  714. // The call to operator delete in a deleting destructor happens
  715. // outside of the function-try-block, which means it's always
  716. // possible to delegate the destructor body to the complete
  717. // destructor. Do so.
  718. if (DtorType == Dtor_Deleting) {
  719. EnterDtorCleanups(Dtor, Dtor_Deleting);
  720. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  721. LoadCXXThis());
  722. PopCleanupBlock();
  723. return;
  724. }
  725. Stmt *Body = Dtor->getBody();
  726. // If the body is a function-try-block, enter the try before
  727. // anything else.
  728. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  729. if (isTryBody)
  730. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  731. // Enter the epilogue cleanups.
  732. RunCleanupsScope DtorEpilogue(*this);
  733. // If this is the complete variant, just invoke the base variant;
  734. // the epilogue will destruct the virtual bases. But we can't do
  735. // this optimization if the body is a function-try-block, because
  736. // we'd introduce *two* handler blocks.
  737. switch (DtorType) {
  738. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  739. case Dtor_Complete:
  740. // Enter the cleanup scopes for virtual bases.
  741. EnterDtorCleanups(Dtor, Dtor_Complete);
  742. if (!isTryBody) {
  743. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  744. LoadCXXThis());
  745. break;
  746. }
  747. // Fallthrough: act like we're in the base variant.
  748. case Dtor_Base:
  749. // Enter the cleanup scopes for fields and non-virtual bases.
  750. EnterDtorCleanups(Dtor, Dtor_Base);
  751. // Initialize the vtable pointers before entering the body.
  752. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  753. InitializeVTablePointers(Dtor->getParent());
  754. if (isTryBody)
  755. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  756. else if (Body)
  757. EmitStmt(Body);
  758. else {
  759. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  760. // nothing to do besides what's in the epilogue
  761. }
  762. // -fapple-kext must inline any call to this dtor into
  763. // the caller's body.
  764. if (getContext().getLangOptions().AppleKext)
  765. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  766. break;
  767. }
  768. // Jump out through the epilogue cleanups.
  769. DtorEpilogue.ForceCleanup();
  770. // Exit the try if applicable.
  771. if (isTryBody)
  772. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  773. }
  774. namespace {
  775. /// Call the operator delete associated with the current destructor.
  776. struct CallDtorDelete : EHScopeStack::Cleanup {
  777. CallDtorDelete() {}
  778. void Emit(CodeGenFunction &CGF, Flags flags) {
  779. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  780. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  781. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  782. CGF.getContext().getTagDeclType(ClassDecl));
  783. }
  784. };
  785. class DestroyField : public EHScopeStack::Cleanup {
  786. const FieldDecl *field;
  787. CodeGenFunction::Destroyer *destroyer;
  788. bool useEHCleanupForArray;
  789. public:
  790. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  791. bool useEHCleanupForArray)
  792. : field(field), destroyer(destroyer),
  793. useEHCleanupForArray(useEHCleanupForArray) {}
  794. void Emit(CodeGenFunction &CGF, Flags flags) {
  795. // Find the address of the field.
  796. llvm::Value *thisValue = CGF.LoadCXXThis();
  797. LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
  798. assert(LV.isSimple());
  799. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  800. flags.isForNormalCleanup() && useEHCleanupForArray);
  801. }
  802. };
  803. }
  804. /// EmitDtorEpilogue - Emit all code that comes at the end of class's
  805. /// destructor. This is to call destructors on members and base classes
  806. /// in reverse order of their construction.
  807. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  808. CXXDtorType DtorType) {
  809. assert(!DD->isTrivial() &&
  810. "Should not emit dtor epilogue for trivial dtor!");
  811. // The deleting-destructor phase just needs to call the appropriate
  812. // operator delete that Sema picked up.
  813. if (DtorType == Dtor_Deleting) {
  814. assert(DD->getOperatorDelete() &&
  815. "operator delete missing - EmitDtorEpilogue");
  816. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  817. return;
  818. }
  819. const CXXRecordDecl *ClassDecl = DD->getParent();
  820. // Unions have no bases and do not call field destructors.
  821. if (ClassDecl->isUnion())
  822. return;
  823. // The complete-destructor phase just destructs all the virtual bases.
  824. if (DtorType == Dtor_Complete) {
  825. // We push them in the forward order so that they'll be popped in
  826. // the reverse order.
  827. for (CXXRecordDecl::base_class_const_iterator I =
  828. ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
  829. I != E; ++I) {
  830. const CXXBaseSpecifier &Base = *I;
  831. CXXRecordDecl *BaseClassDecl
  832. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  833. // Ignore trivial destructors.
  834. if (BaseClassDecl->hasTrivialDestructor())
  835. continue;
  836. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  837. BaseClassDecl,
  838. /*BaseIsVirtual*/ true);
  839. }
  840. return;
  841. }
  842. assert(DtorType == Dtor_Base);
  843. // Destroy non-virtual bases.
  844. for (CXXRecordDecl::base_class_const_iterator I =
  845. ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
  846. const CXXBaseSpecifier &Base = *I;
  847. // Ignore virtual bases.
  848. if (Base.isVirtual())
  849. continue;
  850. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  851. // Ignore trivial destructors.
  852. if (BaseClassDecl->hasTrivialDestructor())
  853. continue;
  854. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  855. BaseClassDecl,
  856. /*BaseIsVirtual*/ false);
  857. }
  858. // Destroy direct fields.
  859. SmallVector<const FieldDecl *, 16> FieldDecls;
  860. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  861. E = ClassDecl->field_end(); I != E; ++I) {
  862. const FieldDecl *field = *I;
  863. QualType type = field->getType();
  864. QualType::DestructionKind dtorKind = type.isDestructedType();
  865. if (!dtorKind) continue;
  866. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  867. EHStack.pushCleanup<DestroyField>(cleanupKind, field,
  868. getDestroyer(dtorKind),
  869. cleanupKind & EHCleanup);
  870. }
  871. }
  872. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  873. /// constructor for each of several members of an array.
  874. ///
  875. /// \param ctor the constructor to call for each element
  876. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  877. /// constructor
  878. /// \param arrayType the type of the array to initialize
  879. /// \param arrayBegin an arrayType*
  880. /// \param zeroInitialize true if each element should be
  881. /// zero-initialized before it is constructed
  882. void
  883. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  884. const ConstantArrayType *arrayType,
  885. llvm::Value *arrayBegin,
  886. CallExpr::const_arg_iterator argBegin,
  887. CallExpr::const_arg_iterator argEnd,
  888. bool zeroInitialize) {
  889. QualType elementType;
  890. llvm::Value *numElements =
  891. emitArrayLength(arrayType, elementType, arrayBegin);
  892. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
  893. argBegin, argEnd, zeroInitialize);
  894. }
  895. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  896. /// constructor for each of several members of an array.
  897. ///
  898. /// \param ctor the constructor to call for each element
  899. /// \param numElements the number of elements in the array;
  900. /// may be zero
  901. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  902. /// constructor
  903. /// \param arrayBegin a T*, where T is the type constructed by ctor
  904. /// \param zeroInitialize true if each element should be
  905. /// zero-initialized before it is constructed
  906. void
  907. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  908. llvm::Value *numElements,
  909. llvm::Value *arrayBegin,
  910. CallExpr::const_arg_iterator argBegin,
  911. CallExpr::const_arg_iterator argEnd,
  912. bool zeroInitialize) {
  913. // It's legal for numElements to be zero. This can happen both
  914. // dynamically, because x can be zero in 'new A[x]', and statically,
  915. // because of GCC extensions that permit zero-length arrays. There
  916. // are probably legitimate places where we could assume that this
  917. // doesn't happen, but it's not clear that it's worth it.
  918. llvm::BranchInst *zeroCheckBranch = 0;
  919. // Optimize for a constant count.
  920. llvm::ConstantInt *constantCount
  921. = dyn_cast<llvm::ConstantInt>(numElements);
  922. if (constantCount) {
  923. // Just skip out if the constant count is zero.
  924. if (constantCount->isZero()) return;
  925. // Otherwise, emit the check.
  926. } else {
  927. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  928. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  929. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  930. EmitBlock(loopBB);
  931. }
  932. // Find the end of the array.
  933. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  934. "arrayctor.end");
  935. // Enter the loop, setting up a phi for the current location to initialize.
  936. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  937. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  938. EmitBlock(loopBB);
  939. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  940. "arrayctor.cur");
  941. cur->addIncoming(arrayBegin, entryBB);
  942. // Inside the loop body, emit the constructor call on the array element.
  943. QualType type = getContext().getTypeDeclType(ctor->getParent());
  944. // Zero initialize the storage, if requested.
  945. if (zeroInitialize)
  946. EmitNullInitialization(cur, type);
  947. // C++ [class.temporary]p4:
  948. // There are two contexts in which temporaries are destroyed at a different
  949. // point than the end of the full-expression. The first context is when a
  950. // default constructor is called to initialize an element of an array.
  951. // If the constructor has one or more default arguments, the destruction of
  952. // every temporary created in a default argument expression is sequenced
  953. // before the construction of the next array element, if any.
  954. {
  955. RunCleanupsScope Scope(*this);
  956. // Evaluate the constructor and its arguments in a regular
  957. // partial-destroy cleanup.
  958. if (getLangOptions().Exceptions &&
  959. !ctor->getParent()->hasTrivialDestructor()) {
  960. Destroyer *destroyer = destroyCXXObject;
  961. pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
  962. }
  963. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
  964. cur, argBegin, argEnd);
  965. }
  966. // Go to the next element.
  967. llvm::Value *next =
  968. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  969. "arrayctor.next");
  970. cur->addIncoming(next, Builder.GetInsertBlock());
  971. // Check whether that's the end of the loop.
  972. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  973. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  974. Builder.CreateCondBr(done, contBB, loopBB);
  975. // Patch the earlier check to skip over the loop.
  976. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  977. EmitBlock(contBB);
  978. }
  979. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  980. llvm::Value *addr,
  981. QualType type) {
  982. const RecordType *rtype = type->castAs<RecordType>();
  983. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  984. const CXXDestructorDecl *dtor = record->getDestructor();
  985. assert(!dtor->isTrivial());
  986. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  987. addr);
  988. }
  989. void
  990. CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  991. CXXCtorType Type, bool ForVirtualBase,
  992. llvm::Value *This,
  993. CallExpr::const_arg_iterator ArgBeg,
  994. CallExpr::const_arg_iterator ArgEnd) {
  995. CGDebugInfo *DI = getDebugInfo();
  996. if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
  997. // If debug info for this class has not been emitted then this is the
  998. // right time to do so.
  999. const CXXRecordDecl *Parent = D->getParent();
  1000. DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
  1001. Parent->getLocation());
  1002. }
  1003. if (D->isTrivial()) {
  1004. if (ArgBeg == ArgEnd) {
  1005. // Trivial default constructor, no codegen required.
  1006. assert(D->isDefaultConstructor() &&
  1007. "trivial 0-arg ctor not a default ctor");
  1008. return;
  1009. }
  1010. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1011. assert(D->isCopyOrMoveConstructor() &&
  1012. "trivial 1-arg ctor not a copy/move ctor");
  1013. const Expr *E = (*ArgBeg);
  1014. QualType Ty = E->getType();
  1015. llvm::Value *Src = EmitLValue(E).getAddress();
  1016. EmitAggregateCopy(This, Src, Ty);
  1017. return;
  1018. }
  1019. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
  1020. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
  1021. EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
  1022. }
  1023. void
  1024. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1025. llvm::Value *This, llvm::Value *Src,
  1026. CallExpr::const_arg_iterator ArgBeg,
  1027. CallExpr::const_arg_iterator ArgEnd) {
  1028. if (D->isTrivial()) {
  1029. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1030. assert(D->isCopyOrMoveConstructor() &&
  1031. "trivial 1-arg ctor not a copy/move ctor");
  1032. EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
  1033. return;
  1034. }
  1035. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
  1036. clang::Ctor_Complete);
  1037. assert(D->isInstance() &&
  1038. "Trying to emit a member call expr on a static method!");
  1039. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  1040. CallArgList Args;
  1041. // Push the this ptr.
  1042. Args.add(RValue::get(This), D->getThisType(getContext()));
  1043. // Push the src ptr.
  1044. QualType QT = *(FPT->arg_type_begin());
  1045. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1046. Src = Builder.CreateBitCast(Src, t);
  1047. Args.add(RValue::get(Src), QT);
  1048. // Skip over first argument (Src).
  1049. ++ArgBeg;
  1050. CallExpr::const_arg_iterator Arg = ArgBeg;
  1051. for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
  1052. E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
  1053. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1054. EmitCallArg(Args, *Arg, *I);
  1055. }
  1056. // Either we've emitted all the call args, or we have a call to a
  1057. // variadic function.
  1058. assert((Arg == ArgEnd || FPT->isVariadic()) &&
  1059. "Extra arguments in non-variadic function!");
  1060. // If we still have any arguments, emit them using the type of the argument.
  1061. for (; Arg != ArgEnd; ++Arg) {
  1062. QualType ArgType = Arg->getType();
  1063. EmitCallArg(Args, *Arg, ArgType);
  1064. }
  1065. EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
  1066. ReturnValueSlot(), Args, D);
  1067. }
  1068. void
  1069. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1070. CXXCtorType CtorType,
  1071. const FunctionArgList &Args) {
  1072. CallArgList DelegateArgs;
  1073. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1074. assert(I != E && "no parameters to constructor");
  1075. // this
  1076. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1077. ++I;
  1078. // vtt
  1079. if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
  1080. /*ForVirtualBase=*/false)) {
  1081. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1082. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1083. if (CodeGenVTables::needsVTTParameter(CurGD)) {
  1084. assert(I != E && "cannot skip vtt parameter, already done with args");
  1085. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1086. ++I;
  1087. }
  1088. }
  1089. // Explicit arguments.
  1090. for (; I != E; ++I) {
  1091. const VarDecl *param = *I;
  1092. EmitDelegateCallArg(DelegateArgs, param);
  1093. }
  1094. EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
  1095. CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
  1096. ReturnValueSlot(), DelegateArgs, Ctor);
  1097. }
  1098. namespace {
  1099. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1100. const CXXDestructorDecl *Dtor;
  1101. llvm::Value *Addr;
  1102. CXXDtorType Type;
  1103. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1104. CXXDtorType Type)
  1105. : Dtor(D), Addr(Addr), Type(Type) {}
  1106. void Emit(CodeGenFunction &CGF, Flags flags) {
  1107. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1108. Addr);
  1109. }
  1110. };
  1111. }
  1112. void
  1113. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1114. const FunctionArgList &Args) {
  1115. assert(Ctor->isDelegatingConstructor());
  1116. llvm::Value *ThisPtr = LoadCXXThis();
  1117. QualType Ty = getContext().getTagDeclType(Ctor->getParent());
  1118. CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
  1119. AggValueSlot AggSlot =
  1120. AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
  1121. AggValueSlot::IsDestructed,
  1122. AggValueSlot::DoesNotNeedGCBarriers,
  1123. AggValueSlot::IsNotAliased);
  1124. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1125. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1126. if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1127. CXXDtorType Type =
  1128. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1129. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1130. ClassDecl->getDestructor(),
  1131. ThisPtr, Type);
  1132. }
  1133. }
  1134. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1135. CXXDtorType Type,
  1136. bool ForVirtualBase,
  1137. llvm::Value *This) {
  1138. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
  1139. ForVirtualBase);
  1140. llvm::Value *Callee = 0;
  1141. if (getContext().getLangOptions().AppleKext)
  1142. Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
  1143. DD->getParent());
  1144. if (!Callee)
  1145. Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
  1146. EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
  1147. }
  1148. namespace {
  1149. struct CallLocalDtor : EHScopeStack::Cleanup {
  1150. const CXXDestructorDecl *Dtor;
  1151. llvm::Value *Addr;
  1152. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1153. : Dtor(D), Addr(Addr) {}
  1154. void Emit(CodeGenFunction &CGF, Flags flags) {
  1155. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1156. /*ForVirtualBase=*/false, Addr);
  1157. }
  1158. };
  1159. }
  1160. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1161. llvm::Value *Addr) {
  1162. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1163. }
  1164. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1165. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1166. if (!ClassDecl) return;
  1167. if (ClassDecl->hasTrivialDestructor()) return;
  1168. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1169. assert(D && D->isUsed() && "destructor not marked as used!");
  1170. PushDestructorCleanup(D, Addr);
  1171. }
  1172. llvm::Value *
  1173. CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
  1174. const CXXRecordDecl *ClassDecl,
  1175. const CXXRecordDecl *BaseClassDecl) {
  1176. llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
  1177. CharUnits VBaseOffsetOffset =
  1178. CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
  1179. llvm::Value *VBaseOffsetPtr =
  1180. Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1181. "vbase.offset.ptr");
  1182. llvm::Type *PtrDiffTy =
  1183. ConvertType(getContext().getPointerDiffType());
  1184. VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
  1185. PtrDiffTy->getPointerTo());
  1186. llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
  1187. return VBaseOffset;
  1188. }
  1189. void
  1190. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1191. const CXXRecordDecl *NearestVBase,
  1192. CharUnits OffsetFromNearestVBase,
  1193. llvm::Constant *VTable,
  1194. const CXXRecordDecl *VTableClass) {
  1195. const CXXRecordDecl *RD = Base.getBase();
  1196. // Compute the address point.
  1197. llvm::Value *VTableAddressPoint;
  1198. // Check if we need to use a vtable from the VTT.
  1199. if (CodeGenVTables::needsVTTParameter(CurGD) &&
  1200. (RD->getNumVBases() || NearestVBase)) {
  1201. // Get the secondary vpointer index.
  1202. uint64_t VirtualPointerIndex =
  1203. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1204. /// Load the VTT.
  1205. llvm::Value *VTT = LoadCXXVTT();
  1206. if (VirtualPointerIndex)
  1207. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1208. // And load the address point from the VTT.
  1209. VTableAddressPoint = Builder.CreateLoad(VTT);
  1210. } else {
  1211. uint64_t AddressPoint =
  1212. CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
  1213. VTableAddressPoint =
  1214. Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
  1215. }
  1216. // Compute where to store the address point.
  1217. llvm::Value *VirtualOffset = 0;
  1218. CharUnits NonVirtualOffset = CharUnits::Zero();
  1219. if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
  1220. // We need to use the virtual base offset offset because the virtual base
  1221. // might have a different offset in the most derived class.
  1222. VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
  1223. NearestVBase);
  1224. NonVirtualOffset = OffsetFromNearestVBase;
  1225. } else {
  1226. // We can just use the base offset in the complete class.
  1227. NonVirtualOffset = Base.getBaseOffset();
  1228. }
  1229. // Apply the offsets.
  1230. llvm::Value *VTableField = LoadCXXThis();
  1231. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1232. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1233. NonVirtualOffset,
  1234. VirtualOffset);
  1235. // Finally, store the address point.
  1236. llvm::Type *AddressPointPtrTy =
  1237. VTableAddressPoint->getType()->getPointerTo();
  1238. VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
  1239. Builder.CreateStore(VTableAddressPoint, VTableField);
  1240. }
  1241. void
  1242. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1243. const CXXRecordDecl *NearestVBase,
  1244. CharUnits OffsetFromNearestVBase,
  1245. bool BaseIsNonVirtualPrimaryBase,
  1246. llvm::Constant *VTable,
  1247. const CXXRecordDecl *VTableClass,
  1248. VisitedVirtualBasesSetTy& VBases) {
  1249. // If this base is a non-virtual primary base the address point has already
  1250. // been set.
  1251. if (!BaseIsNonVirtualPrimaryBase) {
  1252. // Initialize the vtable pointer for this base.
  1253. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1254. VTable, VTableClass);
  1255. }
  1256. const CXXRecordDecl *RD = Base.getBase();
  1257. // Traverse bases.
  1258. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1259. E = RD->bases_end(); I != E; ++I) {
  1260. CXXRecordDecl *BaseDecl
  1261. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1262. // Ignore classes without a vtable.
  1263. if (!BaseDecl->isDynamicClass())
  1264. continue;
  1265. CharUnits BaseOffset;
  1266. CharUnits BaseOffsetFromNearestVBase;
  1267. bool BaseDeclIsNonVirtualPrimaryBase;
  1268. if (I->isVirtual()) {
  1269. // Check if we've visited this virtual base before.
  1270. if (!VBases.insert(BaseDecl))
  1271. continue;
  1272. const ASTRecordLayout &Layout =
  1273. getContext().getASTRecordLayout(VTableClass);
  1274. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1275. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1276. BaseDeclIsNonVirtualPrimaryBase = false;
  1277. } else {
  1278. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1279. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1280. BaseOffsetFromNearestVBase =
  1281. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1282. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1283. }
  1284. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1285. I->isVirtual() ? BaseDecl : NearestVBase,
  1286. BaseOffsetFromNearestVBase,
  1287. BaseDeclIsNonVirtualPrimaryBase,
  1288. VTable, VTableClass, VBases);
  1289. }
  1290. }
  1291. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1292. // Ignore classes without a vtable.
  1293. if (!RD->isDynamicClass())
  1294. return;
  1295. // Get the VTable.
  1296. llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
  1297. // Initialize the vtable pointers for this class and all of its bases.
  1298. VisitedVirtualBasesSetTy VBases;
  1299. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1300. /*NearestVBase=*/0,
  1301. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1302. /*BaseIsNonVirtualPrimaryBase=*/false,
  1303. VTable, RD, VBases);
  1304. }
  1305. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1306. llvm::Type *Ty) {
  1307. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1308. return Builder.CreateLoad(VTablePtrSrc, "vtable");
  1309. }
  1310. static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
  1311. const Expr *E = Base;
  1312. while (true) {
  1313. E = E->IgnoreParens();
  1314. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1315. if (CE->getCastKind() == CK_DerivedToBase ||
  1316. CE->getCastKind() == CK_UncheckedDerivedToBase ||
  1317. CE->getCastKind() == CK_NoOp) {
  1318. E = CE->getSubExpr();
  1319. continue;
  1320. }
  1321. }
  1322. break;
  1323. }
  1324. QualType DerivedType = E->getType();
  1325. if (const PointerType *PTy = DerivedType->getAs<PointerType>())
  1326. DerivedType = PTy->getPointeeType();
  1327. return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
  1328. }
  1329. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1330. // quite what we want.
  1331. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1332. while (true) {
  1333. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1334. E = PE->getSubExpr();
  1335. continue;
  1336. }
  1337. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1338. if (CE->getCastKind() == CK_NoOp) {
  1339. E = CE->getSubExpr();
  1340. continue;
  1341. }
  1342. }
  1343. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1344. if (UO->getOpcode() == UO_Extension) {
  1345. E = UO->getSubExpr();
  1346. continue;
  1347. }
  1348. }
  1349. return E;
  1350. }
  1351. }
  1352. /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
  1353. /// function call on the given expr can be devirtualized.
  1354. static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
  1355. const CXXMethodDecl *MD) {
  1356. // If the most derived class is marked final, we know that no subclass can
  1357. // override this member function and so we can devirtualize it. For example:
  1358. //
  1359. // struct A { virtual void f(); }
  1360. // struct B final : A { };
  1361. //
  1362. // void f(B *b) {
  1363. // b->f();
  1364. // }
  1365. //
  1366. const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
  1367. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1368. return true;
  1369. // If the member function is marked 'final', we know that it can't be
  1370. // overridden and can therefore devirtualize it.
  1371. if (MD->hasAttr<FinalAttr>())
  1372. return true;
  1373. // Similarly, if the class itself is marked 'final' it can't be overridden
  1374. // and we can therefore devirtualize the member function call.
  1375. if (MD->getParent()->hasAttr<FinalAttr>())
  1376. return true;
  1377. Base = skipNoOpCastsAndParens(Base);
  1378. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1379. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1380. // This is a record decl. We know the type and can devirtualize it.
  1381. return VD->getType()->isRecordType();
  1382. }
  1383. return false;
  1384. }
  1385. // We can always devirtualize calls on temporary object expressions.
  1386. if (isa<CXXConstructExpr>(Base))
  1387. return true;
  1388. // And calls on bound temporaries.
  1389. if (isa<CXXBindTemporaryExpr>(Base))
  1390. return true;
  1391. // Check if this is a call expr that returns a record type.
  1392. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  1393. return CE->getCallReturnType()->isRecordType();
  1394. // We can't devirtualize the call.
  1395. return false;
  1396. }
  1397. static bool UseVirtualCall(ASTContext &Context,
  1398. const CXXOperatorCallExpr *CE,
  1399. const CXXMethodDecl *MD) {
  1400. if (!MD->isVirtual())
  1401. return false;
  1402. // When building with -fapple-kext, all calls must go through the vtable since
  1403. // the kernel linker can do runtime patching of vtables.
  1404. if (Context.getLangOptions().AppleKext)
  1405. return true;
  1406. return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
  1407. }
  1408. llvm::Value *
  1409. CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1410. const CXXMethodDecl *MD,
  1411. llvm::Value *This) {
  1412. llvm::FunctionType *fnType =
  1413. CGM.getTypes().GetFunctionType(
  1414. CGM.getTypes().arrangeCXXMethodDeclaration(MD));
  1415. if (UseVirtualCall(getContext(), E, MD))
  1416. return BuildVirtualCall(MD, This, fnType);
  1417. return CGM.GetAddrOfFunction(MD, fnType);
  1418. }
  1419. void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
  1420. CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to block");
  1421. }
  1422. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  1423. const CXXRecordDecl *Lambda = MD->getParent();
  1424. DeclarationName Name
  1425. = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
  1426. DeclContext::lookup_const_result Calls = Lambda->lookup(Name);
  1427. CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++);
  1428. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1429. QualType ResultType = FPT->getResultType();
  1430. // Start building arguments for forwarding call
  1431. CallArgList CallArgs;
  1432. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  1433. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  1434. CallArgs.add(RValue::get(ThisPtr), ThisType);
  1435. // Add the rest of the parameters.
  1436. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  1437. E = MD->param_end(); I != E; ++I) {
  1438. ParmVarDecl *param = *I;
  1439. EmitDelegateCallArg(CallArgs, param);
  1440. }
  1441. // Get the address of the call operator.
  1442. GlobalDecl GD(CallOperator);
  1443. const CGFunctionInfo &CalleeFnInfo =
  1444. CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(),
  1445. RequiredArgs::forPrototypePlus(FPT, 1));
  1446. llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo);
  1447. llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
  1448. // Determine whether we have a return value slot to use.
  1449. ReturnValueSlot Slot;
  1450. if (!ResultType->isVoidType() &&
  1451. CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  1452. hasAggregateLLVMType(CurFnInfo->getReturnType()))
  1453. Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
  1454. // Now emit our call.
  1455. RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator);
  1456. // Forward the returned value
  1457. if (!ResultType->isVoidType() && Slot.isNull())
  1458. EmitReturnOfRValue(RV, ResultType);
  1459. }
  1460. void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
  1461. if (MD->isVariadic()) {
  1462. // FIXME: Making this work correctly is nasty because it requires either
  1463. // cloning the body of the call operator or making the call operator forward.
  1464. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  1465. }
  1466. EmitLambdaDelegatingInvokeBody(MD);
  1467. }