CGDecl.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "llvm/GlobalVariable.h"
  25. #include "llvm/Intrinsics.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Type.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. void CodeGenFunction::EmitDecl(const Decl &D) {
  31. switch (D.getKind()) {
  32. case Decl::TranslationUnit:
  33. case Decl::Namespace:
  34. case Decl::UnresolvedUsingTypename:
  35. case Decl::ClassTemplateSpecialization:
  36. case Decl::ClassTemplatePartialSpecialization:
  37. case Decl::TemplateTypeParm:
  38. case Decl::UnresolvedUsingValue:
  39. case Decl::NonTypeTemplateParm:
  40. case Decl::CXXMethod:
  41. case Decl::CXXConstructor:
  42. case Decl::CXXDestructor:
  43. case Decl::CXXConversion:
  44. case Decl::Field:
  45. case Decl::IndirectField:
  46. case Decl::ObjCIvar:
  47. case Decl::ObjCAtDefsField:
  48. case Decl::ParmVar:
  49. case Decl::ImplicitParam:
  50. case Decl::ClassTemplate:
  51. case Decl::FunctionTemplate:
  52. case Decl::TypeAliasTemplate:
  53. case Decl::TemplateTemplateParm:
  54. case Decl::ObjCMethod:
  55. case Decl::ObjCCategory:
  56. case Decl::ObjCProtocol:
  57. case Decl::ObjCInterface:
  58. case Decl::ObjCCategoryImpl:
  59. case Decl::ObjCImplementation:
  60. case Decl::ObjCProperty:
  61. case Decl::ObjCCompatibleAlias:
  62. case Decl::AccessSpec:
  63. case Decl::LinkageSpec:
  64. case Decl::ObjCPropertyImpl:
  65. case Decl::FileScopeAsm:
  66. case Decl::Friend:
  67. case Decl::FriendTemplate:
  68. case Decl::Block:
  69. case Decl::ClassScopeFunctionSpecialization:
  70. llvm_unreachable("Declaration should not be in declstmts!");
  71. case Decl::Function: // void X();
  72. case Decl::Record: // struct/union/class X;
  73. case Decl::Enum: // enum X;
  74. case Decl::EnumConstant: // enum ? { X = ? }
  75. case Decl::CXXRecord: // struct/union/class X; [C++]
  76. case Decl::Using: // using X; [C++]
  77. case Decl::UsingShadow:
  78. case Decl::UsingDirective: // using namespace X; [C++]
  79. case Decl::NamespaceAlias:
  80. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  81. case Decl::Label: // __label__ x;
  82. case Decl::Import:
  83. // None of these decls require codegen support.
  84. return;
  85. case Decl::Var: {
  86. const VarDecl &VD = cast<VarDecl>(D);
  87. assert(VD.isLocalVarDecl() &&
  88. "Should not see file-scope variables inside a function!");
  89. return EmitVarDecl(VD);
  90. }
  91. case Decl::Typedef: // typedef int X;
  92. case Decl::TypeAlias: { // using X = int; [C++0x]
  93. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  94. QualType Ty = TD.getUnderlyingType();
  95. if (Ty->isVariablyModifiedType())
  96. EmitVariablyModifiedType(Ty);
  97. }
  98. }
  99. }
  100. /// EmitVarDecl - This method handles emission of any variable declaration
  101. /// inside a function, including static vars etc.
  102. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  103. switch (D.getStorageClass()) {
  104. case SC_None:
  105. case SC_Auto:
  106. case SC_Register:
  107. return EmitAutoVarDecl(D);
  108. case SC_Static: {
  109. llvm::GlobalValue::LinkageTypes Linkage =
  110. llvm::GlobalValue::InternalLinkage;
  111. // If the function definition has some sort of weak linkage, its
  112. // static variables should also be weak so that they get properly
  113. // uniqued. We can't do this in C, though, because there's no
  114. // standard way to agree on which variables are the same (i.e.
  115. // there's no mangling).
  116. if (getContext().getLangOptions().CPlusPlus)
  117. if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
  118. Linkage = CurFn->getLinkage();
  119. return EmitStaticVarDecl(D, Linkage);
  120. }
  121. case SC_Extern:
  122. case SC_PrivateExtern:
  123. // Don't emit it now, allow it to be emitted lazily on its first use.
  124. return;
  125. case SC_OpenCLWorkGroupLocal:
  126. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  127. }
  128. llvm_unreachable("Unknown storage class");
  129. }
  130. static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
  131. const char *Separator) {
  132. CodeGenModule &CGM = CGF.CGM;
  133. if (CGF.getContext().getLangOptions().CPlusPlus) {
  134. StringRef Name = CGM.getMangledName(&D);
  135. return Name.str();
  136. }
  137. std::string ContextName;
  138. if (!CGF.CurFuncDecl) {
  139. // Better be in a block declared in global scope.
  140. const NamedDecl *ND = cast<NamedDecl>(&D);
  141. const DeclContext *DC = ND->getDeclContext();
  142. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  143. MangleBuffer Name;
  144. CGM.getBlockMangledName(GlobalDecl(), Name, BD);
  145. ContextName = Name.getString();
  146. }
  147. else
  148. llvm_unreachable("Unknown context for block static var decl");
  149. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
  150. StringRef Name = CGM.getMangledName(FD);
  151. ContextName = Name.str();
  152. } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
  153. ContextName = CGF.CurFn->getName();
  154. else
  155. llvm_unreachable("Unknown context for static var decl");
  156. return ContextName + Separator + D.getNameAsString();
  157. }
  158. llvm::GlobalVariable *
  159. CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
  160. const char *Separator,
  161. llvm::GlobalValue::LinkageTypes Linkage) {
  162. QualType Ty = D.getType();
  163. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  164. // Use the label if the variable is renamed with the asm-label extension.
  165. std::string Name;
  166. if (D.hasAttr<AsmLabelAttr>())
  167. Name = CGM.getMangledName(&D);
  168. else
  169. Name = GetStaticDeclName(*this, D, Separator);
  170. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
  171. llvm::GlobalVariable *GV =
  172. new llvm::GlobalVariable(CGM.getModule(), LTy,
  173. Ty.isConstant(getContext()), Linkage,
  174. CGM.EmitNullConstant(D.getType()), Name, 0,
  175. D.isThreadSpecified(),
  176. CGM.getContext().getTargetAddressSpace(Ty));
  177. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  178. if (Linkage != llvm::GlobalValue::InternalLinkage)
  179. GV->setVisibility(CurFn->getVisibility());
  180. return GV;
  181. }
  182. /// hasNontrivialDestruction - Determine whether a type's destruction is
  183. /// non-trivial. If so, and the variable uses static initialization, we must
  184. /// register its destructor to run on exit.
  185. static bool hasNontrivialDestruction(QualType T) {
  186. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  187. return RD && !RD->hasTrivialDestructor();
  188. }
  189. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  190. /// global variable that has already been created for it. If the initializer
  191. /// has a different type than GV does, this may free GV and return a different
  192. /// one. Otherwise it just returns GV.
  193. llvm::GlobalVariable *
  194. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  195. llvm::GlobalVariable *GV) {
  196. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  197. // If constant emission failed, then this should be a C++ static
  198. // initializer.
  199. if (!Init) {
  200. if (!getContext().getLangOptions().CPlusPlus)
  201. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  202. else if (Builder.GetInsertBlock()) {
  203. // Since we have a static initializer, this global variable can't
  204. // be constant.
  205. GV->setConstant(false);
  206. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  207. }
  208. return GV;
  209. }
  210. // The initializer may differ in type from the global. Rewrite
  211. // the global to match the initializer. (We have to do this
  212. // because some types, like unions, can't be completely represented
  213. // in the LLVM type system.)
  214. if (GV->getType()->getElementType() != Init->getType()) {
  215. llvm::GlobalVariable *OldGV = GV;
  216. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  217. OldGV->isConstant(),
  218. OldGV->getLinkage(), Init, "",
  219. /*InsertBefore*/ OldGV,
  220. D.isThreadSpecified(),
  221. CGM.getContext().getTargetAddressSpace(D.getType()));
  222. GV->setVisibility(OldGV->getVisibility());
  223. // Steal the name of the old global
  224. GV->takeName(OldGV);
  225. // Replace all uses of the old global with the new global
  226. llvm::Constant *NewPtrForOldDecl =
  227. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  228. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  229. // Erase the old global, since it is no longer used.
  230. OldGV->eraseFromParent();
  231. }
  232. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  233. GV->setInitializer(Init);
  234. if (hasNontrivialDestruction(D.getType())) {
  235. // We have a constant initializer, but a nontrivial destructor. We still
  236. // need to perform a guarded "initialization" in order to register the
  237. // destructor.
  238. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  239. }
  240. return GV;
  241. }
  242. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  243. llvm::GlobalValue::LinkageTypes Linkage) {
  244. llvm::Value *&DMEntry = LocalDeclMap[&D];
  245. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  246. llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
  247. // Store into LocalDeclMap before generating initializer to handle
  248. // circular references.
  249. DMEntry = GV;
  250. // We can't have a VLA here, but we can have a pointer to a VLA,
  251. // even though that doesn't really make any sense.
  252. // Make sure to evaluate VLA bounds now so that we have them for later.
  253. if (D.getType()->isVariablyModifiedType())
  254. EmitVariablyModifiedType(D.getType());
  255. // Local static block variables must be treated as globals as they may be
  256. // referenced in their RHS initializer block-literal expresion.
  257. CGM.setStaticLocalDeclAddress(&D, GV);
  258. // If this value has an initializer, emit it.
  259. if (D.getInit())
  260. GV = AddInitializerToStaticVarDecl(D, GV);
  261. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  262. if (D.hasAttr<AnnotateAttr>())
  263. CGM.AddGlobalAnnotations(&D, GV);
  264. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  265. GV->setSection(SA->getName());
  266. if (D.hasAttr<UsedAttr>())
  267. CGM.AddUsedGlobal(GV);
  268. // We may have to cast the constant because of the initializer
  269. // mismatch above.
  270. //
  271. // FIXME: It is really dangerous to store this in the map; if anyone
  272. // RAUW's the GV uses of this constant will be invalid.
  273. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
  274. llvm::Type *LPtrTy =
  275. LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
  276. DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
  277. // Emit global variable debug descriptor for static vars.
  278. CGDebugInfo *DI = getDebugInfo();
  279. if (DI) {
  280. DI->setLocation(D.getLocation());
  281. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
  282. }
  283. }
  284. namespace {
  285. struct DestroyObject : EHScopeStack::Cleanup {
  286. DestroyObject(llvm::Value *addr, QualType type,
  287. CodeGenFunction::Destroyer *destroyer,
  288. bool useEHCleanupForArray)
  289. : addr(addr), type(type), destroyer(destroyer),
  290. useEHCleanupForArray(useEHCleanupForArray) {}
  291. llvm::Value *addr;
  292. QualType type;
  293. CodeGenFunction::Destroyer *destroyer;
  294. bool useEHCleanupForArray;
  295. void Emit(CodeGenFunction &CGF, Flags flags) {
  296. // Don't use an EH cleanup recursively from an EH cleanup.
  297. bool useEHCleanupForArray =
  298. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  299. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  300. }
  301. };
  302. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  303. DestroyNRVOVariable(llvm::Value *addr,
  304. const CXXDestructorDecl *Dtor,
  305. llvm::Value *NRVOFlag)
  306. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  307. const CXXDestructorDecl *Dtor;
  308. llvm::Value *NRVOFlag;
  309. llvm::Value *Loc;
  310. void Emit(CodeGenFunction &CGF, Flags flags) {
  311. // Along the exceptions path we always execute the dtor.
  312. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  313. llvm::BasicBlock *SkipDtorBB = 0;
  314. if (NRVO) {
  315. // If we exited via NRVO, we skip the destructor call.
  316. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  317. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  318. llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
  319. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  320. CGF.EmitBlock(RunDtorBB);
  321. }
  322. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  323. /*ForVirtualBase=*/false, Loc);
  324. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  325. }
  326. };
  327. struct CallStackRestore : EHScopeStack::Cleanup {
  328. llvm::Value *Stack;
  329. CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
  330. void Emit(CodeGenFunction &CGF, Flags flags) {
  331. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  332. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  333. CGF.Builder.CreateCall(F, V);
  334. }
  335. };
  336. struct ExtendGCLifetime : EHScopeStack::Cleanup {
  337. const VarDecl &Var;
  338. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  339. void Emit(CodeGenFunction &CGF, Flags flags) {
  340. // Compute the address of the local variable, in case it's a
  341. // byref or something.
  342. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  343. SourceLocation());
  344. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
  345. CGF.EmitExtendGCLifetime(value);
  346. }
  347. };
  348. struct CallCleanupFunction : EHScopeStack::Cleanup {
  349. llvm::Constant *CleanupFn;
  350. const CGFunctionInfo &FnInfo;
  351. const VarDecl &Var;
  352. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  353. const VarDecl *Var)
  354. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  355. void Emit(CodeGenFunction &CGF, Flags flags) {
  356. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  357. SourceLocation());
  358. // Compute the address of the local variable, in case it's a byref
  359. // or something.
  360. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
  361. // In some cases, the type of the function argument will be different from
  362. // the type of the pointer. An example of this is
  363. // void f(void* arg);
  364. // __attribute__((cleanup(f))) void *g;
  365. //
  366. // To fix this we insert a bitcast here.
  367. QualType ArgTy = FnInfo.arg_begin()->type;
  368. llvm::Value *Arg =
  369. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  370. CallArgList Args;
  371. Args.add(RValue::get(Arg),
  372. CGF.getContext().getPointerType(Var.getType()));
  373. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  374. }
  375. };
  376. }
  377. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  378. /// variable with lifetime.
  379. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  380. llvm::Value *addr,
  381. Qualifiers::ObjCLifetime lifetime) {
  382. switch (lifetime) {
  383. case Qualifiers::OCL_None:
  384. llvm_unreachable("present but none");
  385. case Qualifiers::OCL_ExplicitNone:
  386. // nothing to do
  387. break;
  388. case Qualifiers::OCL_Strong: {
  389. CodeGenFunction::Destroyer *destroyer =
  390. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  391. ? CodeGenFunction::destroyARCStrongPrecise
  392. : CodeGenFunction::destroyARCStrongImprecise);
  393. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  394. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  395. cleanupKind & EHCleanup);
  396. break;
  397. }
  398. case Qualifiers::OCL_Autoreleasing:
  399. // nothing to do
  400. break;
  401. case Qualifiers::OCL_Weak:
  402. // __weak objects always get EH cleanups; otherwise, exceptions
  403. // could cause really nasty crashes instead of mere leaks.
  404. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  405. CodeGenFunction::destroyARCWeak,
  406. /*useEHCleanup*/ true);
  407. break;
  408. }
  409. }
  410. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  411. if (const Expr *e = dyn_cast<Expr>(s)) {
  412. // Skip the most common kinds of expressions that make
  413. // hierarchy-walking expensive.
  414. s = e = e->IgnoreParenCasts();
  415. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  416. return (ref->getDecl() == &var);
  417. }
  418. for (Stmt::const_child_range children = s->children(); children; ++children)
  419. // children might be null; as in missing decl or conditional of an if-stmt.
  420. if ((*children) && isAccessedBy(var, *children))
  421. return true;
  422. return false;
  423. }
  424. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  425. if (!decl) return false;
  426. if (!isa<VarDecl>(decl)) return false;
  427. const VarDecl *var = cast<VarDecl>(decl);
  428. return isAccessedBy(*var, e);
  429. }
  430. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  431. LValue &lvalue,
  432. const VarDecl *var) {
  433. lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
  434. }
  435. void CodeGenFunction::EmitScalarInit(const Expr *init,
  436. const ValueDecl *D,
  437. LValue lvalue,
  438. bool capturedByInit) {
  439. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  440. if (!lifetime) {
  441. llvm::Value *value = EmitScalarExpr(init);
  442. if (capturedByInit)
  443. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  444. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  445. return;
  446. }
  447. // If we're emitting a value with lifetime, we have to do the
  448. // initialization *before* we leave the cleanup scopes.
  449. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  450. enterFullExpression(ewc);
  451. init = ewc->getSubExpr();
  452. }
  453. CodeGenFunction::RunCleanupsScope Scope(*this);
  454. // We have to maintain the illusion that the variable is
  455. // zero-initialized. If the variable might be accessed in its
  456. // initializer, zero-initialize before running the initializer, then
  457. // actually perform the initialization with an assign.
  458. bool accessedByInit = false;
  459. if (lifetime != Qualifiers::OCL_ExplicitNone)
  460. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  461. if (accessedByInit) {
  462. LValue tempLV = lvalue;
  463. // Drill down to the __block object if necessary.
  464. if (capturedByInit) {
  465. // We can use a simple GEP for this because it can't have been
  466. // moved yet.
  467. tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
  468. getByRefValueLLVMField(cast<VarDecl>(D))));
  469. }
  470. llvm::PointerType *ty
  471. = cast<llvm::PointerType>(tempLV.getAddress()->getType());
  472. ty = cast<llvm::PointerType>(ty->getElementType());
  473. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  474. // If __weak, we want to use a barrier under certain conditions.
  475. if (lifetime == Qualifiers::OCL_Weak)
  476. EmitARCInitWeak(tempLV.getAddress(), zero);
  477. // Otherwise just do a simple store.
  478. else
  479. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  480. }
  481. // Emit the initializer.
  482. llvm::Value *value = 0;
  483. switch (lifetime) {
  484. case Qualifiers::OCL_None:
  485. llvm_unreachable("present but none");
  486. case Qualifiers::OCL_ExplicitNone:
  487. // nothing to do
  488. value = EmitScalarExpr(init);
  489. break;
  490. case Qualifiers::OCL_Strong: {
  491. value = EmitARCRetainScalarExpr(init);
  492. break;
  493. }
  494. case Qualifiers::OCL_Weak: {
  495. // No way to optimize a producing initializer into this. It's not
  496. // worth optimizing for, because the value will immediately
  497. // disappear in the common case.
  498. value = EmitScalarExpr(init);
  499. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  500. if (accessedByInit)
  501. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  502. else
  503. EmitARCInitWeak(lvalue.getAddress(), value);
  504. return;
  505. }
  506. case Qualifiers::OCL_Autoreleasing:
  507. value = EmitARCRetainAutoreleaseScalarExpr(init);
  508. break;
  509. }
  510. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  511. // If the variable might have been accessed by its initializer, we
  512. // might have to initialize with a barrier. We have to do this for
  513. // both __weak and __strong, but __weak got filtered out above.
  514. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  515. llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
  516. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  517. EmitARCRelease(oldValue, /*precise*/ false);
  518. return;
  519. }
  520. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  521. }
  522. /// EmitScalarInit - Initialize the given lvalue with the given object.
  523. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  524. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  525. if (!lifetime)
  526. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  527. switch (lifetime) {
  528. case Qualifiers::OCL_None:
  529. llvm_unreachable("present but none");
  530. case Qualifiers::OCL_ExplicitNone:
  531. // nothing to do
  532. break;
  533. case Qualifiers::OCL_Strong:
  534. init = EmitARCRetain(lvalue.getType(), init);
  535. break;
  536. case Qualifiers::OCL_Weak:
  537. // Initialize and then skip the primitive store.
  538. EmitARCInitWeak(lvalue.getAddress(), init);
  539. return;
  540. case Qualifiers::OCL_Autoreleasing:
  541. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  542. break;
  543. }
  544. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  545. }
  546. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  547. /// non-zero parts of the specified initializer with equal or fewer than
  548. /// NumStores scalar stores.
  549. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  550. unsigned &NumStores) {
  551. // Zero and Undef never requires any extra stores.
  552. if (isa<llvm::ConstantAggregateZero>(Init) ||
  553. isa<llvm::ConstantPointerNull>(Init) ||
  554. isa<llvm::UndefValue>(Init))
  555. return true;
  556. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  557. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  558. isa<llvm::ConstantExpr>(Init))
  559. return Init->isNullValue() || NumStores--;
  560. // See if we can emit each element.
  561. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  562. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  563. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  564. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  565. return false;
  566. }
  567. return true;
  568. }
  569. if (llvm::ConstantDataSequential *CDS =
  570. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  571. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  572. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  573. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  574. return false;
  575. }
  576. return true;
  577. }
  578. // Anything else is hard and scary.
  579. return false;
  580. }
  581. /// emitStoresForInitAfterMemset - For inits that
  582. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  583. /// stores that would be required.
  584. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  585. bool isVolatile, CGBuilderTy &Builder) {
  586. // Zero doesn't require a store.
  587. if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
  588. return;
  589. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  590. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  591. isa<llvm::ConstantExpr>(Init)) {
  592. Builder.CreateStore(Init, Loc, isVolatile);
  593. return;
  594. }
  595. if (llvm::ConstantDataSequential *CDS =
  596. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  597. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  598. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  599. // Get a pointer to the element and emit it.
  600. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  601. isVolatile, Builder);
  602. }
  603. return;
  604. }
  605. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  606. "Unknown value type!");
  607. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  608. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  609. // Get a pointer to the element and emit it.
  610. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  611. isVolatile, Builder);
  612. }
  613. }
  614. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  615. /// plus some stores to initialize a local variable instead of using a memcpy
  616. /// from a constant global. It is beneficial to use memset if the global is all
  617. /// zeros, or mostly zeros and large.
  618. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  619. uint64_t GlobalSize) {
  620. // If a global is all zeros, always use a memset.
  621. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  622. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  623. // do it if it will require 6 or fewer scalar stores.
  624. // TODO: Should budget depends on the size? Avoiding a large global warrants
  625. // plopping in more stores.
  626. unsigned StoreBudget = 6;
  627. uint64_t SizeLimit = 32;
  628. return GlobalSize > SizeLimit &&
  629. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  630. }
  631. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  632. /// variable declaration with auto, register, or no storage class specifier.
  633. /// These turn into simple stack objects, or GlobalValues depending on target.
  634. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  635. AutoVarEmission emission = EmitAutoVarAlloca(D);
  636. EmitAutoVarInit(emission);
  637. EmitAutoVarCleanups(emission);
  638. }
  639. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  640. /// local variable. Does not emit initalization or destruction.
  641. CodeGenFunction::AutoVarEmission
  642. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  643. QualType Ty = D.getType();
  644. AutoVarEmission emission(D);
  645. bool isByRef = D.hasAttr<BlocksAttr>();
  646. emission.IsByRef = isByRef;
  647. CharUnits alignment = getContext().getDeclAlign(&D);
  648. emission.Alignment = alignment;
  649. // If the type is variably-modified, emit all the VLA sizes for it.
  650. if (Ty->isVariablyModifiedType())
  651. EmitVariablyModifiedType(Ty);
  652. llvm::Value *DeclPtr;
  653. if (Ty->isConstantSizeType()) {
  654. if (!Target.useGlobalsForAutomaticVariables()) {
  655. bool NRVO = getContext().getLangOptions().ElideConstructors &&
  656. D.isNRVOVariable();
  657. // If this value is a POD array or struct with a statically
  658. // determinable constant initializer, there are optimizations we can do.
  659. //
  660. // TODO: We should constant-evaluate the initializer of any variable,
  661. // as long as it is initialized by a constant expression. Currently,
  662. // isConstantInitializer produces wrong answers for structs with
  663. // reference or bitfield members, and a few other cases, and checking
  664. // for POD-ness protects us from some of these.
  665. if (D.getInit() &&
  666. (Ty->isArrayType() || Ty->isRecordType()) &&
  667. (Ty.isPODType(getContext()) ||
  668. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  669. D.getInit()->isConstantInitializer(getContext(), false)) {
  670. // If the variable's a const type, and it's neither an NRVO
  671. // candidate nor a __block variable and has no mutable members,
  672. // emit it as a global instead.
  673. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  674. CGM.isTypeConstant(Ty, true)) {
  675. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  676. emission.Address = 0; // signal this condition to later callbacks
  677. assert(emission.wasEmittedAsGlobal());
  678. return emission;
  679. }
  680. // Otherwise, tell the initialization code that we're in this case.
  681. emission.IsConstantAggregate = true;
  682. }
  683. // A normal fixed sized variable becomes an alloca in the entry block,
  684. // unless it's an NRVO variable.
  685. llvm::Type *LTy = ConvertTypeForMem(Ty);
  686. if (NRVO) {
  687. // The named return value optimization: allocate this variable in the
  688. // return slot, so that we can elide the copy when returning this
  689. // variable (C++0x [class.copy]p34).
  690. DeclPtr = ReturnValue;
  691. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  692. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  693. // Create a flag that is used to indicate when the NRVO was applied
  694. // to this variable. Set it to zero to indicate that NRVO was not
  695. // applied.
  696. llvm::Value *Zero = Builder.getFalse();
  697. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  698. EnsureInsertPoint();
  699. Builder.CreateStore(Zero, NRVOFlag);
  700. // Record the NRVO flag for this variable.
  701. NRVOFlags[&D] = NRVOFlag;
  702. emission.NRVOFlag = NRVOFlag;
  703. }
  704. }
  705. } else {
  706. if (isByRef)
  707. LTy = BuildByRefType(&D);
  708. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  709. Alloc->setName(D.getName());
  710. CharUnits allocaAlignment = alignment;
  711. if (isByRef)
  712. allocaAlignment = std::max(allocaAlignment,
  713. getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
  714. Alloc->setAlignment(allocaAlignment.getQuantity());
  715. DeclPtr = Alloc;
  716. }
  717. } else {
  718. // Targets that don't support recursion emit locals as globals.
  719. const char *Class =
  720. D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
  721. DeclPtr = CreateStaticVarDecl(D, Class,
  722. llvm::GlobalValue::InternalLinkage);
  723. }
  724. } else {
  725. EnsureInsertPoint();
  726. if (!DidCallStackSave) {
  727. // Save the stack.
  728. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  729. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  730. llvm::Value *V = Builder.CreateCall(F);
  731. Builder.CreateStore(V, Stack);
  732. DidCallStackSave = true;
  733. // Push a cleanup block and restore the stack there.
  734. // FIXME: in general circumstances, this should be an EH cleanup.
  735. EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
  736. }
  737. llvm::Value *elementCount;
  738. QualType elementType;
  739. llvm::tie(elementCount, elementType) = getVLASize(Ty);
  740. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  741. // Allocate memory for the array.
  742. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  743. vla->setAlignment(alignment.getQuantity());
  744. DeclPtr = vla;
  745. }
  746. llvm::Value *&DMEntry = LocalDeclMap[&D];
  747. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  748. DMEntry = DeclPtr;
  749. emission.Address = DeclPtr;
  750. // Emit debug info for local var declaration.
  751. if (HaveInsertPoint())
  752. if (CGDebugInfo *DI = getDebugInfo()) {
  753. DI->setLocation(D.getLocation());
  754. if (Target.useGlobalsForAutomaticVariables()) {
  755. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
  756. } else
  757. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  758. }
  759. if (D.hasAttr<AnnotateAttr>())
  760. EmitVarAnnotations(&D, emission.Address);
  761. return emission;
  762. }
  763. /// Determines whether the given __block variable is potentially
  764. /// captured by the given expression.
  765. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  766. // Skip the most common kinds of expressions that make
  767. // hierarchy-walking expensive.
  768. e = e->IgnoreParenCasts();
  769. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  770. const BlockDecl *block = be->getBlockDecl();
  771. for (BlockDecl::capture_const_iterator i = block->capture_begin(),
  772. e = block->capture_end(); i != e; ++i) {
  773. if (i->getVariable() == &var)
  774. return true;
  775. }
  776. // No need to walk into the subexpressions.
  777. return false;
  778. }
  779. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  780. const CompoundStmt *CS = SE->getSubStmt();
  781. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  782. BE = CS->body_end(); BI != BE; ++BI)
  783. if (Expr *E = dyn_cast<Expr>((*BI))) {
  784. if (isCapturedBy(var, E))
  785. return true;
  786. }
  787. else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
  788. // special case declarations
  789. for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
  790. I != E; ++I) {
  791. if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
  792. Expr *Init = VD->getInit();
  793. if (Init && isCapturedBy(var, Init))
  794. return true;
  795. }
  796. }
  797. }
  798. else
  799. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  800. // Later, provide code to poke into statements for capture analysis.
  801. return true;
  802. return false;
  803. }
  804. for (Stmt::const_child_range children = e->children(); children; ++children)
  805. if (isCapturedBy(var, cast<Expr>(*children)))
  806. return true;
  807. return false;
  808. }
  809. /// \brief Determine whether the given initializer is trivial in the sense
  810. /// that it requires no code to be generated.
  811. static bool isTrivialInitializer(const Expr *Init) {
  812. if (!Init)
  813. return true;
  814. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  815. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  816. if (Constructor->isTrivial() &&
  817. Constructor->isDefaultConstructor() &&
  818. !Construct->requiresZeroInitialization())
  819. return true;
  820. return false;
  821. }
  822. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  823. assert(emission.Variable && "emission was not valid!");
  824. // If this was emitted as a global constant, we're done.
  825. if (emission.wasEmittedAsGlobal()) return;
  826. const VarDecl &D = *emission.Variable;
  827. QualType type = D.getType();
  828. // If this local has an initializer, emit it now.
  829. const Expr *Init = D.getInit();
  830. // If we are at an unreachable point, we don't need to emit the initializer
  831. // unless it contains a label.
  832. if (!HaveInsertPoint()) {
  833. if (!Init || !ContainsLabel(Init)) return;
  834. EnsureInsertPoint();
  835. }
  836. // Initialize the structure of a __block variable.
  837. if (emission.IsByRef)
  838. emitByrefStructureInit(emission);
  839. if (isTrivialInitializer(Init))
  840. return;
  841. CharUnits alignment = emission.Alignment;
  842. // Check whether this is a byref variable that's potentially
  843. // captured and moved by its own initializer. If so, we'll need to
  844. // emit the initializer first, then copy into the variable.
  845. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  846. llvm::Value *Loc =
  847. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  848. llvm::Constant *constant = 0;
  849. if (emission.IsConstantAggregate) {
  850. assert(!capturedByInit && "constant init contains a capturing block?");
  851. constant = CGM.EmitConstantInit(D, this);
  852. }
  853. if (!constant) {
  854. LValue lv = MakeAddrLValue(Loc, type, alignment);
  855. lv.setNonGC(true);
  856. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  857. }
  858. // If this is a simple aggregate initialization, we can optimize it
  859. // in various ways.
  860. bool isVolatile = type.isVolatileQualified();
  861. llvm::Value *SizeVal =
  862. llvm::ConstantInt::get(IntPtrTy,
  863. getContext().getTypeSizeInChars(type).getQuantity());
  864. llvm::Type *BP = Int8PtrTy;
  865. if (Loc->getType() != BP)
  866. Loc = Builder.CreateBitCast(Loc, BP);
  867. // If the initializer is all or mostly zeros, codegen with memset then do
  868. // a few stores afterward.
  869. if (shouldUseMemSetPlusStoresToInitialize(constant,
  870. CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
  871. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  872. alignment.getQuantity(), isVolatile);
  873. if (!constant->isNullValue()) {
  874. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  875. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  876. }
  877. } else {
  878. // Otherwise, create a temporary global with the initializer then
  879. // memcpy from the global to the alloca.
  880. std::string Name = GetStaticDeclName(*this, D, ".");
  881. llvm::GlobalVariable *GV =
  882. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  883. llvm::GlobalValue::PrivateLinkage,
  884. constant, Name, 0, false, 0);
  885. GV->setAlignment(alignment.getQuantity());
  886. GV->setUnnamedAddr(true);
  887. llvm::Value *SrcPtr = GV;
  888. if (SrcPtr->getType() != BP)
  889. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  890. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  891. isVolatile);
  892. }
  893. }
  894. /// Emit an expression as an initializer for a variable at the given
  895. /// location. The expression is not necessarily the normal
  896. /// initializer for the variable, and the address is not necessarily
  897. /// its normal location.
  898. ///
  899. /// \param init the initializing expression
  900. /// \param var the variable to act as if we're initializing
  901. /// \param loc the address to initialize; its type is a pointer
  902. /// to the LLVM mapping of the variable's type
  903. /// \param alignment the alignment of the address
  904. /// \param capturedByInit true if the variable is a __block variable
  905. /// whose address is potentially changed by the initializer
  906. void CodeGenFunction::EmitExprAsInit(const Expr *init,
  907. const ValueDecl *D,
  908. LValue lvalue,
  909. bool capturedByInit) {
  910. QualType type = D->getType();
  911. if (type->isReferenceType()) {
  912. RValue rvalue = EmitReferenceBindingToExpr(init, D);
  913. if (capturedByInit)
  914. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  915. EmitStoreThroughLValue(rvalue, lvalue, true);
  916. } else if (!hasAggregateLLVMType(type)) {
  917. EmitScalarInit(init, D, lvalue, capturedByInit);
  918. } else if (type->isAnyComplexType()) {
  919. ComplexPairTy complex = EmitComplexExpr(init);
  920. if (capturedByInit)
  921. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  922. StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
  923. } else {
  924. // TODO: how can we delay here if D is captured by its initializer?
  925. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  926. AggValueSlot::IsDestructed,
  927. AggValueSlot::DoesNotNeedGCBarriers,
  928. AggValueSlot::IsNotAliased));
  929. MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
  930. }
  931. }
  932. /// Enter a destroy cleanup for the given local variable.
  933. void CodeGenFunction::emitAutoVarTypeCleanup(
  934. const CodeGenFunction::AutoVarEmission &emission,
  935. QualType::DestructionKind dtorKind) {
  936. assert(dtorKind != QualType::DK_none);
  937. // Note that for __block variables, we want to destroy the
  938. // original stack object, not the possibly forwarded object.
  939. llvm::Value *addr = emission.getObjectAddress(*this);
  940. const VarDecl *var = emission.Variable;
  941. QualType type = var->getType();
  942. CleanupKind cleanupKind = NormalAndEHCleanup;
  943. CodeGenFunction::Destroyer *destroyer = 0;
  944. switch (dtorKind) {
  945. case QualType::DK_none:
  946. llvm_unreachable("no cleanup for trivially-destructible variable");
  947. case QualType::DK_cxx_destructor:
  948. // If there's an NRVO flag on the emission, we need a different
  949. // cleanup.
  950. if (emission.NRVOFlag) {
  951. assert(!type->isArrayType());
  952. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  953. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  954. emission.NRVOFlag);
  955. return;
  956. }
  957. break;
  958. case QualType::DK_objc_strong_lifetime:
  959. // Suppress cleanups for pseudo-strong variables.
  960. if (var->isARCPseudoStrong()) return;
  961. // Otherwise, consider whether to use an EH cleanup or not.
  962. cleanupKind = getARCCleanupKind();
  963. // Use the imprecise destroyer by default.
  964. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  965. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  966. break;
  967. case QualType::DK_objc_weak_lifetime:
  968. break;
  969. }
  970. // If we haven't chosen a more specific destroyer, use the default.
  971. if (!destroyer) destroyer = getDestroyer(dtorKind);
  972. // Use an EH cleanup in array destructors iff the destructor itself
  973. // is being pushed as an EH cleanup.
  974. bool useEHCleanup = (cleanupKind & EHCleanup);
  975. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  976. useEHCleanup);
  977. }
  978. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  979. assert(emission.Variable && "emission was not valid!");
  980. // If this was emitted as a global constant, we're done.
  981. if (emission.wasEmittedAsGlobal()) return;
  982. const VarDecl &D = *emission.Variable;
  983. // Check the type for a cleanup.
  984. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  985. emitAutoVarTypeCleanup(emission, dtorKind);
  986. // In GC mode, honor objc_precise_lifetime.
  987. if (getLangOptions().getGC() != LangOptions::NonGC &&
  988. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  989. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  990. }
  991. // Handle the cleanup attribute.
  992. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  993. const FunctionDecl *FD = CA->getFunctionDecl();
  994. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  995. assert(F && "Could not find function!");
  996. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  997. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  998. }
  999. // If this is a block variable, call _Block_object_destroy
  1000. // (on the unforwarded address).
  1001. if (emission.IsByRef)
  1002. enterByrefCleanup(emission);
  1003. }
  1004. CodeGenFunction::Destroyer *
  1005. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1006. switch (kind) {
  1007. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1008. case QualType::DK_cxx_destructor:
  1009. return destroyCXXObject;
  1010. case QualType::DK_objc_strong_lifetime:
  1011. return destroyARCStrongPrecise;
  1012. case QualType::DK_objc_weak_lifetime:
  1013. return destroyARCWeak;
  1014. }
  1015. llvm_unreachable("Unknown DestructionKind");
  1016. }
  1017. /// pushDestroy - Push the standard destructor for the given type.
  1018. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1019. llvm::Value *addr, QualType type) {
  1020. assert(dtorKind && "cannot push destructor for trivial type");
  1021. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1022. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1023. cleanupKind & EHCleanup);
  1024. }
  1025. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1026. QualType type, Destroyer *destroyer,
  1027. bool useEHCleanupForArray) {
  1028. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1029. destroyer, useEHCleanupForArray);
  1030. }
  1031. /// emitDestroy - Immediately perform the destruction of the given
  1032. /// object.
  1033. ///
  1034. /// \param addr - the address of the object; a type*
  1035. /// \param type - the type of the object; if an array type, all
  1036. /// objects are destroyed in reverse order
  1037. /// \param destroyer - the function to call to destroy individual
  1038. /// elements
  1039. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1040. /// used when destroying array elements, in case one of the
  1041. /// destructions throws an exception
  1042. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1043. Destroyer *destroyer,
  1044. bool useEHCleanupForArray) {
  1045. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1046. if (!arrayType)
  1047. return destroyer(*this, addr, type);
  1048. llvm::Value *begin = addr;
  1049. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1050. // Normally we have to check whether the array is zero-length.
  1051. bool checkZeroLength = true;
  1052. // But if the array length is constant, we can suppress that.
  1053. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1054. // ...and if it's constant zero, we can just skip the entire thing.
  1055. if (constLength->isZero()) return;
  1056. checkZeroLength = false;
  1057. }
  1058. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1059. emitArrayDestroy(begin, end, type, destroyer,
  1060. checkZeroLength, useEHCleanupForArray);
  1061. }
  1062. /// emitArrayDestroy - Destroys all the elements of the given array,
  1063. /// beginning from last to first. The array cannot be zero-length.
  1064. ///
  1065. /// \param begin - a type* denoting the first element of the array
  1066. /// \param end - a type* denoting one past the end of the array
  1067. /// \param type - the element type of the array
  1068. /// \param destroyer - the function to call to destroy elements
  1069. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1070. /// the remaining elements in case the destruction of a single
  1071. /// element throws
  1072. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1073. llvm::Value *end,
  1074. QualType type,
  1075. Destroyer *destroyer,
  1076. bool checkZeroLength,
  1077. bool useEHCleanup) {
  1078. assert(!type->isArrayType());
  1079. // The basic structure here is a do-while loop, because we don't
  1080. // need to check for the zero-element case.
  1081. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1082. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1083. if (checkZeroLength) {
  1084. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1085. "arraydestroy.isempty");
  1086. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1087. }
  1088. // Enter the loop body, making that address the current address.
  1089. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1090. EmitBlock(bodyBB);
  1091. llvm::PHINode *elementPast =
  1092. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1093. elementPast->addIncoming(end, entryBB);
  1094. // Shift the address back by one element.
  1095. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1096. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1097. "arraydestroy.element");
  1098. if (useEHCleanup)
  1099. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1100. // Perform the actual destruction there.
  1101. destroyer(*this, element, type);
  1102. if (useEHCleanup)
  1103. PopCleanupBlock();
  1104. // Check whether we've reached the end.
  1105. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1106. Builder.CreateCondBr(done, doneBB, bodyBB);
  1107. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1108. // Done.
  1109. EmitBlock(doneBB);
  1110. }
  1111. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1112. /// emitArrayDestroy, the element type here may still be an array type.
  1113. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1114. llvm::Value *begin, llvm::Value *end,
  1115. QualType type,
  1116. CodeGenFunction::Destroyer *destroyer) {
  1117. // If the element type is itself an array, drill down.
  1118. unsigned arrayDepth = 0;
  1119. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1120. // VLAs don't require a GEP index to walk into.
  1121. if (!isa<VariableArrayType>(arrayType))
  1122. arrayDepth++;
  1123. type = arrayType->getElementType();
  1124. }
  1125. if (arrayDepth) {
  1126. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1127. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1128. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1129. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1130. }
  1131. // Destroy the array. We don't ever need an EH cleanup because we
  1132. // assume that we're in an EH cleanup ourselves, so a throwing
  1133. // destructor causes an immediate terminate.
  1134. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1135. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1136. }
  1137. namespace {
  1138. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1139. /// array destroy where the end pointer is regularly determined and
  1140. /// does not need to be loaded from a local.
  1141. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1142. llvm::Value *ArrayBegin;
  1143. llvm::Value *ArrayEnd;
  1144. QualType ElementType;
  1145. CodeGenFunction::Destroyer *Destroyer;
  1146. public:
  1147. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1148. QualType elementType,
  1149. CodeGenFunction::Destroyer *destroyer)
  1150. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1151. ElementType(elementType), Destroyer(destroyer) {}
  1152. void Emit(CodeGenFunction &CGF, Flags flags) {
  1153. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1154. ElementType, Destroyer);
  1155. }
  1156. };
  1157. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1158. /// partial array destroy where the end pointer is irregularly
  1159. /// determined and must be loaded from a local.
  1160. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1161. llvm::Value *ArrayBegin;
  1162. llvm::Value *ArrayEndPointer;
  1163. QualType ElementType;
  1164. CodeGenFunction::Destroyer *Destroyer;
  1165. public:
  1166. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1167. llvm::Value *arrayEndPointer,
  1168. QualType elementType,
  1169. CodeGenFunction::Destroyer *destroyer)
  1170. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1171. ElementType(elementType), Destroyer(destroyer) {}
  1172. void Emit(CodeGenFunction &CGF, Flags flags) {
  1173. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1174. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1175. ElementType, Destroyer);
  1176. }
  1177. };
  1178. }
  1179. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1180. /// already-constructed elements of the given array. The cleanup
  1181. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1182. ///
  1183. /// \param elementType - the immediate element type of the array;
  1184. /// possibly still an array type
  1185. /// \param array - a value of type elementType*
  1186. /// \param destructionKind - the kind of destruction required
  1187. /// \param initializedElementCount - a value of type size_t* holding
  1188. /// the number of successfully-constructed elements
  1189. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1190. llvm::Value *arrayEndPointer,
  1191. QualType elementType,
  1192. Destroyer *destroyer) {
  1193. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1194. arrayBegin, arrayEndPointer,
  1195. elementType, destroyer);
  1196. }
  1197. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1198. /// already-constructed elements of the given array. The cleanup
  1199. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1200. ///
  1201. /// \param elementType - the immediate element type of the array;
  1202. /// possibly still an array type
  1203. /// \param array - a value of type elementType*
  1204. /// \param destructionKind - the kind of destruction required
  1205. /// \param initializedElementCount - a value of type size_t* holding
  1206. /// the number of successfully-constructed elements
  1207. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1208. llvm::Value *arrayEnd,
  1209. QualType elementType,
  1210. Destroyer *destroyer) {
  1211. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1212. arrayBegin, arrayEnd,
  1213. elementType, destroyer);
  1214. }
  1215. namespace {
  1216. /// A cleanup to perform a release of an object at the end of a
  1217. /// function. This is used to balance out the incoming +1 of a
  1218. /// ns_consumed argument when we can't reasonably do that just by
  1219. /// not doing the initial retain for a __block argument.
  1220. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1221. ConsumeARCParameter(llvm::Value *param) : Param(param) {}
  1222. llvm::Value *Param;
  1223. void Emit(CodeGenFunction &CGF, Flags flags) {
  1224. CGF.EmitARCRelease(Param, /*precise*/ false);
  1225. }
  1226. };
  1227. }
  1228. /// Emit an alloca (or GlobalValue depending on target)
  1229. /// for the specified parameter and set up LocalDeclMap.
  1230. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1231. unsigned ArgNo) {
  1232. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1233. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1234. "Invalid argument to EmitParmDecl");
  1235. Arg->setName(D.getName());
  1236. // Use better IR generation for certain implicit parameters.
  1237. if (isa<ImplicitParamDecl>(D)) {
  1238. // The only implicit argument a block has is its literal.
  1239. if (BlockInfo) {
  1240. LocalDeclMap[&D] = Arg;
  1241. if (CGDebugInfo *DI = getDebugInfo()) {
  1242. DI->setLocation(D.getLocation());
  1243. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
  1244. }
  1245. return;
  1246. }
  1247. }
  1248. QualType Ty = D.getType();
  1249. llvm::Value *DeclPtr;
  1250. // If this is an aggregate or variable sized value, reuse the input pointer.
  1251. if (!Ty->isConstantSizeType() ||
  1252. CodeGenFunction::hasAggregateLLVMType(Ty)) {
  1253. DeclPtr = Arg;
  1254. } else {
  1255. // Otherwise, create a temporary to hold the value.
  1256. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1257. D.getName() + ".addr");
  1258. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1259. DeclPtr = Alloc;
  1260. bool doStore = true;
  1261. Qualifiers qs = Ty.getQualifiers();
  1262. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1263. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1264. // For __strong, it's handled by just skipping the initial retain;
  1265. // otherwise we have to balance out the initial +1 with an extra
  1266. // cleanup to do the release at the end of the function.
  1267. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1268. // 'self' is always formally __strong, but if this is not an
  1269. // init method then we don't want to retain it.
  1270. if (D.isARCPseudoStrong()) {
  1271. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1272. assert(&D == method->getSelfDecl());
  1273. assert(lt == Qualifiers::OCL_Strong);
  1274. assert(qs.hasConst());
  1275. assert(method->getMethodFamily() != OMF_init);
  1276. (void) method;
  1277. lt = Qualifiers::OCL_ExplicitNone;
  1278. }
  1279. if (lt == Qualifiers::OCL_Strong) {
  1280. if (!isConsumed)
  1281. // Don't use objc_retainBlock for block pointers, because we
  1282. // don't want to Block_copy something just because we got it
  1283. // as a parameter.
  1284. Arg = EmitARCRetainNonBlock(Arg);
  1285. } else {
  1286. // Push the cleanup for a consumed parameter.
  1287. if (isConsumed)
  1288. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
  1289. if (lt == Qualifiers::OCL_Weak) {
  1290. EmitARCInitWeak(DeclPtr, Arg);
  1291. doStore = false; // The weak init is a store, no need to do two.
  1292. }
  1293. }
  1294. // Enter the cleanup scope.
  1295. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1296. }
  1297. // Store the initial value into the alloca.
  1298. if (doStore) {
  1299. LValue lv = MakeAddrLValue(DeclPtr, Ty,
  1300. getContext().getDeclAlign(&D));
  1301. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1302. }
  1303. }
  1304. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1305. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  1306. DMEntry = DeclPtr;
  1307. // Emit debug info for param declaration.
  1308. if (CGDebugInfo *DI = getDebugInfo())
  1309. DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
  1310. if (D.hasAttr<AnnotateAttr>())
  1311. EmitVarAnnotations(&D, DeclPtr);
  1312. }