CGDecl.cpp 58 KB

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