CGClass.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
  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 "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenFunction.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/StmtCXX.h"
  23. #include "clang/Basic/TargetBuiltins.h"
  24. #include "clang/CodeGen/CGFunctionInfo.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "llvm/IR/Intrinsics.h"
  27. #include "llvm/IR/Metadata.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. /// Return the best known alignment for an unknown pointer to a
  31. /// particular class.
  32. CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
  33. if (!RD->isCompleteDefinition())
  34. return CharUnits::One(); // Hopefully won't be used anywhere.
  35. auto &layout = getContext().getASTRecordLayout(RD);
  36. // If the class is final, then we know that the pointer points to an
  37. // object of that type and can use the full alignment.
  38. if (RD->hasAttr<FinalAttr>()) {
  39. return layout.getAlignment();
  40. // Otherwise, we have to assume it could be a subclass.
  41. } else {
  42. return layout.getNonVirtualAlignment();
  43. }
  44. }
  45. /// Return the best known alignment for a pointer to a virtual base,
  46. /// given the alignment of a pointer to the derived class.
  47. CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
  48. const CXXRecordDecl *derivedClass,
  49. const CXXRecordDecl *vbaseClass) {
  50. // The basic idea here is that an underaligned derived pointer might
  51. // indicate an underaligned base pointer.
  52. assert(vbaseClass->isCompleteDefinition());
  53. auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
  54. CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
  55. return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
  56. expectedVBaseAlign);
  57. }
  58. CharUnits
  59. CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
  60. const CXXRecordDecl *baseDecl,
  61. CharUnits expectedTargetAlign) {
  62. // If the base is an incomplete type (which is, alas, possible with
  63. // member pointers), be pessimistic.
  64. if (!baseDecl->isCompleteDefinition())
  65. return std::min(actualBaseAlign, expectedTargetAlign);
  66. auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
  67. CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
  68. // If the class is properly aligned, assume the target offset is, too.
  69. //
  70. // This actually isn't necessarily the right thing to do --- if the
  71. // class is a complete object, but it's only properly aligned for a
  72. // base subobject, then the alignments of things relative to it are
  73. // probably off as well. (Note that this requires the alignment of
  74. // the target to be greater than the NV alignment of the derived
  75. // class.)
  76. //
  77. // However, our approach to this kind of under-alignment can only
  78. // ever be best effort; after all, we're never going to propagate
  79. // alignments through variables or parameters. Note, in particular,
  80. // that constructing a polymorphic type in an address that's less
  81. // than pointer-aligned will generally trap in the constructor,
  82. // unless we someday add some sort of attribute to change the
  83. // assumed alignment of 'this'. So our goal here is pretty much
  84. // just to allow the user to explicitly say that a pointer is
  85. // under-aligned and then safely access its fields and v-tables.
  86. if (actualBaseAlign >= expectedBaseAlign) {
  87. return expectedTargetAlign;
  88. }
  89. // Otherwise, we might be offset by an arbitrary multiple of the
  90. // actual alignment. The correct adjustment is to take the min of
  91. // the two alignments.
  92. return std::min(actualBaseAlign, expectedTargetAlign);
  93. }
  94. Address CodeGenFunction::LoadCXXThisAddress() {
  95. assert(CurFuncDecl && "loading 'this' without a func declaration?");
  96. assert(isa<CXXMethodDecl>(CurFuncDecl));
  97. // Lazily compute CXXThisAlignment.
  98. if (CXXThisAlignment.isZero()) {
  99. // Just use the best known alignment for the parent.
  100. // TODO: if we're currently emitting a complete-object ctor/dtor,
  101. // we can always use the complete-object alignment.
  102. auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
  103. CXXThisAlignment = CGM.getClassPointerAlignment(RD);
  104. }
  105. return Address(LoadCXXThis(), CXXThisAlignment);
  106. }
  107. /// Emit the address of a field using a member data pointer.
  108. ///
  109. /// \param E Only used for emergency diagnostics
  110. Address
  111. CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  112. llvm::Value *memberPtr,
  113. const MemberPointerType *memberPtrType,
  114. AlignmentSource *alignSource) {
  115. // Ask the ABI to compute the actual address.
  116. llvm::Value *ptr =
  117. CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
  118. memberPtr, memberPtrType);
  119. QualType memberType = memberPtrType->getPointeeType();
  120. CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource);
  121. memberAlign =
  122. CGM.getDynamicOffsetAlignment(base.getAlignment(),
  123. memberPtrType->getClass()->getAsCXXRecordDecl(),
  124. memberAlign);
  125. return Address(ptr, memberAlign);
  126. }
  127. CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
  128. const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
  129. CastExpr::path_const_iterator End) {
  130. CharUnits Offset = CharUnits::Zero();
  131. const ASTContext &Context = getContext();
  132. const CXXRecordDecl *RD = DerivedClass;
  133. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  134. const CXXBaseSpecifier *Base = *I;
  135. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  136. // Get the layout.
  137. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  138. const CXXRecordDecl *BaseDecl =
  139. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  140. // Add the offset.
  141. Offset += Layout.getBaseClassOffset(BaseDecl);
  142. RD = BaseDecl;
  143. }
  144. return Offset;
  145. }
  146. llvm::Constant *
  147. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  148. CastExpr::path_const_iterator PathBegin,
  149. CastExpr::path_const_iterator PathEnd) {
  150. assert(PathBegin != PathEnd && "Base path should not be empty!");
  151. CharUnits Offset =
  152. computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
  153. if (Offset.isZero())
  154. return nullptr;
  155. llvm::Type *PtrDiffTy =
  156. Types.ConvertType(getContext().getPointerDiffType());
  157. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  158. }
  159. /// Gets the address of a direct base class within a complete object.
  160. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  161. /// when the type is known to be complete (e.g. in complete destructors).
  162. ///
  163. /// The object pointed to by 'This' is assumed to be non-null.
  164. Address
  165. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
  166. const CXXRecordDecl *Derived,
  167. const CXXRecordDecl *Base,
  168. bool BaseIsVirtual) {
  169. // 'this' must be a pointer (in some address space) to Derived.
  170. assert(This.getElementType() == ConvertType(Derived));
  171. // Compute the offset of the virtual base.
  172. CharUnits Offset;
  173. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  174. if (BaseIsVirtual)
  175. Offset = Layout.getVBaseClassOffset(Base);
  176. else
  177. Offset = Layout.getBaseClassOffset(Base);
  178. // Shift and cast down to the base type.
  179. // TODO: for complete types, this should be possible with a GEP.
  180. Address V = This;
  181. if (!Offset.isZero()) {
  182. V = Builder.CreateElementBitCast(V, Int8Ty);
  183. V = Builder.CreateConstInBoundsByteGEP(V, Offset);
  184. }
  185. V = Builder.CreateElementBitCast(V, ConvertType(Base));
  186. return V;
  187. }
  188. static Address
  189. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
  190. CharUnits nonVirtualOffset,
  191. llvm::Value *virtualOffset,
  192. const CXXRecordDecl *derivedClass,
  193. const CXXRecordDecl *nearestVBase) {
  194. // Assert that we have something to do.
  195. assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
  196. // Compute the offset from the static and dynamic components.
  197. llvm::Value *baseOffset;
  198. if (!nonVirtualOffset.isZero()) {
  199. baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
  200. nonVirtualOffset.getQuantity());
  201. if (virtualOffset) {
  202. baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
  203. }
  204. } else {
  205. baseOffset = virtualOffset;
  206. }
  207. // Apply the base offset.
  208. llvm::Value *ptr = addr.getPointer();
  209. ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
  210. ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
  211. // If we have a virtual component, the alignment of the result will
  212. // be relative only to the known alignment of that vbase.
  213. CharUnits alignment;
  214. if (virtualOffset) {
  215. assert(nearestVBase && "virtual offset without vbase?");
  216. alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
  217. derivedClass, nearestVBase);
  218. } else {
  219. alignment = addr.getAlignment();
  220. }
  221. alignment = alignment.alignmentAtOffset(nonVirtualOffset);
  222. return Address(ptr, alignment);
  223. }
  224. Address CodeGenFunction::GetAddressOfBaseClass(
  225. Address Value, const CXXRecordDecl *Derived,
  226. CastExpr::path_const_iterator PathBegin,
  227. CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
  228. SourceLocation Loc) {
  229. assert(PathBegin != PathEnd && "Base path should not be empty!");
  230. CastExpr::path_const_iterator Start = PathBegin;
  231. const CXXRecordDecl *VBase = nullptr;
  232. // Sema has done some convenient canonicalization here: if the
  233. // access path involved any virtual steps, the conversion path will
  234. // *start* with a step down to the correct virtual base subobject,
  235. // and hence will not require any further steps.
  236. if ((*Start)->isVirtual()) {
  237. VBase =
  238. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  239. ++Start;
  240. }
  241. // Compute the static offset of the ultimate destination within its
  242. // allocating subobject (the virtual base, if there is one, or else
  243. // the "complete" object that we see).
  244. CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
  245. VBase ? VBase : Derived, Start, PathEnd);
  246. // If there's a virtual step, we can sometimes "devirtualize" it.
  247. // For now, that's limited to when the derived type is final.
  248. // TODO: "devirtualize" this for accesses to known-complete objects.
  249. if (VBase && Derived->hasAttr<FinalAttr>()) {
  250. const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
  251. CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
  252. NonVirtualOffset += vBaseOffset;
  253. VBase = nullptr; // we no longer have a virtual step
  254. }
  255. // Get the base pointer type.
  256. llvm::Type *BasePtrTy =
  257. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  258. QualType DerivedTy = getContext().getRecordType(Derived);
  259. CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
  260. // If the static offset is zero and we don't have a virtual step,
  261. // just do a bitcast; null checks are unnecessary.
  262. if (NonVirtualOffset.isZero() && !VBase) {
  263. if (sanitizePerformTypeCheck()) {
  264. EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
  265. DerivedTy, DerivedAlign, !NullCheckValue);
  266. }
  267. return Builder.CreateBitCast(Value, BasePtrTy);
  268. }
  269. llvm::BasicBlock *origBB = nullptr;
  270. llvm::BasicBlock *endBB = nullptr;
  271. // Skip over the offset (and the vtable load) if we're supposed to
  272. // null-check the pointer.
  273. if (NullCheckValue) {
  274. origBB = Builder.GetInsertBlock();
  275. llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
  276. endBB = createBasicBlock("cast.end");
  277. llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
  278. Builder.CreateCondBr(isNull, endBB, notNullBB);
  279. EmitBlock(notNullBB);
  280. }
  281. if (sanitizePerformTypeCheck()) {
  282. EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
  283. Value.getPointer(), DerivedTy, DerivedAlign, true);
  284. }
  285. // Compute the virtual offset.
  286. llvm::Value *VirtualOffset = nullptr;
  287. if (VBase) {
  288. VirtualOffset =
  289. CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
  290. }
  291. // Apply both offsets.
  292. Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
  293. VirtualOffset, Derived, VBase);
  294. // Cast to the destination type.
  295. Value = Builder.CreateBitCast(Value, BasePtrTy);
  296. // Build a phi if we needed a null check.
  297. if (NullCheckValue) {
  298. llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
  299. Builder.CreateBr(endBB);
  300. EmitBlock(endBB);
  301. llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
  302. PHI->addIncoming(Value.getPointer(), notNullBB);
  303. PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
  304. Value = Address(PHI, Value.getAlignment());
  305. }
  306. return Value;
  307. }
  308. Address
  309. CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
  310. const CXXRecordDecl *Derived,
  311. CastExpr::path_const_iterator PathBegin,
  312. CastExpr::path_const_iterator PathEnd,
  313. bool NullCheckValue) {
  314. assert(PathBegin != PathEnd && "Base path should not be empty!");
  315. QualType DerivedTy =
  316. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  317. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  318. llvm::Value *NonVirtualOffset =
  319. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  320. if (!NonVirtualOffset) {
  321. // No offset, we can just cast back.
  322. return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
  323. }
  324. llvm::BasicBlock *CastNull = nullptr;
  325. llvm::BasicBlock *CastNotNull = nullptr;
  326. llvm::BasicBlock *CastEnd = nullptr;
  327. if (NullCheckValue) {
  328. CastNull = createBasicBlock("cast.null");
  329. CastNotNull = createBasicBlock("cast.notnull");
  330. CastEnd = createBasicBlock("cast.end");
  331. llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
  332. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  333. EmitBlock(CastNotNull);
  334. }
  335. // Apply the offset.
  336. llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
  337. Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
  338. "sub.ptr");
  339. // Just cast.
  340. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  341. // Produce a PHI if we had a null-check.
  342. if (NullCheckValue) {
  343. Builder.CreateBr(CastEnd);
  344. EmitBlock(CastNull);
  345. Builder.CreateBr(CastEnd);
  346. EmitBlock(CastEnd);
  347. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  348. PHI->addIncoming(Value, CastNotNull);
  349. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
  350. Value = PHI;
  351. }
  352. return Address(Value, CGM.getClassPointerAlignment(Derived));
  353. }
  354. llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
  355. bool ForVirtualBase,
  356. bool Delegating) {
  357. if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
  358. // This constructor/destructor does not need a VTT parameter.
  359. return nullptr;
  360. }
  361. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
  362. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  363. llvm::Value *VTT;
  364. uint64_t SubVTTIndex;
  365. if (Delegating) {
  366. // If this is a delegating constructor call, just load the VTT.
  367. return LoadCXXVTT();
  368. } else if (RD == Base) {
  369. // If the record matches the base, this is the complete ctor/dtor
  370. // variant calling the base variant in a class with virtual bases.
  371. assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
  372. "doing no-op VTT offset in base dtor/ctor?");
  373. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  374. SubVTTIndex = 0;
  375. } else {
  376. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  377. CharUnits BaseOffset = ForVirtualBase ?
  378. Layout.getVBaseClassOffset(Base) :
  379. Layout.getBaseClassOffset(Base);
  380. SubVTTIndex =
  381. CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  382. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  383. }
  384. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  385. // A VTT parameter was passed to the constructor, use it.
  386. VTT = LoadCXXVTT();
  387. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  388. } else {
  389. // We're the complete constructor, so get the VTT by name.
  390. VTT = CGM.getVTables().GetAddrOfVTT(RD);
  391. VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  392. }
  393. return VTT;
  394. }
  395. namespace {
  396. /// Call the destructor for a direct base class.
  397. struct CallBaseDtor final : EHScopeStack::Cleanup {
  398. const CXXRecordDecl *BaseClass;
  399. bool BaseIsVirtual;
  400. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  401. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  402. void Emit(CodeGenFunction &CGF, Flags flags) override {
  403. const CXXRecordDecl *DerivedClass =
  404. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  405. const CXXDestructorDecl *D = BaseClass->getDestructor();
  406. Address Addr =
  407. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
  408. DerivedClass, BaseClass,
  409. BaseIsVirtual);
  410. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
  411. /*Delegating=*/false, Addr);
  412. }
  413. };
  414. /// A visitor which checks whether an initializer uses 'this' in a
  415. /// way which requires the vtable to be properly set.
  416. struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
  417. typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
  418. bool UsesThis;
  419. DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
  420. // Black-list all explicit and implicit references to 'this'.
  421. //
  422. // Do we need to worry about external references to 'this' derived
  423. // from arbitrary code? If so, then anything which runs arbitrary
  424. // external code might potentially access the vtable.
  425. void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
  426. };
  427. } // end anonymous namespace
  428. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  429. DynamicThisUseChecker Checker(C);
  430. Checker.Visit(Init);
  431. return Checker.UsesThis;
  432. }
  433. static void EmitBaseInitializer(CodeGenFunction &CGF,
  434. const CXXRecordDecl *ClassDecl,
  435. CXXCtorInitializer *BaseInit,
  436. CXXCtorType CtorType) {
  437. assert(BaseInit->isBaseInitializer() &&
  438. "Must have base initializer!");
  439. Address ThisPtr = CGF.LoadCXXThisAddress();
  440. const Type *BaseType = BaseInit->getBaseClass();
  441. CXXRecordDecl *BaseClassDecl =
  442. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  443. bool isBaseVirtual = BaseInit->isBaseVirtual();
  444. // The base constructor doesn't construct virtual bases.
  445. if (CtorType == Ctor_Base && isBaseVirtual)
  446. return;
  447. // If the initializer for the base (other than the constructor
  448. // itself) accesses 'this' in any way, we need to initialize the
  449. // vtables.
  450. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  451. CGF.InitializeVTablePointers(ClassDecl);
  452. // We can pretend to be a complete class because it only matters for
  453. // virtual bases, and we only do virtual bases for complete ctors.
  454. Address V =
  455. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  456. BaseClassDecl,
  457. isBaseVirtual);
  458. AggValueSlot AggSlot =
  459. AggValueSlot::forAddr(V, Qualifiers(),
  460. AggValueSlot::IsDestructed,
  461. AggValueSlot::DoesNotNeedGCBarriers,
  462. AggValueSlot::IsNotAliased);
  463. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  464. if (CGF.CGM.getLangOpts().Exceptions &&
  465. !BaseClassDecl->hasTrivialDestructor())
  466. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  467. isBaseVirtual);
  468. }
  469. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  470. LValue LHS,
  471. Expr *Init,
  472. Address ArrayIndexVar,
  473. QualType T,
  474. ArrayRef<VarDecl *> ArrayIndexes,
  475. unsigned Index) {
  476. if (Index == ArrayIndexes.size()) {
  477. LValue LV = LHS;
  478. if (ArrayIndexVar.isValid()) {
  479. // If we have an array index variable, load it and use it as an offset.
  480. // Then, increment the value.
  481. llvm::Value *Dest = LHS.getPointer();
  482. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  483. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  484. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  485. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  486. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  487. // Update the LValue.
  488. CharUnits EltSize = CGF.getContext().getTypeSizeInChars(T);
  489. CharUnits Align = LV.getAlignment().alignmentOfArrayElement(EltSize);
  490. LV.setAddress(Address(Dest, Align));
  491. }
  492. switch (CGF.getEvaluationKind(T)) {
  493. case TEK_Scalar:
  494. CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
  495. break;
  496. case TEK_Complex:
  497. CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
  498. break;
  499. case TEK_Aggregate: {
  500. AggValueSlot Slot =
  501. AggValueSlot::forLValue(LV,
  502. AggValueSlot::IsDestructed,
  503. AggValueSlot::DoesNotNeedGCBarriers,
  504. AggValueSlot::IsNotAliased);
  505. CGF.EmitAggExpr(Init, Slot);
  506. break;
  507. }
  508. }
  509. return;
  510. }
  511. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  512. assert(Array && "Array initialization without the array type?");
  513. Address IndexVar = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
  514. // Initialize this index variable to zero.
  515. llvm::Value* Zero
  516. = llvm::Constant::getNullValue(IndexVar.getElementType());
  517. CGF.Builder.CreateStore(Zero, IndexVar);
  518. // Start the loop with a block that tests the condition.
  519. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  520. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  521. CGF.EmitBlock(CondBlock);
  522. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  523. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  524. // otherwise, go to the block after the for-loop.
  525. uint64_t NumElements = Array->getSize().getZExtValue();
  526. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  527. llvm::Value *NumElementsPtr =
  528. llvm::ConstantInt::get(Counter->getType(), NumElements);
  529. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  530. "isless");
  531. // If the condition is true, execute the body.
  532. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  533. CGF.EmitBlock(ForBody);
  534. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  535. // Inside the loop body recurse to emit the inner loop or, eventually, the
  536. // constructor call.
  537. EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
  538. Array->getElementType(), ArrayIndexes, Index + 1);
  539. CGF.EmitBlock(ContinueBlock);
  540. // Emit the increment of the loop counter.
  541. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  542. Counter = CGF.Builder.CreateLoad(IndexVar);
  543. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  544. CGF.Builder.CreateStore(NextVal, IndexVar);
  545. // Finally, branch back up to the condition for the next iteration.
  546. CGF.EmitBranch(CondBlock);
  547. // Emit the fall-through block.
  548. CGF.EmitBlock(AfterFor, true);
  549. }
  550. static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
  551. auto *CD = dyn_cast<CXXConstructorDecl>(D);
  552. if (!(CD && CD->isCopyOrMoveConstructor()) &&
  553. !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
  554. return false;
  555. // We can emit a memcpy for a trivial copy or move constructor/assignment.
  556. if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
  557. return true;
  558. // We *must* emit a memcpy for a defaulted union copy or move op.
  559. if (D->getParent()->isUnion() && D->isDefaulted())
  560. return true;
  561. return false;
  562. }
  563. static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
  564. CXXCtorInitializer *MemberInit,
  565. LValue &LHS) {
  566. FieldDecl *Field = MemberInit->getAnyMember();
  567. if (MemberInit->isIndirectMemberInitializer()) {
  568. // If we are initializing an anonymous union field, drill down to the field.
  569. IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
  570. for (const auto *I : IndirectField->chain())
  571. LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
  572. } else {
  573. LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
  574. }
  575. }
  576. static void EmitMemberInitializer(CodeGenFunction &CGF,
  577. const CXXRecordDecl *ClassDecl,
  578. CXXCtorInitializer *MemberInit,
  579. const CXXConstructorDecl *Constructor,
  580. FunctionArgList &Args) {
  581. ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
  582. assert(MemberInit->isAnyMemberInitializer() &&
  583. "Must have member initializer!");
  584. assert(MemberInit->getInit() && "Must have initializer!");
  585. // non-static data member initializers.
  586. FieldDecl *Field = MemberInit->getAnyMember();
  587. QualType FieldType = Field->getType();
  588. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  589. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  590. LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  591. EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
  592. // Special case: if we are in a copy or move constructor, and we are copying
  593. // an array of PODs or classes with trivial copy constructors, ignore the
  594. // AST and perform the copy we know is equivalent.
  595. // FIXME: This is hacky at best... if we had a bit more explicit information
  596. // in the AST, we could generalize it more easily.
  597. const ConstantArrayType *Array
  598. = CGF.getContext().getAsConstantArrayType(FieldType);
  599. if (Array && Constructor->isDefaulted() &&
  600. Constructor->isCopyOrMoveConstructor()) {
  601. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  602. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  603. if (BaseElementTy.isPODType(CGF.getContext()) ||
  604. (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
  605. unsigned SrcArgIndex =
  606. CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
  607. llvm::Value *SrcPtr
  608. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  609. LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  610. LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
  611. // Copy the aggregate.
  612. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  613. LHS.isVolatileQualified());
  614. // Ensure that we destroy the objects if an exception is thrown later in
  615. // the constructor.
  616. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  617. if (CGF.needsEHCleanup(dtorKind))
  618. CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  619. return;
  620. }
  621. }
  622. ArrayRef<VarDecl *> ArrayIndexes;
  623. if (MemberInit->getNumArrayIndices())
  624. ArrayIndexes = MemberInit->getArrayIndexes();
  625. CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
  626. }
  627. void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
  628. Expr *Init, ArrayRef<VarDecl *> ArrayIndexes) {
  629. QualType FieldType = Field->getType();
  630. switch (getEvaluationKind(FieldType)) {
  631. case TEK_Scalar:
  632. if (LHS.isSimple()) {
  633. EmitExprAsInit(Init, Field, LHS, false);
  634. } else {
  635. RValue RHS = RValue::get(EmitScalarExpr(Init));
  636. EmitStoreThroughLValue(RHS, LHS);
  637. }
  638. break;
  639. case TEK_Complex:
  640. EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
  641. break;
  642. case TEK_Aggregate: {
  643. Address ArrayIndexVar = Address::invalid();
  644. if (ArrayIndexes.size()) {
  645. // The LHS is a pointer to the first object we'll be constructing, as
  646. // a flat array.
  647. QualType BaseElementTy = getContext().getBaseElementType(FieldType);
  648. llvm::Type *BasePtr = ConvertType(BaseElementTy);
  649. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  650. Address BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(), BasePtr);
  651. LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  652. // Create an array index that will be used to walk over all of the
  653. // objects we're constructing.
  654. ArrayIndexVar = CreateMemTemp(getContext().getSizeType(), "object.index");
  655. llvm::Value *Zero =
  656. llvm::Constant::getNullValue(ArrayIndexVar.getElementType());
  657. Builder.CreateStore(Zero, ArrayIndexVar);
  658. // Emit the block variables for the array indices, if any.
  659. for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
  660. EmitAutoVarDecl(*ArrayIndexes[I]);
  661. }
  662. EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
  663. ArrayIndexes, 0);
  664. }
  665. }
  666. // Ensure that we destroy this object if an exception is thrown
  667. // later in the constructor.
  668. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  669. if (needsEHCleanup(dtorKind))
  670. pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  671. }
  672. /// Checks whether the given constructor is a valid subject for the
  673. /// complete-to-base constructor delegation optimization, i.e.
  674. /// emitting the complete constructor as a simple call to the base
  675. /// constructor.
  676. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  677. // Currently we disable the optimization for classes with virtual
  678. // bases because (1) the addresses of parameter variables need to be
  679. // consistent across all initializers but (2) the delegate function
  680. // call necessarily creates a second copy of the parameter variable.
  681. //
  682. // The limiting example (purely theoretical AFAIK):
  683. // struct A { A(int &c) { c++; } };
  684. // struct B : virtual A {
  685. // B(int count) : A(count) { printf("%d\n", count); }
  686. // };
  687. // ...although even this example could in principle be emitted as a
  688. // delegation since the address of the parameter doesn't escape.
  689. if (Ctor->getParent()->getNumVBases()) {
  690. // TODO: white-list trivial vbase initializers. This case wouldn't
  691. // be subject to the restrictions below.
  692. // TODO: white-list cases where:
  693. // - there are no non-reference parameters to the constructor
  694. // - the initializers don't access any non-reference parameters
  695. // - the initializers don't take the address of non-reference
  696. // parameters
  697. // - etc.
  698. // If we ever add any of the above cases, remember that:
  699. // - function-try-blocks will always blacklist this optimization
  700. // - we need to perform the constructor prologue and cleanup in
  701. // EmitConstructorBody.
  702. return false;
  703. }
  704. // We also disable the optimization for variadic functions because
  705. // it's impossible to "re-pass" varargs.
  706. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  707. return false;
  708. // FIXME: Decide if we can do a delegation of a delegating constructor.
  709. if (Ctor->isDelegatingConstructor())
  710. return false;
  711. return true;
  712. }
  713. // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
  714. // to poison the extra field paddings inserted under
  715. // -fsanitize-address-field-padding=1|2.
  716. void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
  717. ASTContext &Context = getContext();
  718. const CXXRecordDecl *ClassDecl =
  719. Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
  720. : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
  721. if (!ClassDecl->mayInsertExtraPadding()) return;
  722. struct SizeAndOffset {
  723. uint64_t Size;
  724. uint64_t Offset;
  725. };
  726. unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
  727. const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
  728. // Populate sizes and offsets of fields.
  729. SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
  730. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
  731. SSV[i].Offset =
  732. Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
  733. size_t NumFields = 0;
  734. for (const auto *Field : ClassDecl->fields()) {
  735. const FieldDecl *D = Field;
  736. std::pair<CharUnits, CharUnits> FieldInfo =
  737. Context.getTypeInfoInChars(D->getType());
  738. CharUnits FieldSize = FieldInfo.first;
  739. assert(NumFields < SSV.size());
  740. SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
  741. NumFields++;
  742. }
  743. assert(NumFields == SSV.size());
  744. if (SSV.size() <= 1) return;
  745. // We will insert calls to __asan_* run-time functions.
  746. // LLVM AddressSanitizer pass may decide to inline them later.
  747. llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
  748. llvm::FunctionType *FTy =
  749. llvm::FunctionType::get(CGM.VoidTy, Args, false);
  750. llvm::Constant *F = CGM.CreateRuntimeFunction(
  751. FTy, Prologue ? "__asan_poison_intra_object_redzone"
  752. : "__asan_unpoison_intra_object_redzone");
  753. llvm::Value *ThisPtr = LoadCXXThis();
  754. ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
  755. uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
  756. // For each field check if it has sufficient padding,
  757. // if so (un)poison it with a call.
  758. for (size_t i = 0; i < SSV.size(); i++) {
  759. uint64_t AsanAlignment = 8;
  760. uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
  761. uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
  762. uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
  763. if (PoisonSize < AsanAlignment || !SSV[i].Size ||
  764. (NextField % AsanAlignment) != 0)
  765. continue;
  766. Builder.CreateCall(
  767. F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
  768. Builder.getIntN(PtrSize, PoisonSize)});
  769. }
  770. }
  771. /// EmitConstructorBody - Emits the body of the current constructor.
  772. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  773. EmitAsanPrologueOrEpilogue(true);
  774. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  775. CXXCtorType CtorType = CurGD.getCtorType();
  776. assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
  777. CtorType == Ctor_Complete) &&
  778. "can only generate complete ctor for this ABI");
  779. // Before we go any further, try the complete->base constructor
  780. // delegation optimization.
  781. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
  782. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  783. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
  784. return;
  785. }
  786. const FunctionDecl *Definition = nullptr;
  787. Stmt *Body = Ctor->getBody(Definition);
  788. assert(Definition == Ctor && "emitting wrong constructor body");
  789. // Enter the function-try-block before the constructor prologue if
  790. // applicable.
  791. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  792. if (IsTryBody)
  793. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  794. incrementProfileCounter(Body);
  795. RunCleanupsScope RunCleanups(*this);
  796. // TODO: in restricted cases, we can emit the vbase initializers of
  797. // a complete ctor and then delegate to the base ctor.
  798. // Emit the constructor prologue, i.e. the base and member
  799. // initializers.
  800. EmitCtorPrologue(Ctor, CtorType, Args);
  801. // Emit the body of the statement.
  802. if (IsTryBody)
  803. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  804. else if (Body)
  805. EmitStmt(Body);
  806. // Emit any cleanup blocks associated with the member or base
  807. // initializers, which includes (along the exceptional path) the
  808. // destructors for those members and bases that were fully
  809. // constructed.
  810. RunCleanups.ForceCleanup();
  811. if (IsTryBody)
  812. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  813. }
  814. namespace {
  815. /// RAII object to indicate that codegen is copying the value representation
  816. /// instead of the object representation. Useful when copying a struct or
  817. /// class which has uninitialized members and we're only performing
  818. /// lvalue-to-rvalue conversion on the object but not its members.
  819. class CopyingValueRepresentation {
  820. public:
  821. explicit CopyingValueRepresentation(CodeGenFunction &CGF)
  822. : CGF(CGF), OldSanOpts(CGF.SanOpts) {
  823. CGF.SanOpts.set(SanitizerKind::Bool, false);
  824. CGF.SanOpts.set(SanitizerKind::Enum, false);
  825. }
  826. ~CopyingValueRepresentation() {
  827. CGF.SanOpts = OldSanOpts;
  828. }
  829. private:
  830. CodeGenFunction &CGF;
  831. SanitizerSet OldSanOpts;
  832. };
  833. }
  834. namespace {
  835. class FieldMemcpyizer {
  836. public:
  837. FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
  838. const VarDecl *SrcRec)
  839. : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
  840. RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
  841. FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
  842. LastFieldOffset(0), LastAddedFieldIndex(0) {}
  843. bool isMemcpyableField(FieldDecl *F) const {
  844. // Never memcpy fields when we are adding poisoned paddings.
  845. if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
  846. return false;
  847. Qualifiers Qual = F->getType().getQualifiers();
  848. if (Qual.hasVolatile() || Qual.hasObjCLifetime())
  849. return false;
  850. return true;
  851. }
  852. void addMemcpyableField(FieldDecl *F) {
  853. if (!FirstField)
  854. addInitialField(F);
  855. else
  856. addNextField(F);
  857. }
  858. CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
  859. unsigned LastFieldSize =
  860. LastField->isBitField() ?
  861. LastField->getBitWidthValue(CGF.getContext()) :
  862. CGF.getContext().getTypeSize(LastField->getType());
  863. uint64_t MemcpySizeBits =
  864. LastFieldOffset + LastFieldSize - FirstByteOffset +
  865. CGF.getContext().getCharWidth() - 1;
  866. CharUnits MemcpySize =
  867. CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
  868. return MemcpySize;
  869. }
  870. void emitMemcpy() {
  871. // Give the subclass a chance to bail out if it feels the memcpy isn't
  872. // worth it (e.g. Hasn't aggregated enough data).
  873. if (!FirstField) {
  874. return;
  875. }
  876. uint64_t FirstByteOffset;
  877. if (FirstField->isBitField()) {
  878. const CGRecordLayout &RL =
  879. CGF.getTypes().getCGRecordLayout(FirstField->getParent());
  880. const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
  881. // FirstFieldOffset is not appropriate for bitfields,
  882. // we need to use the storage offset instead.
  883. FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
  884. } else {
  885. FirstByteOffset = FirstFieldOffset;
  886. }
  887. CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
  888. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  889. Address ThisPtr = CGF.LoadCXXThisAddress();
  890. LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  891. LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
  892. llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
  893. LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  894. LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
  895. emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
  896. Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
  897. MemcpySize);
  898. reset();
  899. }
  900. void reset() {
  901. FirstField = nullptr;
  902. }
  903. protected:
  904. CodeGenFunction &CGF;
  905. const CXXRecordDecl *ClassDecl;
  906. private:
  907. void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
  908. llvm::PointerType *DPT = DestPtr.getType();
  909. llvm::Type *DBP =
  910. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
  911. DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
  912. llvm::PointerType *SPT = SrcPtr.getType();
  913. llvm::Type *SBP =
  914. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
  915. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
  916. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
  917. }
  918. void addInitialField(FieldDecl *F) {
  919. FirstField = F;
  920. LastField = F;
  921. FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  922. LastFieldOffset = FirstFieldOffset;
  923. LastAddedFieldIndex = F->getFieldIndex();
  924. return;
  925. }
  926. void addNextField(FieldDecl *F) {
  927. // For the most part, the following invariant will hold:
  928. // F->getFieldIndex() == LastAddedFieldIndex + 1
  929. // The one exception is that Sema won't add a copy-initializer for an
  930. // unnamed bitfield, which will show up here as a gap in the sequence.
  931. assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
  932. "Cannot aggregate fields out of order.");
  933. LastAddedFieldIndex = F->getFieldIndex();
  934. // The 'first' and 'last' fields are chosen by offset, rather than field
  935. // index. This allows the code to support bitfields, as well as regular
  936. // fields.
  937. uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  938. if (FOffset < FirstFieldOffset) {
  939. FirstField = F;
  940. FirstFieldOffset = FOffset;
  941. } else if (FOffset > LastFieldOffset) {
  942. LastField = F;
  943. LastFieldOffset = FOffset;
  944. }
  945. }
  946. const VarDecl *SrcRec;
  947. const ASTRecordLayout &RecLayout;
  948. FieldDecl *FirstField;
  949. FieldDecl *LastField;
  950. uint64_t FirstFieldOffset, LastFieldOffset;
  951. unsigned LastAddedFieldIndex;
  952. };
  953. class ConstructorMemcpyizer : public FieldMemcpyizer {
  954. private:
  955. /// Get source argument for copy constructor. Returns null if not a copy
  956. /// constructor.
  957. static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
  958. const CXXConstructorDecl *CD,
  959. FunctionArgList &Args) {
  960. if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
  961. return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
  962. return nullptr;
  963. }
  964. // Returns true if a CXXCtorInitializer represents a member initialization
  965. // that can be rolled into a memcpy.
  966. bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
  967. if (!MemcpyableCtor)
  968. return false;
  969. FieldDecl *Field = MemberInit->getMember();
  970. assert(Field && "No field for member init.");
  971. QualType FieldType = Field->getType();
  972. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  973. // Bail out on non-memcpyable, not-trivially-copyable members.
  974. if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
  975. !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
  976. FieldType->isReferenceType()))
  977. return false;
  978. // Bail out on volatile fields.
  979. if (!isMemcpyableField(Field))
  980. return false;
  981. // Otherwise we're good.
  982. return true;
  983. }
  984. public:
  985. ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
  986. FunctionArgList &Args)
  987. : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
  988. ConstructorDecl(CD),
  989. MemcpyableCtor(CD->isDefaulted() &&
  990. CD->isCopyOrMoveConstructor() &&
  991. CGF.getLangOpts().getGC() == LangOptions::NonGC),
  992. Args(Args) { }
  993. void addMemberInitializer(CXXCtorInitializer *MemberInit) {
  994. if (isMemberInitMemcpyable(MemberInit)) {
  995. AggregatedInits.push_back(MemberInit);
  996. addMemcpyableField(MemberInit->getMember());
  997. } else {
  998. emitAggregatedInits();
  999. EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
  1000. ConstructorDecl, Args);
  1001. }
  1002. }
  1003. void emitAggregatedInits() {
  1004. if (AggregatedInits.size() <= 1) {
  1005. // This memcpy is too small to be worthwhile. Fall back on default
  1006. // codegen.
  1007. if (!AggregatedInits.empty()) {
  1008. CopyingValueRepresentation CVR(CGF);
  1009. EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
  1010. AggregatedInits[0], ConstructorDecl, Args);
  1011. AggregatedInits.clear();
  1012. }
  1013. reset();
  1014. return;
  1015. }
  1016. pushEHDestructors();
  1017. emitMemcpy();
  1018. AggregatedInits.clear();
  1019. }
  1020. void pushEHDestructors() {
  1021. Address ThisPtr = CGF.LoadCXXThisAddress();
  1022. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  1023. LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  1024. for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
  1025. CXXCtorInitializer *MemberInit = AggregatedInits[i];
  1026. QualType FieldType = MemberInit->getAnyMember()->getType();
  1027. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  1028. if (!CGF.needsEHCleanup(dtorKind))
  1029. continue;
  1030. LValue FieldLHS = LHS;
  1031. EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
  1032. CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
  1033. }
  1034. }
  1035. void finish() {
  1036. emitAggregatedInits();
  1037. }
  1038. private:
  1039. const CXXConstructorDecl *ConstructorDecl;
  1040. bool MemcpyableCtor;
  1041. FunctionArgList &Args;
  1042. SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
  1043. };
  1044. class AssignmentMemcpyizer : public FieldMemcpyizer {
  1045. private:
  1046. // Returns the memcpyable field copied by the given statement, if one
  1047. // exists. Otherwise returns null.
  1048. FieldDecl *getMemcpyableField(Stmt *S) {
  1049. if (!AssignmentsMemcpyable)
  1050. return nullptr;
  1051. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  1052. // Recognise trivial assignments.
  1053. if (BO->getOpcode() != BO_Assign)
  1054. return nullptr;
  1055. MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
  1056. if (!ME)
  1057. return nullptr;
  1058. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  1059. if (!Field || !isMemcpyableField(Field))
  1060. return nullptr;
  1061. Stmt *RHS = BO->getRHS();
  1062. if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
  1063. RHS = EC->getSubExpr();
  1064. if (!RHS)
  1065. return nullptr;
  1066. MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
  1067. if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
  1068. return nullptr;
  1069. return Field;
  1070. } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
  1071. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
  1072. if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
  1073. return nullptr;
  1074. MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
  1075. if (!IOA)
  1076. return nullptr;
  1077. FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
  1078. if (!Field || !isMemcpyableField(Field))
  1079. return nullptr;
  1080. MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
  1081. if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
  1082. return nullptr;
  1083. return Field;
  1084. } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  1085. FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1086. if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
  1087. return nullptr;
  1088. Expr *DstPtr = CE->getArg(0);
  1089. if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
  1090. DstPtr = DC->getSubExpr();
  1091. UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
  1092. if (!DUO || DUO->getOpcode() != UO_AddrOf)
  1093. return nullptr;
  1094. MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
  1095. if (!ME)
  1096. return nullptr;
  1097. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  1098. if (!Field || !isMemcpyableField(Field))
  1099. return nullptr;
  1100. Expr *SrcPtr = CE->getArg(1);
  1101. if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
  1102. SrcPtr = SC->getSubExpr();
  1103. UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
  1104. if (!SUO || SUO->getOpcode() != UO_AddrOf)
  1105. return nullptr;
  1106. MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
  1107. if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
  1108. return nullptr;
  1109. return Field;
  1110. }
  1111. return nullptr;
  1112. }
  1113. bool AssignmentsMemcpyable;
  1114. SmallVector<Stmt*, 16> AggregatedStmts;
  1115. public:
  1116. AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
  1117. FunctionArgList &Args)
  1118. : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
  1119. AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
  1120. assert(Args.size() == 2);
  1121. }
  1122. void emitAssignment(Stmt *S) {
  1123. FieldDecl *F = getMemcpyableField(S);
  1124. if (F) {
  1125. addMemcpyableField(F);
  1126. AggregatedStmts.push_back(S);
  1127. } else {
  1128. emitAggregatedStmts();
  1129. CGF.EmitStmt(S);
  1130. }
  1131. }
  1132. void emitAggregatedStmts() {
  1133. if (AggregatedStmts.size() <= 1) {
  1134. if (!AggregatedStmts.empty()) {
  1135. CopyingValueRepresentation CVR(CGF);
  1136. CGF.EmitStmt(AggregatedStmts[0]);
  1137. }
  1138. reset();
  1139. }
  1140. emitMemcpy();
  1141. AggregatedStmts.clear();
  1142. }
  1143. void finish() {
  1144. emitAggregatedStmts();
  1145. }
  1146. };
  1147. } // end anonymous namespace
  1148. static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
  1149. const Type *BaseType = BaseInit->getBaseClass();
  1150. const auto *BaseClassDecl =
  1151. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  1152. return BaseClassDecl->isDynamicClass();
  1153. }
  1154. /// EmitCtorPrologue - This routine generates necessary code to initialize
  1155. /// base classes and non-static data members belonging to this constructor.
  1156. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  1157. CXXCtorType CtorType,
  1158. FunctionArgList &Args) {
  1159. if (CD->isDelegatingConstructor())
  1160. return EmitDelegatingCXXConstructorCall(CD, Args);
  1161. const CXXRecordDecl *ClassDecl = CD->getParent();
  1162. CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  1163. E = CD->init_end();
  1164. llvm::BasicBlock *BaseCtorContinueBB = nullptr;
  1165. if (ClassDecl->getNumVBases() &&
  1166. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1167. // The ABIs that don't have constructor variants need to put a branch
  1168. // before the virtual base initialization code.
  1169. BaseCtorContinueBB =
  1170. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  1171. assert(BaseCtorContinueBB);
  1172. }
  1173. llvm::Value *const OldThis = CXXThisValue;
  1174. // Virtual base initializers first.
  1175. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  1176. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1177. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1178. isInitializerOfDynamicClass(*B))
  1179. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1180. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1181. }
  1182. if (BaseCtorContinueBB) {
  1183. // Complete object handler should continue to the remaining initializers.
  1184. Builder.CreateBr(BaseCtorContinueBB);
  1185. EmitBlock(BaseCtorContinueBB);
  1186. }
  1187. // Then, non-virtual base initializers.
  1188. for (; B != E && (*B)->isBaseInitializer(); B++) {
  1189. assert(!(*B)->isBaseVirtual());
  1190. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1191. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1192. isInitializerOfDynamicClass(*B))
  1193. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1194. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1195. }
  1196. CXXThisValue = OldThis;
  1197. InitializeVTablePointers(ClassDecl);
  1198. // And finally, initialize class members.
  1199. FieldConstructionScope FCS(*this, LoadCXXThisAddress());
  1200. ConstructorMemcpyizer CM(*this, CD, Args);
  1201. for (; B != E; B++) {
  1202. CXXCtorInitializer *Member = (*B);
  1203. assert(!Member->isBaseInitializer());
  1204. assert(Member->isAnyMemberInitializer() &&
  1205. "Delegating initializer on non-delegating constructor");
  1206. CM.addMemberInitializer(Member);
  1207. }
  1208. CM.finish();
  1209. }
  1210. static bool
  1211. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1212. static bool
  1213. HasTrivialDestructorBody(ASTContext &Context,
  1214. const CXXRecordDecl *BaseClassDecl,
  1215. const CXXRecordDecl *MostDerivedClassDecl)
  1216. {
  1217. // If the destructor is trivial we don't have to check anything else.
  1218. if (BaseClassDecl->hasTrivialDestructor())
  1219. return true;
  1220. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1221. return false;
  1222. // Check fields.
  1223. for (const auto *Field : BaseClassDecl->fields())
  1224. if (!FieldHasTrivialDestructorBody(Context, Field))
  1225. return false;
  1226. // Check non-virtual bases.
  1227. for (const auto &I : BaseClassDecl->bases()) {
  1228. if (I.isVirtual())
  1229. continue;
  1230. const CXXRecordDecl *NonVirtualBase =
  1231. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1232. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1233. MostDerivedClassDecl))
  1234. return false;
  1235. }
  1236. if (BaseClassDecl == MostDerivedClassDecl) {
  1237. // Check virtual bases.
  1238. for (const auto &I : BaseClassDecl->vbases()) {
  1239. const CXXRecordDecl *VirtualBase =
  1240. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1241. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1242. MostDerivedClassDecl))
  1243. return false;
  1244. }
  1245. }
  1246. return true;
  1247. }
  1248. static bool
  1249. FieldHasTrivialDestructorBody(ASTContext &Context,
  1250. const FieldDecl *Field)
  1251. {
  1252. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1253. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1254. if (!RT)
  1255. return true;
  1256. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1257. // The destructor for an implicit anonymous union member is never invoked.
  1258. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  1259. return false;
  1260. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1261. }
  1262. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1263. /// any vtable pointers before calling this destructor.
  1264. static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
  1265. const CXXDestructorDecl *Dtor) {
  1266. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1267. if (!ClassDecl->isDynamicClass())
  1268. return true;
  1269. if (!Dtor->hasTrivialBody())
  1270. return false;
  1271. // Check the fields.
  1272. for (const auto *Field : ClassDecl->fields())
  1273. if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
  1274. return false;
  1275. return true;
  1276. }
  1277. /// EmitDestructorBody - Emits the body of the current destructor.
  1278. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1279. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1280. CXXDtorType DtorType = CurGD.getDtorType();
  1281. Stmt *Body = Dtor->getBody();
  1282. if (Body)
  1283. incrementProfileCounter(Body);
  1284. // The call to operator delete in a deleting destructor happens
  1285. // outside of the function-try-block, which means it's always
  1286. // possible to delegate the destructor body to the complete
  1287. // destructor. Do so.
  1288. if (DtorType == Dtor_Deleting) {
  1289. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1290. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1291. /*Delegating=*/false, LoadCXXThisAddress());
  1292. PopCleanupBlock();
  1293. return;
  1294. }
  1295. // If the body is a function-try-block, enter the try before
  1296. // anything else.
  1297. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1298. if (isTryBody)
  1299. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1300. EmitAsanPrologueOrEpilogue(false);
  1301. // Enter the epilogue cleanups.
  1302. RunCleanupsScope DtorEpilogue(*this);
  1303. // If this is the complete variant, just invoke the base variant;
  1304. // the epilogue will destruct the virtual bases. But we can't do
  1305. // this optimization if the body is a function-try-block, because
  1306. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1307. // always delegate because we might not have a definition in this TU.
  1308. switch (DtorType) {
  1309. case Dtor_Comdat:
  1310. llvm_unreachable("not expecting a COMDAT");
  1311. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1312. case Dtor_Complete:
  1313. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1314. "can't emit a dtor without a body for non-Microsoft ABIs");
  1315. // Enter the cleanup scopes for virtual bases.
  1316. EnterDtorCleanups(Dtor, Dtor_Complete);
  1317. if (!isTryBody) {
  1318. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1319. /*Delegating=*/false, LoadCXXThisAddress());
  1320. break;
  1321. }
  1322. // Fallthrough: act like we're in the base variant.
  1323. case Dtor_Base:
  1324. assert(Body);
  1325. // Enter the cleanup scopes for fields and non-virtual bases.
  1326. EnterDtorCleanups(Dtor, Dtor_Base);
  1327. // Initialize the vtable pointers before entering the body.
  1328. if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
  1329. // Insert the llvm.invariant.group.barrier intrinsic before initializing
  1330. // the vptrs to cancel any previous assumptions we might have made.
  1331. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1332. CGM.getCodeGenOpts().OptimizationLevel > 0)
  1333. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1334. InitializeVTablePointers(Dtor->getParent());
  1335. }
  1336. if (isTryBody)
  1337. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1338. else if (Body)
  1339. EmitStmt(Body);
  1340. else {
  1341. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1342. // nothing to do besides what's in the epilogue
  1343. }
  1344. // -fapple-kext must inline any call to this dtor into
  1345. // the caller's body.
  1346. if (getLangOpts().AppleKext)
  1347. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1348. break;
  1349. }
  1350. // Jump out through the epilogue cleanups.
  1351. DtorEpilogue.ForceCleanup();
  1352. // Exit the try if applicable.
  1353. if (isTryBody)
  1354. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1355. }
  1356. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1357. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1358. const Stmt *RootS = AssignOp->getBody();
  1359. assert(isa<CompoundStmt>(RootS) &&
  1360. "Body of an implicit assignment operator should be compound stmt.");
  1361. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1362. LexicalScope Scope(*this, RootCS->getSourceRange());
  1363. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1364. for (auto *I : RootCS->body())
  1365. AM.emitAssignment(I);
  1366. AM.finish();
  1367. }
  1368. namespace {
  1369. /// Call the operator delete associated with the current destructor.
  1370. struct CallDtorDelete final : EHScopeStack::Cleanup {
  1371. CallDtorDelete() {}
  1372. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1373. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1374. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1375. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1376. CGF.getContext().getTagDeclType(ClassDecl));
  1377. }
  1378. };
  1379. struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
  1380. llvm::Value *ShouldDeleteCondition;
  1381. public:
  1382. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1383. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1384. assert(ShouldDeleteCondition != nullptr);
  1385. }
  1386. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1387. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1388. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1389. llvm::Value *ShouldCallDelete
  1390. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1391. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1392. CGF.EmitBlock(callDeleteBB);
  1393. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1394. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1395. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1396. CGF.getContext().getTagDeclType(ClassDecl));
  1397. CGF.Builder.CreateBr(continueBB);
  1398. CGF.EmitBlock(continueBB);
  1399. }
  1400. };
  1401. class DestroyField final : public EHScopeStack::Cleanup {
  1402. const FieldDecl *field;
  1403. CodeGenFunction::Destroyer *destroyer;
  1404. bool useEHCleanupForArray;
  1405. public:
  1406. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1407. bool useEHCleanupForArray)
  1408. : field(field), destroyer(destroyer),
  1409. useEHCleanupForArray(useEHCleanupForArray) {}
  1410. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1411. // Find the address of the field.
  1412. Address thisValue = CGF.LoadCXXThisAddress();
  1413. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1414. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1415. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1416. assert(LV.isSimple());
  1417. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  1418. flags.isForNormalCleanup() && useEHCleanupForArray);
  1419. }
  1420. };
  1421. static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
  1422. CharUnits::QuantityType PoisonSize) {
  1423. // Pass in void pointer and size of region as arguments to runtime
  1424. // function
  1425. llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
  1426. llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
  1427. llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
  1428. llvm::FunctionType *FnType =
  1429. llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
  1430. llvm::Value *Fn =
  1431. CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
  1432. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1433. }
  1434. class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
  1435. const CXXDestructorDecl *Dtor;
  1436. public:
  1437. SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1438. // Generate function call for handling object poisoning.
  1439. // Disables tail call elimination, to prevent the current stack frame
  1440. // from disappearing from the stack trace.
  1441. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1442. const ASTRecordLayout &Layout =
  1443. CGF.getContext().getASTRecordLayout(Dtor->getParent());
  1444. // Nothing to poison.
  1445. if (Layout.getFieldCount() == 0)
  1446. return;
  1447. // Prevent the current stack frame from disappearing from the stack trace.
  1448. CGF.CurFn->addFnAttr("disable-tail-calls", "true");
  1449. // Construct pointer to region to begin poisoning, and calculate poison
  1450. // size, so that only members declared in this class are poisoned.
  1451. ASTContext &Context = CGF.getContext();
  1452. unsigned fieldIndex = 0;
  1453. int startIndex = -1;
  1454. // RecordDecl::field_iterator Field;
  1455. for (const FieldDecl *Field : Dtor->getParent()->fields()) {
  1456. // Poison field if it is trivial
  1457. if (FieldHasTrivialDestructorBody(Context, Field)) {
  1458. // Start sanitizing at this field
  1459. if (startIndex < 0)
  1460. startIndex = fieldIndex;
  1461. // Currently on the last field, and it must be poisoned with the
  1462. // current block.
  1463. if (fieldIndex == Layout.getFieldCount() - 1) {
  1464. PoisonMembers(CGF, startIndex, Layout.getFieldCount());
  1465. }
  1466. } else if (startIndex >= 0) {
  1467. // No longer within a block of memory to poison, so poison the block
  1468. PoisonMembers(CGF, startIndex, fieldIndex);
  1469. // Re-set the start index
  1470. startIndex = -1;
  1471. }
  1472. fieldIndex += 1;
  1473. }
  1474. }
  1475. private:
  1476. /// \param layoutStartOffset index of the ASTRecordLayout field to
  1477. /// start poisoning (inclusive)
  1478. /// \param layoutEndOffset index of the ASTRecordLayout field to
  1479. /// end poisoning (exclusive)
  1480. void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
  1481. unsigned layoutEndOffset) {
  1482. ASTContext &Context = CGF.getContext();
  1483. const ASTRecordLayout &Layout =
  1484. Context.getASTRecordLayout(Dtor->getParent());
  1485. llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
  1486. CGF.SizeTy,
  1487. Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
  1488. .getQuantity());
  1489. llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
  1490. CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
  1491. OffsetSizePtr);
  1492. CharUnits::QuantityType PoisonSize;
  1493. if (layoutEndOffset >= Layout.getFieldCount()) {
  1494. PoisonSize = Layout.getNonVirtualSize().getQuantity() -
  1495. Context.toCharUnitsFromBits(
  1496. Layout.getFieldOffset(layoutStartOffset))
  1497. .getQuantity();
  1498. } else {
  1499. PoisonSize = Context.toCharUnitsFromBits(
  1500. Layout.getFieldOffset(layoutEndOffset) -
  1501. Layout.getFieldOffset(layoutStartOffset))
  1502. .getQuantity();
  1503. }
  1504. if (PoisonSize == 0)
  1505. return;
  1506. EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
  1507. }
  1508. };
  1509. class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
  1510. const CXXDestructorDecl *Dtor;
  1511. public:
  1512. SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1513. // Generate function call for handling vtable pointer poisoning.
  1514. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1515. assert(Dtor->getParent()->isDynamicClass());
  1516. (void)Dtor;
  1517. ASTContext &Context = CGF.getContext();
  1518. // Poison vtable and vtable ptr if they exist for this class.
  1519. llvm::Value *VTablePtr = CGF.LoadCXXThis();
  1520. CharUnits::QuantityType PoisonSize =
  1521. Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
  1522. // Pass in void pointer and size of region as arguments to runtime
  1523. // function
  1524. EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
  1525. }
  1526. };
  1527. } // end anonymous namespace
  1528. /// \brief Emit all code that comes at the end of class's
  1529. /// destructor. This is to call destructors on members and base classes
  1530. /// in reverse order of their construction.
  1531. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1532. CXXDtorType DtorType) {
  1533. assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
  1534. "Should not emit dtor epilogue for non-exported trivial dtor!");
  1535. // The deleting-destructor phase just needs to call the appropriate
  1536. // operator delete that Sema picked up.
  1537. if (DtorType == Dtor_Deleting) {
  1538. assert(DD->getOperatorDelete() &&
  1539. "operator delete missing - EnterDtorCleanups");
  1540. if (CXXStructorImplicitParamValue) {
  1541. // If there is an implicit param to the deleting dtor, it's a boolean
  1542. // telling whether we should call delete at the end of the dtor.
  1543. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1544. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1545. } else {
  1546. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1547. }
  1548. return;
  1549. }
  1550. const CXXRecordDecl *ClassDecl = DD->getParent();
  1551. // Unions have no bases and do not call field destructors.
  1552. if (ClassDecl->isUnion())
  1553. return;
  1554. // The complete-destructor phase just destructs all the virtual bases.
  1555. if (DtorType == Dtor_Complete) {
  1556. // Poison the vtable pointer such that access after the base
  1557. // and member destructors are invoked is invalid.
  1558. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1559. SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
  1560. ClassDecl->isPolymorphic())
  1561. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1562. // We push them in the forward order so that they'll be popped in
  1563. // the reverse order.
  1564. for (const auto &Base : ClassDecl->vbases()) {
  1565. CXXRecordDecl *BaseClassDecl
  1566. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  1567. // Ignore trivial destructors.
  1568. if (BaseClassDecl->hasTrivialDestructor())
  1569. continue;
  1570. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1571. BaseClassDecl,
  1572. /*BaseIsVirtual*/ true);
  1573. }
  1574. return;
  1575. }
  1576. assert(DtorType == Dtor_Base);
  1577. // Poison the vtable pointer if it has no virtual bases, but inherits
  1578. // virtual functions.
  1579. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1580. SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
  1581. ClassDecl->isPolymorphic())
  1582. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1583. // Destroy non-virtual bases.
  1584. for (const auto &Base : ClassDecl->bases()) {
  1585. // Ignore virtual bases.
  1586. if (Base.isVirtual())
  1587. continue;
  1588. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1589. // Ignore trivial destructors.
  1590. if (BaseClassDecl->hasTrivialDestructor())
  1591. continue;
  1592. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1593. BaseClassDecl,
  1594. /*BaseIsVirtual*/ false);
  1595. }
  1596. // Poison fields such that access after their destructors are
  1597. // invoked, and before the base class destructor runs, is invalid.
  1598. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1599. SanOpts.has(SanitizerKind::Memory))
  1600. EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
  1601. // Destroy direct fields.
  1602. for (const auto *Field : ClassDecl->fields()) {
  1603. QualType type = Field->getType();
  1604. QualType::DestructionKind dtorKind = type.isDestructedType();
  1605. if (!dtorKind) continue;
  1606. // Anonymous union members do not have their destructors called.
  1607. const RecordType *RT = type->getAsUnionType();
  1608. if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
  1609. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1610. EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
  1611. getDestroyer(dtorKind),
  1612. cleanupKind & EHCleanup);
  1613. }
  1614. }
  1615. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1616. /// constructor for each of several members of an array.
  1617. ///
  1618. /// \param ctor the constructor to call for each element
  1619. /// \param arrayType the type of the array to initialize
  1620. /// \param arrayBegin an arrayType*
  1621. /// \param zeroInitialize true if each element should be
  1622. /// zero-initialized before it is constructed
  1623. void CodeGenFunction::EmitCXXAggrConstructorCall(
  1624. const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
  1625. Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
  1626. QualType elementType;
  1627. llvm::Value *numElements =
  1628. emitArrayLength(arrayType, elementType, arrayBegin);
  1629. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
  1630. }
  1631. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1632. /// constructor for each of several members of an array.
  1633. ///
  1634. /// \param ctor the constructor to call for each element
  1635. /// \param numElements the number of elements in the array;
  1636. /// may be zero
  1637. /// \param arrayBase a T*, where T is the type constructed by ctor
  1638. /// \param zeroInitialize true if each element should be
  1639. /// zero-initialized before it is constructed
  1640. void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1641. llvm::Value *numElements,
  1642. Address arrayBase,
  1643. const CXXConstructExpr *E,
  1644. bool zeroInitialize) {
  1645. // It's legal for numElements to be zero. This can happen both
  1646. // dynamically, because x can be zero in 'new A[x]', and statically,
  1647. // because of GCC extensions that permit zero-length arrays. There
  1648. // are probably legitimate places where we could assume that this
  1649. // doesn't happen, but it's not clear that it's worth it.
  1650. llvm::BranchInst *zeroCheckBranch = nullptr;
  1651. // Optimize for a constant count.
  1652. llvm::ConstantInt *constantCount
  1653. = dyn_cast<llvm::ConstantInt>(numElements);
  1654. if (constantCount) {
  1655. // Just skip out if the constant count is zero.
  1656. if (constantCount->isZero()) return;
  1657. // Otherwise, emit the check.
  1658. } else {
  1659. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1660. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1661. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1662. EmitBlock(loopBB);
  1663. }
  1664. // Find the end of the array.
  1665. llvm::Value *arrayBegin = arrayBase.getPointer();
  1666. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  1667. "arrayctor.end");
  1668. // Enter the loop, setting up a phi for the current location to initialize.
  1669. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1670. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1671. EmitBlock(loopBB);
  1672. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1673. "arrayctor.cur");
  1674. cur->addIncoming(arrayBegin, entryBB);
  1675. // Inside the loop body, emit the constructor call on the array element.
  1676. // The alignment of the base, adjusted by the size of a single element,
  1677. // provides a conservative estimate of the alignment of every element.
  1678. // (This assumes we never start tracking offsetted alignments.)
  1679. //
  1680. // Note that these are complete objects and so we don't need to
  1681. // use the non-virtual size or alignment.
  1682. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1683. CharUnits eltAlignment =
  1684. arrayBase.getAlignment()
  1685. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1686. Address curAddr = Address(cur, eltAlignment);
  1687. // Zero initialize the storage, if requested.
  1688. if (zeroInitialize)
  1689. EmitNullInitialization(curAddr, type);
  1690. // C++ [class.temporary]p4:
  1691. // There are two contexts in which temporaries are destroyed at a different
  1692. // point than the end of the full-expression. The first context is when a
  1693. // default constructor is called to initialize an element of an array.
  1694. // If the constructor has one or more default arguments, the destruction of
  1695. // every temporary created in a default argument expression is sequenced
  1696. // before the construction of the next array element, if any.
  1697. {
  1698. RunCleanupsScope Scope(*this);
  1699. // Evaluate the constructor and its arguments in a regular
  1700. // partial-destroy cleanup.
  1701. if (getLangOpts().Exceptions &&
  1702. !ctor->getParent()->hasTrivialDestructor()) {
  1703. Destroyer *destroyer = destroyCXXObject;
  1704. pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
  1705. *destroyer);
  1706. }
  1707. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
  1708. /*Delegating=*/false, curAddr, E);
  1709. }
  1710. // Go to the next element.
  1711. llvm::Value *next =
  1712. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  1713. "arrayctor.next");
  1714. cur->addIncoming(next, Builder.GetInsertBlock());
  1715. // Check whether that's the end of the loop.
  1716. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1717. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1718. Builder.CreateCondBr(done, contBB, loopBB);
  1719. // Patch the earlier check to skip over the loop.
  1720. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1721. EmitBlock(contBB);
  1722. }
  1723. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1724. Address addr,
  1725. QualType type) {
  1726. const RecordType *rtype = type->castAs<RecordType>();
  1727. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1728. const CXXDestructorDecl *dtor = record->getDestructor();
  1729. assert(!dtor->isTrivial());
  1730. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1731. /*Delegating=*/false, addr);
  1732. }
  1733. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1734. CXXCtorType Type,
  1735. bool ForVirtualBase,
  1736. bool Delegating, Address This,
  1737. const CXXConstructExpr *E) {
  1738. const CXXRecordDecl *ClassDecl = D->getParent();
  1739. // C++11 [class.mfct.non-static]p2:
  1740. // If a non-static member function of a class X is called for an object that
  1741. // is not of type X, or of a type derived from X, the behavior is undefined.
  1742. // FIXME: Provide a source location here.
  1743. EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
  1744. This.getPointer(), getContext().getRecordType(ClassDecl));
  1745. if (D->isTrivial() && D->isDefaultConstructor()) {
  1746. assert(E->getNumArgs() == 0 && "trivial default ctor with args");
  1747. return;
  1748. }
  1749. // If this is a trivial constructor, just emit what's needed. If this is a
  1750. // union copy constructor, we must emit a memcpy, because the AST does not
  1751. // model that copy.
  1752. if (isMemcpyEquivalentSpecialMember(D)) {
  1753. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1754. const Expr *Arg = E->getArg(0);
  1755. QualType SrcTy = Arg->getType();
  1756. Address Src = EmitLValue(Arg).getAddress();
  1757. QualType DestTy = getContext().getTypeDeclType(ClassDecl);
  1758. EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
  1759. return;
  1760. }
  1761. CallArgList Args;
  1762. // Push the this ptr.
  1763. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1764. // Add the rest of the user-supplied arguments.
  1765. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1766. EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor());
  1767. // Insert any ABI-specific implicit constructor arguments.
  1768. unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
  1769. *this, D, Type, ForVirtualBase, Delegating, Args);
  1770. // Emit the call.
  1771. llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
  1772. const CGFunctionInfo &Info =
  1773. CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
  1774. EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
  1775. // Generate vtable assumptions if we're constructing a complete object
  1776. // with a vtable. We don't do this for base subobjects for two reasons:
  1777. // first, it's incorrect for classes with virtual bases, and second, we're
  1778. // about to overwrite the vptrs anyway.
  1779. // We also have to make sure if we can refer to vtable:
  1780. // - Otherwise we can refer to vtable if it's safe to speculatively emit.
  1781. // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
  1782. // sure that definition of vtable is not hidden,
  1783. // then we are always safe to refer to it.
  1784. // FIXME: It looks like InstCombine is very inefficient on dealing with
  1785. // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
  1786. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1787. ClassDecl->isDynamicClass() && Type != Ctor_Base &&
  1788. CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
  1789. CGM.getCodeGenOpts().StrictVTablePointers)
  1790. EmitVTableAssumptionLoads(ClassDecl, This);
  1791. }
  1792. void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
  1793. llvm::Value *VTableGlobal =
  1794. CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
  1795. if (!VTableGlobal)
  1796. return;
  1797. // We can just use the base offset in the complete class.
  1798. CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
  1799. if (!NonVirtualOffset.isZero())
  1800. This =
  1801. ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
  1802. Vptr.VTableClass, Vptr.NearestVBase);
  1803. llvm::Value *VPtrValue =
  1804. GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
  1805. llvm::Value *Cmp =
  1806. Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
  1807. Builder.CreateAssumption(Cmp);
  1808. }
  1809. void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
  1810. Address This) {
  1811. if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
  1812. for (const VPtr &Vptr : getVTablePointers(ClassDecl))
  1813. EmitVTableAssumptionLoad(Vptr, This);
  1814. }
  1815. void
  1816. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1817. Address This, Address Src,
  1818. const CXXConstructExpr *E) {
  1819. if (isMemcpyEquivalentSpecialMember(D)) {
  1820. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1821. assert(D->isCopyOrMoveConstructor() &&
  1822. "trivial 1-arg ctor not a copy/move ctor");
  1823. EmitAggregateCopyCtor(This, Src,
  1824. getContext().getTypeDeclType(D->getParent()),
  1825. (*E->arg_begin())->getType());
  1826. return;
  1827. }
  1828. llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
  1829. assert(D->isInstance() &&
  1830. "Trying to emit a member call expr on a static method!");
  1831. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1832. CallArgList Args;
  1833. // Push the this ptr.
  1834. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1835. // Push the src ptr.
  1836. QualType QT = *(FPT->param_type_begin());
  1837. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1838. Src = Builder.CreateBitCast(Src, t);
  1839. Args.add(RValue::get(Src.getPointer()), QT);
  1840. // Skip over first argument (Src).
  1841. EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
  1842. /*ParamsToSkip*/ 1);
  1843. EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
  1844. Callee, ReturnValueSlot(), Args, D);
  1845. }
  1846. void
  1847. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1848. CXXCtorType CtorType,
  1849. const FunctionArgList &Args,
  1850. SourceLocation Loc) {
  1851. CallArgList DelegateArgs;
  1852. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1853. assert(I != E && "no parameters to constructor");
  1854. // this
  1855. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1856. ++I;
  1857. // vtt
  1858. if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
  1859. /*ForVirtualBase=*/false,
  1860. /*Delegating=*/true)) {
  1861. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1862. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1863. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  1864. assert(I != E && "cannot skip vtt parameter, already done with args");
  1865. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1866. ++I;
  1867. }
  1868. }
  1869. // Explicit arguments.
  1870. for (; I != E; ++I) {
  1871. const VarDecl *param = *I;
  1872. // FIXME: per-argument source location
  1873. EmitDelegateCallArg(DelegateArgs, param, Loc);
  1874. }
  1875. llvm::Value *Callee =
  1876. CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
  1877. EmitCall(CGM.getTypes()
  1878. .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
  1879. Callee, ReturnValueSlot(), DelegateArgs, Ctor);
  1880. }
  1881. namespace {
  1882. struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
  1883. const CXXDestructorDecl *Dtor;
  1884. Address Addr;
  1885. CXXDtorType Type;
  1886. CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
  1887. CXXDtorType Type)
  1888. : Dtor(D), Addr(Addr), Type(Type) {}
  1889. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1890. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1891. /*Delegating=*/true, Addr);
  1892. }
  1893. };
  1894. } // end anonymous namespace
  1895. void
  1896. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1897. const FunctionArgList &Args) {
  1898. assert(Ctor->isDelegatingConstructor());
  1899. Address ThisPtr = LoadCXXThisAddress();
  1900. AggValueSlot AggSlot =
  1901. AggValueSlot::forAddr(ThisPtr, Qualifiers(),
  1902. AggValueSlot::IsDestructed,
  1903. AggValueSlot::DoesNotNeedGCBarriers,
  1904. AggValueSlot::IsNotAliased);
  1905. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1906. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1907. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1908. CXXDtorType Type =
  1909. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1910. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1911. ClassDecl->getDestructor(),
  1912. ThisPtr, Type);
  1913. }
  1914. }
  1915. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1916. CXXDtorType Type,
  1917. bool ForVirtualBase,
  1918. bool Delegating,
  1919. Address This) {
  1920. CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
  1921. Delegating, This);
  1922. }
  1923. namespace {
  1924. struct CallLocalDtor final : EHScopeStack::Cleanup {
  1925. const CXXDestructorDecl *Dtor;
  1926. Address Addr;
  1927. CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
  1928. : Dtor(D), Addr(Addr) {}
  1929. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1930. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1931. /*ForVirtualBase=*/false,
  1932. /*Delegating=*/false, Addr);
  1933. }
  1934. };
  1935. }
  1936. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1937. Address Addr) {
  1938. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1939. }
  1940. void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
  1941. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1942. if (!ClassDecl) return;
  1943. if (ClassDecl->hasTrivialDestructor()) return;
  1944. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1945. assert(D && D->isUsed() && "destructor not marked as used!");
  1946. PushDestructorCleanup(D, Addr);
  1947. }
  1948. void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
  1949. // Compute the address point.
  1950. llvm::Value *VTableAddressPoint =
  1951. CGM.getCXXABI().getVTableAddressPointInStructor(
  1952. *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
  1953. if (!VTableAddressPoint)
  1954. return;
  1955. // Compute where to store the address point.
  1956. llvm::Value *VirtualOffset = nullptr;
  1957. CharUnits NonVirtualOffset = CharUnits::Zero();
  1958. if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
  1959. // We need to use the virtual base offset offset because the virtual base
  1960. // might have a different offset in the most derived class.
  1961. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
  1962. *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
  1963. NonVirtualOffset = Vptr.OffsetFromNearestVBase;
  1964. } else {
  1965. // We can just use the base offset in the complete class.
  1966. NonVirtualOffset = Vptr.Base.getBaseOffset();
  1967. }
  1968. // Apply the offsets.
  1969. Address VTableField = LoadCXXThisAddress();
  1970. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1971. VTableField = ApplyNonVirtualAndVirtualOffset(
  1972. *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
  1973. Vptr.NearestVBase);
  1974. // Finally, store the address point. Use the same LLVM types as the field to
  1975. // support optimization.
  1976. llvm::Type *VTablePtrTy =
  1977. llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
  1978. ->getPointerTo()
  1979. ->getPointerTo();
  1980. VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
  1981. VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
  1982. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  1983. CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr());
  1984. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1985. CGM.getCodeGenOpts().StrictVTablePointers)
  1986. CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
  1987. }
  1988. CodeGenFunction::VPtrsVector
  1989. CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
  1990. CodeGenFunction::VPtrsVector VPtrsResult;
  1991. VisitedVirtualBasesSetTy VBases;
  1992. getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
  1993. /*NearestVBase=*/nullptr,
  1994. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1995. /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
  1996. VPtrsResult);
  1997. return VPtrsResult;
  1998. }
  1999. void CodeGenFunction::getVTablePointers(BaseSubobject Base,
  2000. const CXXRecordDecl *NearestVBase,
  2001. CharUnits OffsetFromNearestVBase,
  2002. bool BaseIsNonVirtualPrimaryBase,
  2003. const CXXRecordDecl *VTableClass,
  2004. VisitedVirtualBasesSetTy &VBases,
  2005. VPtrsVector &Vptrs) {
  2006. // If this base is a non-virtual primary base the address point has already
  2007. // been set.
  2008. if (!BaseIsNonVirtualPrimaryBase) {
  2009. // Initialize the vtable pointer for this base.
  2010. VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
  2011. Vptrs.push_back(Vptr);
  2012. }
  2013. const CXXRecordDecl *RD = Base.getBase();
  2014. // Traverse bases.
  2015. for (const auto &I : RD->bases()) {
  2016. CXXRecordDecl *BaseDecl
  2017. = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  2018. // Ignore classes without a vtable.
  2019. if (!BaseDecl->isDynamicClass())
  2020. continue;
  2021. CharUnits BaseOffset;
  2022. CharUnits BaseOffsetFromNearestVBase;
  2023. bool BaseDeclIsNonVirtualPrimaryBase;
  2024. if (I.isVirtual()) {
  2025. // Check if we've visited this virtual base before.
  2026. if (!VBases.insert(BaseDecl).second)
  2027. continue;
  2028. const ASTRecordLayout &Layout =
  2029. getContext().getASTRecordLayout(VTableClass);
  2030. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  2031. BaseOffsetFromNearestVBase = CharUnits::Zero();
  2032. BaseDeclIsNonVirtualPrimaryBase = false;
  2033. } else {
  2034. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  2035. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  2036. BaseOffsetFromNearestVBase =
  2037. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  2038. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  2039. }
  2040. getVTablePointers(
  2041. BaseSubobject(BaseDecl, BaseOffset),
  2042. I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
  2043. BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
  2044. }
  2045. }
  2046. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  2047. // Ignore classes without a vtable.
  2048. if (!RD->isDynamicClass())
  2049. return;
  2050. // Initialize the vtable pointers for this class and all of its bases.
  2051. if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
  2052. for (const VPtr &Vptr : getVTablePointers(RD))
  2053. InitializeVTablePointer(Vptr);
  2054. if (RD->getNumVBases())
  2055. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  2056. }
  2057. llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
  2058. llvm::Type *VTableTy,
  2059. const CXXRecordDecl *RD) {
  2060. Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
  2061. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  2062. CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr());
  2063. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2064. CGM.getCodeGenOpts().StrictVTablePointers)
  2065. CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
  2066. return VTable;
  2067. }
  2068. // If a class has a single non-virtual base and does not introduce or override
  2069. // virtual member functions or fields, it will have the same layout as its base.
  2070. // This function returns the least derived such class.
  2071. //
  2072. // Casting an instance of a base class to such a derived class is technically
  2073. // undefined behavior, but it is a relatively common hack for introducing member
  2074. // functions on class instances with specific properties (e.g. llvm::Operator)
  2075. // that works under most compilers and should not have security implications, so
  2076. // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
  2077. static const CXXRecordDecl *
  2078. LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
  2079. if (!RD->field_empty())
  2080. return RD;
  2081. if (RD->getNumVBases() != 0)
  2082. return RD;
  2083. if (RD->getNumBases() != 1)
  2084. return RD;
  2085. for (const CXXMethodDecl *MD : RD->methods()) {
  2086. if (MD->isVirtual()) {
  2087. // Virtual member functions are only ok if they are implicit destructors
  2088. // because the implicit destructor will have the same semantics as the
  2089. // base class's destructor if no fields are added.
  2090. if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
  2091. continue;
  2092. return RD;
  2093. }
  2094. }
  2095. return LeastDerivedClassWithSameLayout(
  2096. RD->bases_begin()->getType()->getAsCXXRecordDecl());
  2097. }
  2098. void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
  2099. llvm::Value *VTable,
  2100. CFITypeCheckKind TCK,
  2101. SourceLocation Loc) {
  2102. const CXXRecordDecl *ClassDecl = MD->getParent();
  2103. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2104. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  2105. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  2106. }
  2107. void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
  2108. llvm::Value *Derived,
  2109. bool MayBeNull,
  2110. CFITypeCheckKind TCK,
  2111. SourceLocation Loc) {
  2112. if (!getLangOpts().CPlusPlus)
  2113. return;
  2114. auto *ClassTy = T->getAs<RecordType>();
  2115. if (!ClassTy)
  2116. return;
  2117. const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
  2118. if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
  2119. return;
  2120. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2121. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  2122. llvm::BasicBlock *ContBlock = nullptr;
  2123. if (MayBeNull) {
  2124. llvm::Value *DerivedNotNull =
  2125. Builder.CreateIsNotNull(Derived, "cast.nonnull");
  2126. llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
  2127. ContBlock = createBasicBlock("cast.cont");
  2128. Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
  2129. EmitBlock(CheckBlock);
  2130. }
  2131. llvm::Value *VTable =
  2132. GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
  2133. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  2134. if (MayBeNull) {
  2135. Builder.CreateBr(ContBlock);
  2136. EmitBlock(ContBlock);
  2137. }
  2138. }
  2139. void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
  2140. llvm::Value *VTable,
  2141. CFITypeCheckKind TCK,
  2142. SourceLocation Loc) {
  2143. if (CGM.IsCFIBlacklistedRecord(RD))
  2144. return;
  2145. SanitizerScope SanScope(this);
  2146. llvm::Metadata *MD =
  2147. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2148. llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  2149. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2150. llvm::Value *BitSetTest =
  2151. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
  2152. {CastedVTable, BitSetName});
  2153. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso) {
  2154. if (auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD)) {
  2155. EmitCfiSlowPathCheck(BitSetTest, TypeId, CastedVTable);
  2156. return;
  2157. }
  2158. }
  2159. SanitizerMask M;
  2160. switch (TCK) {
  2161. case CFITCK_VCall:
  2162. M = SanitizerKind::CFIVCall;
  2163. break;
  2164. case CFITCK_NVCall:
  2165. M = SanitizerKind::CFINVCall;
  2166. break;
  2167. case CFITCK_DerivedCast:
  2168. M = SanitizerKind::CFIDerivedCast;
  2169. break;
  2170. case CFITCK_UnrelatedCast:
  2171. M = SanitizerKind::CFIUnrelatedCast;
  2172. break;
  2173. }
  2174. llvm::Constant *StaticData[] = {
  2175. EmitCheckSourceLocation(Loc),
  2176. EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
  2177. llvm::ConstantInt::get(Int8Ty, TCK),
  2178. };
  2179. EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
  2180. CastedVTable);
  2181. }
  2182. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  2183. // quite what we want.
  2184. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  2185. while (true) {
  2186. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  2187. E = PE->getSubExpr();
  2188. continue;
  2189. }
  2190. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  2191. if (CE->getCastKind() == CK_NoOp) {
  2192. E = CE->getSubExpr();
  2193. continue;
  2194. }
  2195. }
  2196. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  2197. if (UO->getOpcode() == UO_Extension) {
  2198. E = UO->getSubExpr();
  2199. continue;
  2200. }
  2201. }
  2202. return E;
  2203. }
  2204. }
  2205. bool
  2206. CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
  2207. const CXXMethodDecl *MD) {
  2208. // When building with -fapple-kext, all calls must go through the vtable since
  2209. // the kernel linker can do runtime patching of vtables.
  2210. if (getLangOpts().AppleKext)
  2211. return false;
  2212. // If the most derived class is marked final, we know that no subclass can
  2213. // override this member function and so we can devirtualize it. For example:
  2214. //
  2215. // struct A { virtual void f(); }
  2216. // struct B final : A { };
  2217. //
  2218. // void f(B *b) {
  2219. // b->f();
  2220. // }
  2221. //
  2222. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  2223. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  2224. return true;
  2225. // If the member function is marked 'final', we know that it can't be
  2226. // overridden and can therefore devirtualize it.
  2227. if (MD->hasAttr<FinalAttr>())
  2228. return true;
  2229. // Similarly, if the class itself is marked 'final' it can't be overridden
  2230. // and we can therefore devirtualize the member function call.
  2231. if (MD->getParent()->hasAttr<FinalAttr>())
  2232. return true;
  2233. Base = skipNoOpCastsAndParens(Base);
  2234. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  2235. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  2236. // This is a record decl. We know the type and can devirtualize it.
  2237. return VD->getType()->isRecordType();
  2238. }
  2239. return false;
  2240. }
  2241. // We can devirtualize calls on an object accessed by a class member access
  2242. // expression, since by C++11 [basic.life]p6 we know that it can't refer to
  2243. // a derived class object constructed in the same location.
  2244. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
  2245. if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
  2246. return VD->getType()->isRecordType();
  2247. // We can always devirtualize calls on temporary object expressions.
  2248. if (isa<CXXConstructExpr>(Base))
  2249. return true;
  2250. // And calls on bound temporaries.
  2251. if (isa<CXXBindTemporaryExpr>(Base))
  2252. return true;
  2253. // Check if this is a call expr that returns a record type.
  2254. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  2255. return CE->getCallReturnType(getContext())->isRecordType();
  2256. // We can't devirtualize the call.
  2257. return false;
  2258. }
  2259. void CodeGenFunction::EmitForwardingCallToLambda(
  2260. const CXXMethodDecl *callOperator,
  2261. CallArgList &callArgs) {
  2262. // Get the address of the call operator.
  2263. const CGFunctionInfo &calleeFnInfo =
  2264. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  2265. llvm::Value *callee =
  2266. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  2267. CGM.getTypes().GetFunctionType(calleeFnInfo));
  2268. // Prepare the return slot.
  2269. const FunctionProtoType *FPT =
  2270. callOperator->getType()->castAs<FunctionProtoType>();
  2271. QualType resultType = FPT->getReturnType();
  2272. ReturnValueSlot returnSlot;
  2273. if (!resultType->isVoidType() &&
  2274. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2275. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  2276. returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
  2277. // We don't need to separately arrange the call arguments because
  2278. // the call can't be variadic anyway --- it's impossible to forward
  2279. // variadic arguments.
  2280. // Now emit our call.
  2281. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
  2282. callArgs, callOperator);
  2283. // If necessary, copy the returned value into the slot.
  2284. if (!resultType->isVoidType() && returnSlot.isNull())
  2285. EmitReturnOfRValue(RV, resultType);
  2286. else
  2287. EmitBranchThroughCleanup(ReturnBlock);
  2288. }
  2289. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  2290. const BlockDecl *BD = BlockInfo->getBlockDecl();
  2291. const VarDecl *variable = BD->capture_begin()->getVariable();
  2292. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  2293. // Start building arguments for forwarding call
  2294. CallArgList CallArgs;
  2295. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2296. Address ThisPtr = GetAddrOfBlockDecl(variable, false);
  2297. CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
  2298. // Add the rest of the parameters.
  2299. for (auto param : BD->params())
  2300. EmitDelegateCallArg(CallArgs, param, param->getLocStart());
  2301. assert(!Lambda->isGenericLambda() &&
  2302. "generic lambda interconversion to block not implemented");
  2303. EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
  2304. }
  2305. void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
  2306. if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
  2307. // FIXME: Making this work correctly is nasty because it requires either
  2308. // cloning the body of the call operator or making the call operator forward.
  2309. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  2310. return;
  2311. }
  2312. EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
  2313. }
  2314. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  2315. const CXXRecordDecl *Lambda = MD->getParent();
  2316. // Start building arguments for forwarding call
  2317. CallArgList CallArgs;
  2318. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2319. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  2320. CallArgs.add(RValue::get(ThisPtr), ThisType);
  2321. // Add the rest of the parameters.
  2322. for (auto Param : MD->params())
  2323. EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
  2324. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2325. // For a generic lambda, find the corresponding call operator specialization
  2326. // to which the call to the static-invoker shall be forwarded.
  2327. if (Lambda->isGenericLambda()) {
  2328. assert(MD->isFunctionTemplateSpecialization());
  2329. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  2330. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  2331. void *InsertPos = nullptr;
  2332. FunctionDecl *CorrespondingCallOpSpecialization =
  2333. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  2334. assert(CorrespondingCallOpSpecialization);
  2335. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  2336. }
  2337. EmitForwardingCallToLambda(CallOp, CallArgs);
  2338. }
  2339. void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
  2340. if (MD->isVariadic()) {
  2341. // FIXME: Making this work correctly is nasty because it requires either
  2342. // cloning the body of the call operator or making the call operator forward.
  2343. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  2344. return;
  2345. }
  2346. EmitLambdaDelegatingInvokeBody(MD);
  2347. }