CGClass.cpp 100 KB

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