CodeGenModule.cpp 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CodeGenFunction.h"
  21. #include "CodeGenTBAA.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/CharUnits.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclTemplate.h"
  28. #include "clang/AST/Mangle.h"
  29. #include "clang/AST/RecordLayout.h"
  30. #include "clang/AST/RecursiveASTVisitor.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/CharInfo.h"
  33. #include "clang/Basic/Diagnostic.h"
  34. #include "clang/Basic/Module.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Basic/Version.h"
  38. #include "clang/Frontend/CodeGenOptions.h"
  39. #include "clang/Sema/SemaDiagnostic.h"
  40. #include "llvm/ADT/APSInt.h"
  41. #include "llvm/ADT/Triple.h"
  42. #include "llvm/IR/CallingConv.h"
  43. #include "llvm/IR/DataLayout.h"
  44. #include "llvm/IR/Intrinsics.h"
  45. #include "llvm/IR/LLVMContext.h"
  46. #include "llvm/IR/Module.h"
  47. #include "llvm/Support/CallSite.h"
  48. #include "llvm/Support/ConvertUTF.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Target/Mangler.h"
  51. using namespace clang;
  52. using namespace CodeGen;
  53. static const char AnnotationSection[] = "llvm.metadata";
  54. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  55. switch (CGM.getTarget().getCXXABI().getKind()) {
  56. case TargetCXXABI::GenericAArch64:
  57. case TargetCXXABI::GenericARM:
  58. case TargetCXXABI::iOS:
  59. case TargetCXXABI::GenericItanium:
  60. return *CreateItaniumCXXABI(CGM);
  61. case TargetCXXABI::Microsoft:
  62. return *CreateMicrosoftCXXABI(CGM);
  63. }
  64. llvm_unreachable("invalid C++ ABI kind");
  65. }
  66. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  67. llvm::Module &M, const llvm::DataLayout &TD,
  68. DiagnosticsEngine &diags)
  69. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  70. Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
  71. ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
  72. TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
  73. OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
  74. NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0),
  75. ConstantStringClassRef(0), NSConstantStringType(0),
  76. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
  77. BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
  78. LifetimeStartFn(0), LifetimeEndFn(0),
  79. SanitizerBlacklist(
  80. llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
  81. SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
  82. : LangOpts.Sanitize) {
  83. // Initialize the type cache.
  84. llvm::LLVMContext &LLVMContext = M.getContext();
  85. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  86. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  87. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  88. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  89. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  90. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  91. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  92. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  93. PointerAlignInBytes =
  94. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  95. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  96. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  97. Int8PtrTy = Int8Ty->getPointerTo(0);
  98. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  99. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  100. if (LangOpts.ObjC1)
  101. createObjCRuntime();
  102. if (LangOpts.OpenCL)
  103. createOpenCLRuntime();
  104. if (LangOpts.CUDA)
  105. createCUDARuntime();
  106. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  107. if (SanOpts.Thread ||
  108. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  109. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  110. ABI.getMangleContext());
  111. // If debug info or coverage generation is enabled, create the CGDebugInfo
  112. // object.
  113. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  114. CodeGenOpts.EmitGcovArcs ||
  115. CodeGenOpts.EmitGcovNotes)
  116. DebugInfo = new CGDebugInfo(*this);
  117. Block.GlobalUniqueCount = 0;
  118. if (C.getLangOpts().ObjCAutoRefCount)
  119. ARCData = new ARCEntrypoints();
  120. RRData = new RREntrypoints();
  121. }
  122. CodeGenModule::~CodeGenModule() {
  123. delete ObjCRuntime;
  124. delete OpenCLRuntime;
  125. delete CUDARuntime;
  126. delete TheTargetCodeGenInfo;
  127. delete &ABI;
  128. delete TBAA;
  129. delete DebugInfo;
  130. delete ARCData;
  131. delete RRData;
  132. }
  133. void CodeGenModule::createObjCRuntime() {
  134. // This is just isGNUFamily(), but we want to force implementors of
  135. // new ABIs to decide how best to do this.
  136. switch (LangOpts.ObjCRuntime.getKind()) {
  137. case ObjCRuntime::GNUstep:
  138. case ObjCRuntime::GCC:
  139. case ObjCRuntime::ObjFW:
  140. ObjCRuntime = CreateGNUObjCRuntime(*this);
  141. return;
  142. case ObjCRuntime::FragileMacOSX:
  143. case ObjCRuntime::MacOSX:
  144. case ObjCRuntime::iOS:
  145. ObjCRuntime = CreateMacObjCRuntime(*this);
  146. return;
  147. }
  148. llvm_unreachable("bad runtime kind");
  149. }
  150. void CodeGenModule::createOpenCLRuntime() {
  151. OpenCLRuntime = new CGOpenCLRuntime(*this);
  152. }
  153. void CodeGenModule::createCUDARuntime() {
  154. CUDARuntime = CreateNVCUDARuntime(*this);
  155. }
  156. void CodeGenModule::checkAliases() {
  157. bool Error = false;
  158. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  159. E = Aliases.end(); I != E; ++I) {
  160. const GlobalDecl &GD = *I;
  161. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  162. const AliasAttr *AA = D->getAttr<AliasAttr>();
  163. StringRef MangledName = getMangledName(GD);
  164. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  165. llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
  166. llvm::GlobalValue *GV = Alias->getAliasedGlobal();
  167. if (GV->isDeclaration()) {
  168. Error = true;
  169. getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
  170. } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) {
  171. Error = true;
  172. getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
  173. }
  174. }
  175. if (!Error)
  176. return;
  177. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  178. E = Aliases.end(); I != E; ++I) {
  179. const GlobalDecl &GD = *I;
  180. StringRef MangledName = getMangledName(GD);
  181. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  182. llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
  183. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  184. Alias->eraseFromParent();
  185. }
  186. }
  187. void CodeGenModule::Release() {
  188. EmitDeferred();
  189. checkAliases();
  190. EmitCXXGlobalInitFunc();
  191. EmitCXXGlobalDtorFunc();
  192. EmitCXXThreadLocalInitFunc();
  193. if (ObjCRuntime)
  194. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  195. AddGlobalCtor(ObjCInitFunction);
  196. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  197. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  198. EmitGlobalAnnotations();
  199. EmitStaticExternCAliases();
  200. EmitLLVMUsed();
  201. if (CodeGenOpts.Autolink &&
  202. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  203. EmitModuleLinkOptions();
  204. }
  205. if (CodeGenOpts.DwarfVersion)
  206. // We actually want the latest version when there are conflicts.
  207. // We can change from Warning to Latest if such mode is supported.
  208. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  209. CodeGenOpts.DwarfVersion);
  210. SimplifyPersonality();
  211. if (getCodeGenOpts().EmitDeclMetadata)
  212. EmitDeclMetadata();
  213. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  214. EmitCoverageFile();
  215. if (DebugInfo)
  216. DebugInfo->finalize();
  217. EmitVersionIdentMetadata();
  218. }
  219. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  220. // Make sure that this type is translated.
  221. Types.UpdateCompletedType(TD);
  222. }
  223. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  224. if (!TBAA)
  225. return 0;
  226. return TBAA->getTBAAInfo(QTy);
  227. }
  228. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  229. if (!TBAA)
  230. return 0;
  231. return TBAA->getTBAAInfoForVTablePtr();
  232. }
  233. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  234. if (!TBAA)
  235. return 0;
  236. return TBAA->getTBAAStructInfo(QTy);
  237. }
  238. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  239. if (!TBAA)
  240. return 0;
  241. return TBAA->getTBAAStructTypeInfo(QTy);
  242. }
  243. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  244. llvm::MDNode *AccessN,
  245. uint64_t O) {
  246. if (!TBAA)
  247. return 0;
  248. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  249. }
  250. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  251. /// and struct-path aware TBAA, the tag has the same format:
  252. /// base type, access type and offset.
  253. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  254. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  255. llvm::MDNode *TBAAInfo,
  256. bool ConvertTypeToTag) {
  257. if (ConvertTypeToTag && TBAA)
  258. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  259. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  260. else
  261. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  262. }
  263. void CodeGenModule::Error(SourceLocation loc, StringRef error) {
  264. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
  265. getDiags().Report(Context.getFullLoc(loc), diagID);
  266. }
  267. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  268. /// specified stmt yet.
  269. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  270. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  271. "cannot compile this %0 yet");
  272. std::string Msg = Type;
  273. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  274. << Msg << S->getSourceRange();
  275. }
  276. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  277. /// specified decl yet.
  278. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  279. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  280. "cannot compile this %0 yet");
  281. std::string Msg = Type;
  282. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  283. }
  284. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  285. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  286. }
  287. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  288. const NamedDecl *D) const {
  289. // Internal definitions always have default visibility.
  290. if (GV->hasLocalLinkage()) {
  291. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  292. return;
  293. }
  294. // Set visibility for definitions.
  295. LinkageInfo LV = D->getLinkageAndVisibility();
  296. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  297. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  298. }
  299. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  300. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  301. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  302. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  303. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  304. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  305. }
  306. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  307. CodeGenOptions::TLSModel M) {
  308. switch (M) {
  309. case CodeGenOptions::GeneralDynamicTLSModel:
  310. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  311. case CodeGenOptions::LocalDynamicTLSModel:
  312. return llvm::GlobalVariable::LocalDynamicTLSModel;
  313. case CodeGenOptions::InitialExecTLSModel:
  314. return llvm::GlobalVariable::InitialExecTLSModel;
  315. case CodeGenOptions::LocalExecTLSModel:
  316. return llvm::GlobalVariable::LocalExecTLSModel;
  317. }
  318. llvm_unreachable("Invalid TLS model!");
  319. }
  320. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  321. const VarDecl &D) const {
  322. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  323. llvm::GlobalVariable::ThreadLocalMode TLM;
  324. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  325. // Override the TLS model if it is explicitly specified.
  326. if (D.hasAttr<TLSModelAttr>()) {
  327. const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
  328. TLM = GetLLVMTLSModel(Attr->getModel());
  329. }
  330. GV->setThreadLocalMode(TLM);
  331. }
  332. /// Set the symbol visibility of type information (vtable and RTTI)
  333. /// associated with the given type.
  334. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  335. const CXXRecordDecl *RD,
  336. TypeVisibilityKind TVK) const {
  337. setGlobalVisibility(GV, RD);
  338. if (!CodeGenOpts.HiddenWeakVTables)
  339. return;
  340. // We never want to drop the visibility for RTTI names.
  341. if (TVK == TVK_ForRTTIName)
  342. return;
  343. // We want to drop the visibility to hidden for weak type symbols.
  344. // This isn't possible if there might be unresolved references
  345. // elsewhere that rely on this symbol being visible.
  346. // This should be kept roughly in sync with setThunkVisibility
  347. // in CGVTables.cpp.
  348. // Preconditions.
  349. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  350. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  351. return;
  352. // Don't override an explicit visibility attribute.
  353. if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
  354. return;
  355. switch (RD->getTemplateSpecializationKind()) {
  356. // We have to disable the optimization if this is an EI definition
  357. // because there might be EI declarations in other shared objects.
  358. case TSK_ExplicitInstantiationDefinition:
  359. case TSK_ExplicitInstantiationDeclaration:
  360. return;
  361. // Every use of a non-template class's type information has to emit it.
  362. case TSK_Undeclared:
  363. break;
  364. // In theory, implicit instantiations can ignore the possibility of
  365. // an explicit instantiation declaration because there necessarily
  366. // must be an EI definition somewhere with default visibility. In
  367. // practice, it's possible to have an explicit instantiation for
  368. // an arbitrary template class, and linkers aren't necessarily able
  369. // to deal with mixed-visibility symbols.
  370. case TSK_ExplicitSpecialization:
  371. case TSK_ImplicitInstantiation:
  372. return;
  373. }
  374. // If there's a key function, there may be translation units
  375. // that don't have the key function's definition. But ignore
  376. // this if we're emitting RTTI under -fno-rtti.
  377. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  378. // FIXME: what should we do if we "lose" the key function during
  379. // the emission of the file?
  380. if (Context.getCurrentKeyFunction(RD))
  381. return;
  382. }
  383. // Otherwise, drop the visibility to hidden.
  384. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  385. GV->setUnnamedAddr(true);
  386. }
  387. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  388. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  389. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  390. if (!Str.empty())
  391. return Str;
  392. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  393. IdentifierInfo *II = ND->getIdentifier();
  394. assert(II && "Attempt to mangle unnamed decl.");
  395. Str = II->getName();
  396. return Str;
  397. }
  398. SmallString<256> Buffer;
  399. llvm::raw_svector_ostream Out(Buffer);
  400. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  401. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  402. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  403. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  404. else
  405. getCXXABI().getMangleContext().mangleName(ND, Out);
  406. // Allocate space for the mangled name.
  407. Out.flush();
  408. size_t Length = Buffer.size();
  409. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  410. std::copy(Buffer.begin(), Buffer.end(), Name);
  411. Str = StringRef(Name, Length);
  412. return Str;
  413. }
  414. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  415. const BlockDecl *BD) {
  416. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  417. const Decl *D = GD.getDecl();
  418. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  419. if (D == 0)
  420. MangleCtx.mangleGlobalBlock(BD,
  421. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  422. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  423. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  424. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  425. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  426. else
  427. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  428. }
  429. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  430. return getModule().getNamedValue(Name);
  431. }
  432. /// AddGlobalCtor - Add a function to the list that will be called before
  433. /// main() runs.
  434. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  435. // FIXME: Type coercion of void()* types.
  436. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  437. }
  438. /// AddGlobalDtor - Add a function to the list that will be called
  439. /// when the module is unloaded.
  440. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  441. // FIXME: Type coercion of void()* types.
  442. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  443. }
  444. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  445. // Ctor function type is void()*.
  446. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  447. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  448. // Get the type of a ctor entry, { i32, void ()* }.
  449. llvm::StructType *CtorStructTy =
  450. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  451. // Construct the constructor and destructor arrays.
  452. SmallVector<llvm::Constant*, 8> Ctors;
  453. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  454. llvm::Constant *S[] = {
  455. llvm::ConstantInt::get(Int32Ty, I->second, false),
  456. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  457. };
  458. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  459. }
  460. if (!Ctors.empty()) {
  461. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  462. new llvm::GlobalVariable(TheModule, AT, false,
  463. llvm::GlobalValue::AppendingLinkage,
  464. llvm::ConstantArray::get(AT, Ctors),
  465. GlobalName);
  466. }
  467. }
  468. llvm::GlobalValue::LinkageTypes
  469. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  470. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  471. if (isa<CXXDestructorDecl>(D) &&
  472. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  473. GD.getDtorType()))
  474. return llvm::Function::LinkOnceODRLinkage;
  475. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  476. if (Linkage == GVA_Internal)
  477. return llvm::Function::InternalLinkage;
  478. if (D->hasAttr<DLLExportAttr>())
  479. return llvm::Function::DLLExportLinkage;
  480. if (D->hasAttr<WeakAttr>())
  481. return llvm::Function::WeakAnyLinkage;
  482. // In C99 mode, 'inline' functions are guaranteed to have a strong
  483. // definition somewhere else, so we can use available_externally linkage.
  484. if (Linkage == GVA_C99Inline)
  485. return llvm::Function::AvailableExternallyLinkage;
  486. // Note that Apple's kernel linker doesn't support symbol
  487. // coalescing, so we need to avoid linkonce and weak linkages there.
  488. // Normally, this means we just map to internal, but for explicit
  489. // instantiations we'll map to external.
  490. // In C++, the compiler has to emit a definition in every translation unit
  491. // that references the function. We should use linkonce_odr because
  492. // a) if all references in this translation unit are optimized away, we
  493. // don't need to codegen it. b) if the function persists, it needs to be
  494. // merged with other definitions. c) C++ has the ODR, so we know the
  495. // definition is dependable.
  496. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  497. return !Context.getLangOpts().AppleKext
  498. ? llvm::Function::LinkOnceODRLinkage
  499. : llvm::Function::InternalLinkage;
  500. // An explicit instantiation of a template has weak linkage, since
  501. // explicit instantiations can occur in multiple translation units
  502. // and must all be equivalent. However, we are not allowed to
  503. // throw away these explicit instantiations.
  504. if (Linkage == GVA_ExplicitTemplateInstantiation)
  505. return !Context.getLangOpts().AppleKext
  506. ? llvm::Function::WeakODRLinkage
  507. : llvm::Function::ExternalLinkage;
  508. // Otherwise, we have strong external linkage.
  509. assert(Linkage == GVA_StrongExternal);
  510. return llvm::Function::ExternalLinkage;
  511. }
  512. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  513. ///
  514. /// FIXME: This is currently only done for aliases and functions, but not for
  515. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  516. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  517. llvm::GlobalValue *GV) {
  518. SetCommonAttributes(D, GV);
  519. }
  520. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  521. const CGFunctionInfo &Info,
  522. llvm::Function *F) {
  523. unsigned CallingConv;
  524. AttributeListType AttributeList;
  525. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  526. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  527. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  528. }
  529. /// Determines whether the language options require us to model
  530. /// unwind exceptions. We treat -fexceptions as mandating this
  531. /// except under the fragile ObjC ABI with only ObjC exceptions
  532. /// enabled. This means, for example, that C with -fexceptions
  533. /// enables this.
  534. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  535. // If exceptions are completely disabled, obviously this is false.
  536. if (!LangOpts.Exceptions) return false;
  537. // If C++ exceptions are enabled, this is true.
  538. if (LangOpts.CXXExceptions) return true;
  539. // If ObjC exceptions are enabled, this depends on the ABI.
  540. if (LangOpts.ObjCExceptions) {
  541. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  542. }
  543. return true;
  544. }
  545. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  546. llvm::Function *F) {
  547. llvm::AttrBuilder B;
  548. if (CodeGenOpts.UnwindTables)
  549. B.addAttribute(llvm::Attribute::UWTable);
  550. if (!hasUnwindExceptions(LangOpts))
  551. B.addAttribute(llvm::Attribute::NoUnwind);
  552. if (D->hasAttr<NakedAttr>()) {
  553. // Naked implies noinline: we should not be inlining such functions.
  554. B.addAttribute(llvm::Attribute::Naked);
  555. B.addAttribute(llvm::Attribute::NoInline);
  556. } else if (D->hasAttr<NoInlineAttr>()) {
  557. B.addAttribute(llvm::Attribute::NoInline);
  558. } else if ((D->hasAttr<AlwaysInlineAttr>() ||
  559. D->hasAttr<ForceInlineAttr>()) &&
  560. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  561. llvm::Attribute::NoInline)) {
  562. // (noinline wins over always_inline, and we can't specify both in IR)
  563. B.addAttribute(llvm::Attribute::AlwaysInline);
  564. }
  565. if (D->hasAttr<ColdAttr>()) {
  566. B.addAttribute(llvm::Attribute::OptimizeForSize);
  567. B.addAttribute(llvm::Attribute::Cold);
  568. }
  569. if (D->hasAttr<MinSizeAttr>())
  570. B.addAttribute(llvm::Attribute::MinSize);
  571. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  572. B.addAttribute(llvm::Attribute::StackProtect);
  573. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  574. B.addAttribute(llvm::Attribute::StackProtectReq);
  575. // Add sanitizer attributes if function is not blacklisted.
  576. if (!SanitizerBlacklist->isIn(*F)) {
  577. // When AddressSanitizer is enabled, set SanitizeAddress attribute
  578. // unless __attribute__((no_sanitize_address)) is used.
  579. if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
  580. B.addAttribute(llvm::Attribute::SanitizeAddress);
  581. // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
  582. if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
  583. B.addAttribute(llvm::Attribute::SanitizeThread);
  584. }
  585. // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
  586. if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
  587. B.addAttribute(llvm::Attribute::SanitizeMemory);
  588. }
  589. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  590. llvm::AttributeSet::get(
  591. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  592. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  593. F->setUnnamedAddr(true);
  594. else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
  595. if (MD->isVirtual())
  596. F->setUnnamedAddr(true);
  597. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  598. if (alignment)
  599. F->setAlignment(alignment);
  600. // C++ ABI requires 2-byte alignment for member functions.
  601. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  602. F->setAlignment(2);
  603. }
  604. void CodeGenModule::SetCommonAttributes(const Decl *D,
  605. llvm::GlobalValue *GV) {
  606. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  607. setGlobalVisibility(GV, ND);
  608. else
  609. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  610. if (D->hasAttr<UsedAttr>())
  611. AddUsedGlobal(GV);
  612. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  613. GV->setSection(SA->getName());
  614. // Alias cannot have attributes. Filter them here.
  615. if (!isa<llvm::GlobalAlias>(GV))
  616. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  617. }
  618. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  619. llvm::Function *F,
  620. const CGFunctionInfo &FI) {
  621. SetLLVMFunctionAttributes(D, FI, F);
  622. SetLLVMFunctionAttributesForDefinition(D, F);
  623. F->setLinkage(llvm::Function::InternalLinkage);
  624. SetCommonAttributes(D, F);
  625. }
  626. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  627. llvm::Function *F,
  628. bool IsIncompleteFunction) {
  629. if (unsigned IID = F->getIntrinsicID()) {
  630. // If this is an intrinsic function, set the function's attributes
  631. // to the intrinsic's attributes.
  632. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
  633. (llvm::Intrinsic::ID)IID));
  634. return;
  635. }
  636. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  637. if (!IsIncompleteFunction)
  638. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  639. if (getCXXABI().HasThisReturn(GD)) {
  640. assert(!F->arg_empty() &&
  641. F->arg_begin()->getType()
  642. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  643. "unexpected this return");
  644. F->addAttribute(1, llvm::Attribute::Returned);
  645. }
  646. // Only a few attributes are set on declarations; these may later be
  647. // overridden by a definition.
  648. if (FD->hasAttr<DLLImportAttr>()) {
  649. F->setLinkage(llvm::Function::DLLImportLinkage);
  650. } else if (FD->hasAttr<WeakAttr>() ||
  651. FD->isWeakImported()) {
  652. // "extern_weak" is overloaded in LLVM; we probably should have
  653. // separate linkage types for this.
  654. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  655. } else {
  656. F->setLinkage(llvm::Function::ExternalLinkage);
  657. LinkageInfo LV = FD->getLinkageAndVisibility();
  658. if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
  659. F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  660. }
  661. }
  662. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  663. F->setSection(SA->getName());
  664. // A replaceable global allocation function does not act like a builtin by
  665. // default, only if it is invoked by a new-expression or delete-expression.
  666. if (FD->isReplaceableGlobalAllocationFunction())
  667. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  668. llvm::Attribute::NoBuiltin);
  669. }
  670. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  671. assert(!GV->isDeclaration() &&
  672. "Only globals with definition can force usage.");
  673. LLVMUsed.push_back(GV);
  674. }
  675. void CodeGenModule::EmitLLVMUsed() {
  676. // Don't create llvm.used if there is no need.
  677. if (LLVMUsed.empty())
  678. return;
  679. // Convert LLVMUsed to what ConstantArray needs.
  680. SmallVector<llvm::Constant*, 8> UsedArray;
  681. UsedArray.resize(LLVMUsed.size());
  682. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  683. UsedArray[i] =
  684. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  685. Int8PtrTy);
  686. }
  687. if (UsedArray.empty())
  688. return;
  689. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  690. llvm::GlobalVariable *GV =
  691. new llvm::GlobalVariable(getModule(), ATy, false,
  692. llvm::GlobalValue::AppendingLinkage,
  693. llvm::ConstantArray::get(ATy, UsedArray),
  694. "llvm.used");
  695. GV->setSection("llvm.metadata");
  696. }
  697. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  698. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  699. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  700. }
  701. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  702. llvm::SmallString<32> Opt;
  703. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  704. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  705. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  706. }
  707. void CodeGenModule::AddDependentLib(StringRef Lib) {
  708. llvm::SmallString<24> Opt;
  709. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  710. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  711. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  712. }
  713. /// \brief Add link options implied by the given module, including modules
  714. /// it depends on, using a postorder walk.
  715. static void addLinkOptionsPostorder(CodeGenModule &CGM,
  716. Module *Mod,
  717. SmallVectorImpl<llvm::Value *> &Metadata,
  718. llvm::SmallPtrSet<Module *, 16> &Visited) {
  719. // Import this module's parent.
  720. if (Mod->Parent && Visited.insert(Mod->Parent)) {
  721. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  722. }
  723. // Import this module's dependencies.
  724. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  725. if (Visited.insert(Mod->Imports[I-1]))
  726. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  727. }
  728. // Add linker options to link against the libraries/frameworks
  729. // described by this module.
  730. llvm::LLVMContext &Context = CGM.getLLVMContext();
  731. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  732. // Link against a framework. Frameworks are currently Darwin only, so we
  733. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  734. if (Mod->LinkLibraries[I-1].IsFramework) {
  735. llvm::Value *Args[2] = {
  736. llvm::MDString::get(Context, "-framework"),
  737. llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
  738. };
  739. Metadata.push_back(llvm::MDNode::get(Context, Args));
  740. continue;
  741. }
  742. // Link against a library.
  743. llvm::SmallString<24> Opt;
  744. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  745. Mod->LinkLibraries[I-1].Library, Opt);
  746. llvm::Value *OptString = llvm::MDString::get(Context, Opt);
  747. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  748. }
  749. }
  750. void CodeGenModule::EmitModuleLinkOptions() {
  751. // Collect the set of all of the modules we want to visit to emit link
  752. // options, which is essentially the imported modules and all of their
  753. // non-explicit child modules.
  754. llvm::SetVector<clang::Module *> LinkModules;
  755. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  756. SmallVector<clang::Module *, 16> Stack;
  757. // Seed the stack with imported modules.
  758. for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
  759. MEnd = ImportedModules.end();
  760. M != MEnd; ++M) {
  761. if (Visited.insert(*M))
  762. Stack.push_back(*M);
  763. }
  764. // Find all of the modules to import, making a little effort to prune
  765. // non-leaf modules.
  766. while (!Stack.empty()) {
  767. clang::Module *Mod = Stack.pop_back_val();
  768. bool AnyChildren = false;
  769. // Visit the submodules of this module.
  770. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  771. SubEnd = Mod->submodule_end();
  772. Sub != SubEnd; ++Sub) {
  773. // Skip explicit children; they need to be explicitly imported to be
  774. // linked against.
  775. if ((*Sub)->IsExplicit)
  776. continue;
  777. if (Visited.insert(*Sub)) {
  778. Stack.push_back(*Sub);
  779. AnyChildren = true;
  780. }
  781. }
  782. // We didn't find any children, so add this module to the list of
  783. // modules to link against.
  784. if (!AnyChildren) {
  785. LinkModules.insert(Mod);
  786. }
  787. }
  788. // Add link options for all of the imported modules in reverse topological
  789. // order. We don't do anything to try to order import link flags with respect
  790. // to linker options inserted by things like #pragma comment().
  791. SmallVector<llvm::Value *, 16> MetadataArgs;
  792. Visited.clear();
  793. for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
  794. MEnd = LinkModules.end();
  795. M != MEnd; ++M) {
  796. if (Visited.insert(*M))
  797. addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
  798. }
  799. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  800. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  801. // Add the linker options metadata flag.
  802. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  803. llvm::MDNode::get(getLLVMContext(),
  804. LinkerOptionsMetadata));
  805. }
  806. void CodeGenModule::EmitDeferred() {
  807. // Emit code for any potentially referenced deferred decls. Since a
  808. // previously unused static decl may become used during the generation of code
  809. // for a static function, iterate until no changes are made.
  810. while (true) {
  811. if (!DeferredVTables.empty()) {
  812. EmitDeferredVTables();
  813. // Emitting a v-table doesn't directly cause more v-tables to
  814. // become deferred, although it can cause functions to be
  815. // emitted that then need those v-tables.
  816. assert(DeferredVTables.empty());
  817. }
  818. // Stop if we're out of both deferred v-tables and deferred declarations.
  819. if (DeferredDeclsToEmit.empty()) break;
  820. GlobalDecl D = DeferredDeclsToEmit.back();
  821. DeferredDeclsToEmit.pop_back();
  822. // Check to see if we've already emitted this. This is necessary
  823. // for a couple of reasons: first, decls can end up in the
  824. // deferred-decls queue multiple times, and second, decls can end
  825. // up with definitions in unusual ways (e.g. by an extern inline
  826. // function acquiring a strong function redefinition). Just
  827. // ignore these cases.
  828. //
  829. // TODO: That said, looking this up multiple times is very wasteful.
  830. StringRef Name = getMangledName(D);
  831. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  832. assert(CGRef && "Deferred decl wasn't referenced?");
  833. if (!CGRef->isDeclaration())
  834. continue;
  835. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  836. // purposes an alias counts as a definition.
  837. if (isa<llvm::GlobalAlias>(CGRef))
  838. continue;
  839. // Otherwise, emit the definition and move on to the next one.
  840. EmitGlobalDefinition(D);
  841. }
  842. }
  843. void CodeGenModule::EmitGlobalAnnotations() {
  844. if (Annotations.empty())
  845. return;
  846. // Create a new global variable for the ConstantStruct in the Module.
  847. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  848. Annotations[0]->getType(), Annotations.size()), Annotations);
  849. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  850. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  851. "llvm.global.annotations");
  852. gv->setSection(AnnotationSection);
  853. }
  854. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  855. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  856. if (i != AnnotationStrings.end())
  857. return i->second;
  858. // Not found yet, create a new global.
  859. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  860. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  861. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  862. gv->setSection(AnnotationSection);
  863. gv->setUnnamedAddr(true);
  864. AnnotationStrings[Str] = gv;
  865. return gv;
  866. }
  867. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  868. SourceManager &SM = getContext().getSourceManager();
  869. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  870. if (PLoc.isValid())
  871. return EmitAnnotationString(PLoc.getFilename());
  872. return EmitAnnotationString(SM.getBufferName(Loc));
  873. }
  874. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  875. SourceManager &SM = getContext().getSourceManager();
  876. PresumedLoc PLoc = SM.getPresumedLoc(L);
  877. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  878. SM.getExpansionLineNumber(L);
  879. return llvm::ConstantInt::get(Int32Ty, LineNo);
  880. }
  881. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  882. const AnnotateAttr *AA,
  883. SourceLocation L) {
  884. // Get the globals for file name, annotation, and the line number.
  885. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  886. *UnitGV = EmitAnnotationUnit(L),
  887. *LineNoCst = EmitAnnotationLineNo(L);
  888. // Create the ConstantStruct for the global annotation.
  889. llvm::Constant *Fields[4] = {
  890. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  891. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  892. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  893. LineNoCst
  894. };
  895. return llvm::ConstantStruct::getAnon(Fields);
  896. }
  897. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  898. llvm::GlobalValue *GV) {
  899. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  900. // Get the struct elements for these annotations.
  901. for (specific_attr_iterator<AnnotateAttr>
  902. ai = D->specific_attr_begin<AnnotateAttr>(),
  903. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  904. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  905. }
  906. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  907. // Never defer when EmitAllDecls is specified.
  908. if (LangOpts.EmitAllDecls)
  909. return false;
  910. return !getContext().DeclMustBeEmitted(Global);
  911. }
  912. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  913. const CXXUuidofExpr* E) {
  914. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  915. // well-formed.
  916. StringRef Uuid = E->getUuidAsStringRef(Context);
  917. std::string Name = "_GUID_" + Uuid.lower();
  918. std::replace(Name.begin(), Name.end(), '-', '_');
  919. // Look for an existing global.
  920. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  921. return GV;
  922. llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
  923. assert(Init && "failed to initialize as constant");
  924. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  925. getModule(), Init->getType(),
  926. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  927. return GV;
  928. }
  929. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  930. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  931. assert(AA && "No alias?");
  932. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  933. // See if there is already something with the target's name in the module.
  934. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  935. if (Entry) {
  936. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  937. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  938. }
  939. llvm::Constant *Aliasee;
  940. if (isa<llvm::FunctionType>(DeclTy))
  941. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  942. GlobalDecl(cast<FunctionDecl>(VD)),
  943. /*ForVTable=*/false);
  944. else
  945. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  946. llvm::PointerType::getUnqual(DeclTy), 0);
  947. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  948. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  949. WeakRefReferences.insert(F);
  950. return Aliasee;
  951. }
  952. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  953. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  954. // Weak references don't produce any output by themselves.
  955. if (Global->hasAttr<WeakRefAttr>())
  956. return;
  957. // If this is an alias definition (which otherwise looks like a declaration)
  958. // emit it now.
  959. if (Global->hasAttr<AliasAttr>())
  960. return EmitAliasDefinition(GD);
  961. // If this is CUDA, be selective about which declarations we emit.
  962. if (LangOpts.CUDA) {
  963. if (CodeGenOpts.CUDAIsDevice) {
  964. if (!Global->hasAttr<CUDADeviceAttr>() &&
  965. !Global->hasAttr<CUDAGlobalAttr>() &&
  966. !Global->hasAttr<CUDAConstantAttr>() &&
  967. !Global->hasAttr<CUDASharedAttr>())
  968. return;
  969. } else {
  970. if (!Global->hasAttr<CUDAHostAttr>() && (
  971. Global->hasAttr<CUDADeviceAttr>() ||
  972. Global->hasAttr<CUDAConstantAttr>() ||
  973. Global->hasAttr<CUDASharedAttr>()))
  974. return;
  975. }
  976. }
  977. // Ignore declarations, they will be emitted on their first use.
  978. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  979. // Forward declarations are emitted lazily on first use.
  980. if (!FD->doesThisDeclarationHaveABody()) {
  981. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  982. return;
  983. const FunctionDecl *InlineDefinition = 0;
  984. FD->getBody(InlineDefinition);
  985. StringRef MangledName = getMangledName(GD);
  986. DeferredDecls.erase(MangledName);
  987. EmitGlobalDefinition(InlineDefinition);
  988. return;
  989. }
  990. } else {
  991. const VarDecl *VD = cast<VarDecl>(Global);
  992. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  993. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  994. return;
  995. }
  996. // Defer code generation when possible if this is a static definition, inline
  997. // function etc. These we only want to emit if they are used.
  998. if (!MayDeferGeneration(Global)) {
  999. // Emit the definition if it can't be deferred.
  1000. EmitGlobalDefinition(GD);
  1001. return;
  1002. }
  1003. // If we're deferring emission of a C++ variable with an
  1004. // initializer, remember the order in which it appeared in the file.
  1005. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1006. cast<VarDecl>(Global)->hasInit()) {
  1007. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1008. CXXGlobalInits.push_back(0);
  1009. }
  1010. // If the value has already been used, add it directly to the
  1011. // DeferredDeclsToEmit list.
  1012. StringRef MangledName = getMangledName(GD);
  1013. if (GetGlobalValue(MangledName))
  1014. DeferredDeclsToEmit.push_back(GD);
  1015. else {
  1016. // Otherwise, remember that we saw a deferred decl with this name. The
  1017. // first use of the mangled name will cause it to move into
  1018. // DeferredDeclsToEmit.
  1019. DeferredDecls[MangledName] = GD;
  1020. }
  1021. }
  1022. namespace {
  1023. struct FunctionIsDirectlyRecursive :
  1024. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1025. const StringRef Name;
  1026. const Builtin::Context &BI;
  1027. bool Result;
  1028. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1029. Name(N), BI(C), Result(false) {
  1030. }
  1031. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1032. bool TraverseCallExpr(CallExpr *E) {
  1033. const FunctionDecl *FD = E->getDirectCallee();
  1034. if (!FD)
  1035. return true;
  1036. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1037. if (Attr && Name == Attr->getLabel()) {
  1038. Result = true;
  1039. return false;
  1040. }
  1041. unsigned BuiltinID = FD->getBuiltinID();
  1042. if (!BuiltinID)
  1043. return true;
  1044. StringRef BuiltinName = BI.GetName(BuiltinID);
  1045. if (BuiltinName.startswith("__builtin_") &&
  1046. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1047. Result = true;
  1048. return false;
  1049. }
  1050. return true;
  1051. }
  1052. };
  1053. }
  1054. // isTriviallyRecursive - Check if this function calls another
  1055. // decl that, because of the asm attribute or the other decl being a builtin,
  1056. // ends up pointing to itself.
  1057. bool
  1058. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1059. StringRef Name;
  1060. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1061. // asm labels are a special kind of mangling we have to support.
  1062. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1063. if (!Attr)
  1064. return false;
  1065. Name = Attr->getLabel();
  1066. } else {
  1067. Name = FD->getName();
  1068. }
  1069. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1070. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1071. return Walker.Result;
  1072. }
  1073. bool
  1074. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1075. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1076. return true;
  1077. const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
  1078. if (CodeGenOpts.OptimizationLevel == 0 &&
  1079. !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
  1080. return false;
  1081. // PR9614. Avoid cases where the source code is lying to us. An available
  1082. // externally function should have an equivalent function somewhere else,
  1083. // but a function that calls itself is clearly not equivalent to the real
  1084. // implementation.
  1085. // This happens in glibc's btowc and in some configure checks.
  1086. return !isTriviallyRecursive(F);
  1087. }
  1088. /// If the type for the method's class was generated by
  1089. /// CGDebugInfo::createContextChain(), the cache contains only a
  1090. /// limited DIType without any declarations. Since EmitFunctionStart()
  1091. /// needs to find the canonical declaration for each method, we need
  1092. /// to construct the complete type prior to emitting the method.
  1093. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1094. if (!D->isInstance())
  1095. return;
  1096. if (CGDebugInfo *DI = getModuleDebugInfo())
  1097. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1098. const PointerType *ThisPtr =
  1099. cast<PointerType>(D->getThisType(getContext()));
  1100. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1101. }
  1102. }
  1103. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  1104. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1105. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1106. Context.getSourceManager(),
  1107. "Generating code for declaration");
  1108. if (isa<FunctionDecl>(D)) {
  1109. // At -O0, don't generate IR for functions with available_externally
  1110. // linkage.
  1111. if (!shouldEmitFunction(GD))
  1112. return;
  1113. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  1114. CompleteDIClassType(Method);
  1115. // Make sure to emit the definition(s) before we emit the thunks.
  1116. // This is necessary for the generation of certain thunks.
  1117. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  1118. EmitCXXConstructor(CD, GD.getCtorType());
  1119. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  1120. EmitCXXDestructor(DD, GD.getDtorType());
  1121. else
  1122. EmitGlobalFunctionDefinition(GD);
  1123. if (Method->isVirtual())
  1124. getVTables().EmitThunks(GD);
  1125. return;
  1126. }
  1127. return EmitGlobalFunctionDefinition(GD);
  1128. }
  1129. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1130. return EmitGlobalVarDefinition(VD);
  1131. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1132. }
  1133. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1134. /// module, create and return an llvm Function with the specified type. If there
  1135. /// is something in the module with the specified name, return it potentially
  1136. /// bitcasted to the right type.
  1137. ///
  1138. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1139. /// to set the attributes on the function when it is first created.
  1140. llvm::Constant *
  1141. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1142. llvm::Type *Ty,
  1143. GlobalDecl GD, bool ForVTable,
  1144. llvm::AttributeSet ExtraAttrs) {
  1145. const Decl *D = GD.getDecl();
  1146. // Lookup the entry, lazily creating it if necessary.
  1147. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1148. if (Entry) {
  1149. if (WeakRefReferences.erase(Entry)) {
  1150. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1151. if (FD && !FD->hasAttr<WeakAttr>())
  1152. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1153. }
  1154. if (Entry->getType()->getElementType() == Ty)
  1155. return Entry;
  1156. // Make sure the result is of the correct type.
  1157. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1158. }
  1159. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1160. // each other bottoming out with the base dtor. Therefore we emit non-base
  1161. // dtors on usage, even if there is no dtor definition in the TU.
  1162. if (D && isa<CXXDestructorDecl>(D) &&
  1163. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1164. GD.getDtorType()))
  1165. DeferredDeclsToEmit.push_back(GD);
  1166. // This function doesn't have a complete type (for example, the return
  1167. // type is an incomplete struct). Use a fake type instead, and make
  1168. // sure not to try to set attributes.
  1169. bool IsIncompleteFunction = false;
  1170. llvm::FunctionType *FTy;
  1171. if (isa<llvm::FunctionType>(Ty)) {
  1172. FTy = cast<llvm::FunctionType>(Ty);
  1173. } else {
  1174. FTy = llvm::FunctionType::get(VoidTy, false);
  1175. IsIncompleteFunction = true;
  1176. }
  1177. llvm::Function *F = llvm::Function::Create(FTy,
  1178. llvm::Function::ExternalLinkage,
  1179. MangledName, &getModule());
  1180. assert(F->getName() == MangledName && "name was uniqued!");
  1181. if (D)
  1182. SetFunctionAttributes(GD, F, IsIncompleteFunction);
  1183. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1184. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1185. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1186. llvm::AttributeSet::get(VMContext,
  1187. llvm::AttributeSet::FunctionIndex,
  1188. B));
  1189. }
  1190. // This is the first use or definition of a mangled name. If there is a
  1191. // deferred decl with this name, remember that we need to emit it at the end
  1192. // of the file.
  1193. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1194. if (DDI != DeferredDecls.end()) {
  1195. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1196. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1197. DeferredDeclsToEmit.push_back(DDI->second);
  1198. DeferredDecls.erase(DDI);
  1199. // Otherwise, if this is a sized deallocation function, emit a weak definition
  1200. // for it at the end of the translation unit.
  1201. } else if (D && cast<FunctionDecl>(D)
  1202. ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
  1203. DeferredDeclsToEmit.push_back(GD);
  1204. // Otherwise, there are cases we have to worry about where we're
  1205. // using a declaration for which we must emit a definition but where
  1206. // we might not find a top-level definition:
  1207. // - member functions defined inline in their classes
  1208. // - friend functions defined inline in some class
  1209. // - special member functions with implicit definitions
  1210. // If we ever change our AST traversal to walk into class methods,
  1211. // this will be unnecessary.
  1212. //
  1213. // We also don't emit a definition for a function if it's going to be an entry
  1214. // in a vtable, unless it's already marked as used.
  1215. } else if (getLangOpts().CPlusPlus && D) {
  1216. // Look for a declaration that's lexically in a record.
  1217. const FunctionDecl *FD = cast<FunctionDecl>(D);
  1218. FD = FD->getMostRecentDecl();
  1219. do {
  1220. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1221. if (FD->isImplicit() && !ForVTable) {
  1222. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  1223. DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
  1224. break;
  1225. } else if (FD->doesThisDeclarationHaveABody()) {
  1226. DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
  1227. break;
  1228. }
  1229. }
  1230. FD = FD->getPreviousDecl();
  1231. } while (FD);
  1232. }
  1233. // Make sure the result is of the requested type.
  1234. if (!IsIncompleteFunction) {
  1235. assert(F->getType()->getElementType() == Ty);
  1236. return F;
  1237. }
  1238. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1239. return llvm::ConstantExpr::getBitCast(F, PTy);
  1240. }
  1241. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1242. /// non-null, then this function will use the specified type if it has to
  1243. /// create it (this occurs when we see a definition of the function).
  1244. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1245. llvm::Type *Ty,
  1246. bool ForVTable) {
  1247. // If there was no specific requested type, just convert it now.
  1248. if (!Ty)
  1249. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1250. StringRef MangledName = getMangledName(GD);
  1251. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  1252. }
  1253. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1254. /// type and name.
  1255. llvm::Constant *
  1256. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1257. StringRef Name,
  1258. llvm::AttributeSet ExtraAttrs) {
  1259. llvm::Constant *C
  1260. = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1261. ExtraAttrs);
  1262. if (llvm::Function *F = dyn_cast<llvm::Function>(C))
  1263. if (F->empty())
  1264. F->setCallingConv(getRuntimeCC());
  1265. return C;
  1266. }
  1267. /// isTypeConstant - Determine whether an object of this type can be emitted
  1268. /// as a constant.
  1269. ///
  1270. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1271. /// will not be considered. The caller will need to verify that the object is
  1272. /// not written to during its construction.
  1273. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1274. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1275. return false;
  1276. if (Context.getLangOpts().CPlusPlus) {
  1277. if (const CXXRecordDecl *Record
  1278. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1279. return ExcludeCtor && !Record->hasMutableFields() &&
  1280. Record->hasTrivialDestructor();
  1281. }
  1282. return true;
  1283. }
  1284. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1285. /// create and return an llvm GlobalVariable with the specified type. If there
  1286. /// is something in the module with the specified name, return it potentially
  1287. /// bitcasted to the right type.
  1288. ///
  1289. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1290. /// to set the attributes on the global when it is first created.
  1291. llvm::Constant *
  1292. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1293. llvm::PointerType *Ty,
  1294. const VarDecl *D,
  1295. bool UnnamedAddr) {
  1296. // Lookup the entry, lazily creating it if necessary.
  1297. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1298. if (Entry) {
  1299. if (WeakRefReferences.erase(Entry)) {
  1300. if (D && !D->hasAttr<WeakAttr>())
  1301. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1302. }
  1303. if (UnnamedAddr)
  1304. Entry->setUnnamedAddr(true);
  1305. if (Entry->getType() == Ty)
  1306. return Entry;
  1307. // Make sure the result is of the correct type.
  1308. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1309. }
  1310. // This is the first use or definition of a mangled name. If there is a
  1311. // deferred decl with this name, remember that we need to emit it at the end
  1312. // of the file.
  1313. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1314. if (DDI != DeferredDecls.end()) {
  1315. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1316. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1317. DeferredDeclsToEmit.push_back(DDI->second);
  1318. DeferredDecls.erase(DDI);
  1319. }
  1320. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1321. llvm::GlobalVariable *GV =
  1322. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  1323. llvm::GlobalValue::ExternalLinkage,
  1324. 0, MangledName, 0,
  1325. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1326. // Handle things which are present even on external declarations.
  1327. if (D) {
  1328. // FIXME: This code is overly simple and should be merged with other global
  1329. // handling.
  1330. GV->setConstant(isTypeConstant(D->getType(), false));
  1331. // Set linkage and visibility in case we never see a definition.
  1332. LinkageInfo LV = D->getLinkageAndVisibility();
  1333. if (LV.getLinkage() != ExternalLinkage) {
  1334. // Don't set internal linkage on declarations.
  1335. } else {
  1336. if (D->hasAttr<DLLImportAttr>())
  1337. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1338. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1339. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1340. // Set visibility on a declaration only if it's explicit.
  1341. if (LV.isVisibilityExplicit())
  1342. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  1343. }
  1344. if (D->getTLSKind()) {
  1345. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1346. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1347. setTLSMode(GV, *D);
  1348. }
  1349. }
  1350. if (AddrSpace != Ty->getAddressSpace())
  1351. return llvm::ConstantExpr::getBitCast(GV, Ty);
  1352. else
  1353. return GV;
  1354. }
  1355. llvm::GlobalVariable *
  1356. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1357. llvm::Type *Ty,
  1358. llvm::GlobalValue::LinkageTypes Linkage) {
  1359. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1360. llvm::GlobalVariable *OldGV = 0;
  1361. if (GV) {
  1362. // Check if the variable has the right type.
  1363. if (GV->getType()->getElementType() == Ty)
  1364. return GV;
  1365. // Because C++ name mangling, the only way we can end up with an already
  1366. // existing global with the same name is if it has been declared extern "C".
  1367. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1368. OldGV = GV;
  1369. }
  1370. // Create a new variable.
  1371. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1372. Linkage, 0, Name);
  1373. if (OldGV) {
  1374. // Replace occurrences of the old variable if needed.
  1375. GV->takeName(OldGV);
  1376. if (!OldGV->use_empty()) {
  1377. llvm::Constant *NewPtrForOldDecl =
  1378. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1379. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1380. }
  1381. OldGV->eraseFromParent();
  1382. }
  1383. return GV;
  1384. }
  1385. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1386. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1387. /// then it will be created with the specified type instead of whatever the
  1388. /// normal requested type would be.
  1389. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1390. llvm::Type *Ty) {
  1391. assert(D->hasGlobalStorage() && "Not a global variable");
  1392. QualType ASTTy = D->getType();
  1393. if (Ty == 0)
  1394. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1395. llvm::PointerType *PTy =
  1396. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1397. StringRef MangledName = getMangledName(D);
  1398. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1399. }
  1400. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1401. /// specified type and name.
  1402. llvm::Constant *
  1403. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1404. StringRef Name) {
  1405. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1406. true);
  1407. }
  1408. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1409. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1410. if (MayDeferGeneration(D)) {
  1411. // If we have not seen a reference to this variable yet, place it
  1412. // into the deferred declarations table to be emitted if needed
  1413. // later.
  1414. StringRef MangledName = getMangledName(D);
  1415. if (!GetGlobalValue(MangledName)) {
  1416. DeferredDecls[MangledName] = D;
  1417. return;
  1418. }
  1419. }
  1420. // The tentative definition is the only definition.
  1421. EmitGlobalVarDefinition(D);
  1422. }
  1423. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1424. return Context.toCharUnitsFromBits(
  1425. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1426. }
  1427. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1428. unsigned AddrSpace) {
  1429. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1430. if (D->hasAttr<CUDAConstantAttr>())
  1431. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1432. else if (D->hasAttr<CUDASharedAttr>())
  1433. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1434. else
  1435. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1436. }
  1437. return AddrSpace;
  1438. }
  1439. template<typename SomeDecl>
  1440. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1441. llvm::GlobalValue *GV) {
  1442. if (!getLangOpts().CPlusPlus)
  1443. return;
  1444. // Must have 'used' attribute, or else inline assembly can't rely on
  1445. // the name existing.
  1446. if (!D->template hasAttr<UsedAttr>())
  1447. return;
  1448. // Must have internal linkage and an ordinary name.
  1449. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1450. return;
  1451. // Must be in an extern "C" context. Entities declared directly within
  1452. // a record are not extern "C" even if the record is in such a context.
  1453. const SomeDecl *First = D->getFirstDecl();
  1454. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1455. return;
  1456. // OK, this is an internal linkage entity inside an extern "C" linkage
  1457. // specification. Make a note of that so we can give it the "expected"
  1458. // mangled name if nothing else is using that name.
  1459. std::pair<StaticExternCMap::iterator, bool> R =
  1460. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1461. // If we have multiple internal linkage entities with the same name
  1462. // in extern "C" regions, none of them gets that name.
  1463. if (!R.second)
  1464. R.first->second = 0;
  1465. }
  1466. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1467. llvm::Constant *Init = 0;
  1468. QualType ASTTy = D->getType();
  1469. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1470. bool NeedsGlobalCtor = false;
  1471. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1472. const VarDecl *InitDecl;
  1473. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1474. if (!InitExpr) {
  1475. // This is a tentative definition; tentative definitions are
  1476. // implicitly initialized with { 0 }.
  1477. //
  1478. // Note that tentative definitions are only emitted at the end of
  1479. // a translation unit, so they should never have incomplete
  1480. // type. In addition, EmitTentativeDefinition makes sure that we
  1481. // never attempt to emit a tentative definition if a real one
  1482. // exists. A use may still exists, however, so we still may need
  1483. // to do a RAUW.
  1484. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1485. Init = EmitNullConstant(D->getType());
  1486. } else {
  1487. initializedGlobalDecl = GlobalDecl(D);
  1488. Init = EmitConstantInit(*InitDecl);
  1489. if (!Init) {
  1490. QualType T = InitExpr->getType();
  1491. if (D->getType()->isReferenceType())
  1492. T = D->getType();
  1493. if (getLangOpts().CPlusPlus) {
  1494. Init = EmitNullConstant(T);
  1495. NeedsGlobalCtor = true;
  1496. } else {
  1497. ErrorUnsupported(D, "static initializer");
  1498. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1499. }
  1500. } else {
  1501. // We don't need an initializer, so remove the entry for the delayed
  1502. // initializer position (just in case this entry was delayed) if we
  1503. // also don't need to register a destructor.
  1504. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1505. DelayedCXXInitPosition.erase(D);
  1506. }
  1507. }
  1508. llvm::Type* InitType = Init->getType();
  1509. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1510. // Strip off a bitcast if we got one back.
  1511. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1512. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1513. // all zero index gep.
  1514. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1515. Entry = CE->getOperand(0);
  1516. }
  1517. // Entry is now either a Function or GlobalVariable.
  1518. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1519. // We have a definition after a declaration with the wrong type.
  1520. // We must make a new GlobalVariable* and update everything that used OldGV
  1521. // (a declaration or tentative definition) with the new GlobalVariable*
  1522. // (which will be a definition).
  1523. //
  1524. // This happens if there is a prototype for a global (e.g.
  1525. // "extern int x[];") and then a definition of a different type (e.g.
  1526. // "int x[10];"). This also happens when an initializer has a different type
  1527. // from the type of the global (this happens with unions).
  1528. if (GV == 0 ||
  1529. GV->getType()->getElementType() != InitType ||
  1530. GV->getType()->getAddressSpace() !=
  1531. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1532. // Move the old entry aside so that we'll create a new one.
  1533. Entry->setName(StringRef());
  1534. // Make a new global with the correct type, this is now guaranteed to work.
  1535. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1536. // Replace all uses of the old global with the new global
  1537. llvm::Constant *NewPtrForOldDecl =
  1538. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1539. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1540. // Erase the old global, since it is no longer used.
  1541. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1542. }
  1543. MaybeHandleStaticInExternC(D, GV);
  1544. if (D->hasAttr<AnnotateAttr>())
  1545. AddGlobalAnnotations(D, GV);
  1546. GV->setInitializer(Init);
  1547. // If it is safe to mark the global 'constant', do so now.
  1548. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1549. isTypeConstant(D->getType(), true));
  1550. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1551. // Set the llvm linkage type as appropriate.
  1552. llvm::GlobalValue::LinkageTypes Linkage =
  1553. GetLLVMLinkageVarDefinition(D, GV->isConstant());
  1554. GV->setLinkage(Linkage);
  1555. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1556. // common vars aren't constant even if declared const.
  1557. GV->setConstant(false);
  1558. SetCommonAttributes(D, GV);
  1559. // Emit the initializer function if necessary.
  1560. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1561. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1562. // If we are compiling with ASan, add metadata indicating dynamically
  1563. // initialized globals.
  1564. if (SanOpts.Address && NeedsGlobalCtor) {
  1565. llvm::Module &M = getModule();
  1566. llvm::NamedMDNode *DynamicInitializers =
  1567. M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
  1568. llvm::Value *GlobalToAdd[] = { GV };
  1569. llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
  1570. DynamicInitializers->addOperand(ThisGlobal);
  1571. }
  1572. // Emit global variable debug information.
  1573. if (CGDebugInfo *DI = getModuleDebugInfo())
  1574. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1575. DI->EmitGlobalVariable(GV, D);
  1576. }
  1577. llvm::GlobalValue::LinkageTypes
  1578. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
  1579. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1580. if (Linkage == GVA_Internal)
  1581. return llvm::Function::InternalLinkage;
  1582. else if (D->hasAttr<DLLImportAttr>())
  1583. return llvm::Function::DLLImportLinkage;
  1584. else if (D->hasAttr<DLLExportAttr>())
  1585. return llvm::Function::DLLExportLinkage;
  1586. else if (D->hasAttr<SelectAnyAttr>()) {
  1587. // selectany symbols are externally visible, so use weak instead of
  1588. // linkonce. MSVC optimizes away references to const selectany globals, so
  1589. // all definitions should be the same and ODR linkage should be used.
  1590. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  1591. return llvm::GlobalVariable::WeakODRLinkage;
  1592. } else if (D->hasAttr<WeakAttr>()) {
  1593. if (isConstant)
  1594. return llvm::GlobalVariable::WeakODRLinkage;
  1595. else
  1596. return llvm::GlobalVariable::WeakAnyLinkage;
  1597. } else if (Linkage == GVA_TemplateInstantiation ||
  1598. Linkage == GVA_ExplicitTemplateInstantiation)
  1599. return llvm::GlobalVariable::WeakODRLinkage;
  1600. else if (!getLangOpts().CPlusPlus &&
  1601. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1602. D->getAttr<CommonAttr>()) &&
  1603. !D->hasExternalStorage() && !D->getInit() &&
  1604. !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
  1605. !D->getAttr<WeakImportAttr>()) {
  1606. // Thread local vars aren't considered common linkage.
  1607. return llvm::GlobalVariable::CommonLinkage;
  1608. } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
  1609. getTarget().getTriple().isMacOSX())
  1610. // On Darwin, the backing variable for a C++11 thread_local variable always
  1611. // has internal linkage; all accesses should just be calls to the
  1612. // Itanium-specified entry point, which has the normal linkage of the
  1613. // variable.
  1614. return llvm::GlobalValue::InternalLinkage;
  1615. return llvm::GlobalVariable::ExternalLinkage;
  1616. }
  1617. /// Replace the uses of a function that was declared with a non-proto type.
  1618. /// We want to silently drop extra arguments from call sites
  1619. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1620. llvm::Function *newFn) {
  1621. // Fast path.
  1622. if (old->use_empty()) return;
  1623. llvm::Type *newRetTy = newFn->getReturnType();
  1624. SmallVector<llvm::Value*, 4> newArgs;
  1625. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1626. ui != ue; ) {
  1627. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1628. llvm::User *user = *use;
  1629. // Recognize and replace uses of bitcasts. Most calls to
  1630. // unprototyped functions will use bitcasts.
  1631. if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1632. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1633. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1634. continue;
  1635. }
  1636. // Recognize calls to the function.
  1637. llvm::CallSite callSite(user);
  1638. if (!callSite) continue;
  1639. if (!callSite.isCallee(use)) continue;
  1640. // If the return types don't match exactly, then we can't
  1641. // transform this call unless it's dead.
  1642. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1643. continue;
  1644. // Get the call site's attribute list.
  1645. SmallVector<llvm::AttributeSet, 8> newAttrs;
  1646. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1647. // Collect any return attributes from the call.
  1648. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  1649. newAttrs.push_back(
  1650. llvm::AttributeSet::get(newFn->getContext(),
  1651. oldAttrs.getRetAttributes()));
  1652. // If the function was passed too few arguments, don't transform.
  1653. unsigned newNumArgs = newFn->arg_size();
  1654. if (callSite.arg_size() < newNumArgs) continue;
  1655. // If extra arguments were passed, we silently drop them.
  1656. // If any of the types mismatch, we don't transform.
  1657. unsigned argNo = 0;
  1658. bool dontTransform = false;
  1659. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1660. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1661. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1662. dontTransform = true;
  1663. break;
  1664. }
  1665. // Add any parameter attributes.
  1666. if (oldAttrs.hasAttributes(argNo + 1))
  1667. newAttrs.
  1668. push_back(llvm::
  1669. AttributeSet::get(newFn->getContext(),
  1670. oldAttrs.getParamAttributes(argNo + 1)));
  1671. }
  1672. if (dontTransform)
  1673. continue;
  1674. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  1675. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  1676. oldAttrs.getFnAttributes()));
  1677. // Okay, we can transform this. Create the new call instruction and copy
  1678. // over the required information.
  1679. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1680. llvm::CallSite newCall;
  1681. if (callSite.isCall()) {
  1682. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  1683. callSite.getInstruction());
  1684. } else {
  1685. llvm::InvokeInst *oldInvoke =
  1686. cast<llvm::InvokeInst>(callSite.getInstruction());
  1687. newCall = llvm::InvokeInst::Create(newFn,
  1688. oldInvoke->getNormalDest(),
  1689. oldInvoke->getUnwindDest(),
  1690. newArgs, "",
  1691. callSite.getInstruction());
  1692. }
  1693. newArgs.clear(); // for the next iteration
  1694. if (!newCall->getType()->isVoidTy())
  1695. newCall->takeName(callSite.getInstruction());
  1696. newCall.setAttributes(
  1697. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  1698. newCall.setCallingConv(callSite.getCallingConv());
  1699. // Finally, remove the old call, replacing any uses with the new one.
  1700. if (!callSite->use_empty())
  1701. callSite->replaceAllUsesWith(newCall.getInstruction());
  1702. // Copy debug location attached to CI.
  1703. if (!callSite->getDebugLoc().isUnknown())
  1704. newCall->setDebugLoc(callSite->getDebugLoc());
  1705. callSite->eraseFromParent();
  1706. }
  1707. }
  1708. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1709. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1710. /// existing call uses of the old function in the module, this adjusts them to
  1711. /// call the new function directly.
  1712. ///
  1713. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1714. /// functions to be able to inline them. If there is a bitcast in the way, it
  1715. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1716. /// run at -O0.
  1717. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1718. llvm::Function *NewFn) {
  1719. // If we're redefining a global as a function, don't transform it.
  1720. if (!isa<llvm::Function>(Old)) return;
  1721. replaceUsesOfNonProtoConstant(Old, NewFn);
  1722. }
  1723. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1724. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1725. // If we have a definition, this might be a deferred decl. If the
  1726. // instantiation is explicit, make sure we emit it at the end.
  1727. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1728. GetAddrOfGlobalVar(VD);
  1729. EmitTopLevelDecl(VD);
  1730. }
  1731. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1732. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1733. // Compute the function info and LLVM type.
  1734. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1735. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1736. // Get or create the prototype for the function.
  1737. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1738. // Strip off a bitcast if we got one back.
  1739. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1740. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1741. Entry = CE->getOperand(0);
  1742. }
  1743. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1744. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1745. // If the types mismatch then we have to rewrite the definition.
  1746. assert(OldFn->isDeclaration() &&
  1747. "Shouldn't replace non-declaration");
  1748. // F is the Function* for the one with the wrong type, we must make a new
  1749. // Function* and update everything that used F (a declaration) with the new
  1750. // Function* (which will be a definition).
  1751. //
  1752. // This happens if there is a prototype for a function
  1753. // (e.g. "int f()") and then a definition of a different type
  1754. // (e.g. "int f(int x)"). Move the old function aside so that it
  1755. // doesn't interfere with GetAddrOfFunction.
  1756. OldFn->setName(StringRef());
  1757. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1758. // This might be an implementation of a function without a
  1759. // prototype, in which case, try to do special replacement of
  1760. // calls which match the new prototype. The really key thing here
  1761. // is that we also potentially drop arguments from the call site
  1762. // so as to make a direct call, which makes the inliner happier
  1763. // and suppresses a number of optimizer warnings (!) about
  1764. // dropping arguments.
  1765. if (!OldFn->use_empty()) {
  1766. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1767. OldFn->removeDeadConstantUsers();
  1768. }
  1769. // Replace uses of F with the Function we will endow with a body.
  1770. if (!Entry->use_empty()) {
  1771. llvm::Constant *NewPtrForOldDecl =
  1772. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1773. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1774. }
  1775. // Ok, delete the old function now, which is dead.
  1776. OldFn->eraseFromParent();
  1777. Entry = NewFn;
  1778. }
  1779. // We need to set linkage and visibility on the function before
  1780. // generating code for it because various parts of IR generation
  1781. // want to propagate this information down (e.g. to local static
  1782. // declarations).
  1783. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1784. setFunctionLinkage(GD, Fn);
  1785. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1786. setGlobalVisibility(Fn, D);
  1787. MaybeHandleStaticInExternC(D, Fn);
  1788. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1789. SetFunctionDefinitionAttributes(D, Fn);
  1790. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1791. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1792. AddGlobalCtor(Fn, CA->getPriority());
  1793. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1794. AddGlobalDtor(Fn, DA->getPriority());
  1795. if (D->hasAttr<AnnotateAttr>())
  1796. AddGlobalAnnotations(D, Fn);
  1797. }
  1798. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1799. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1800. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1801. assert(AA && "Not an alias?");
  1802. StringRef MangledName = getMangledName(GD);
  1803. // If there is a definition in the module, then it wins over the alias.
  1804. // This is dubious, but allow it to be safe. Just ignore the alias.
  1805. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1806. if (Entry && !Entry->isDeclaration())
  1807. return;
  1808. Aliases.push_back(GD);
  1809. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1810. // Create a reference to the named value. This ensures that it is emitted
  1811. // if a deferred decl.
  1812. llvm::Constant *Aliasee;
  1813. if (isa<llvm::FunctionType>(DeclTy))
  1814. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  1815. /*ForVTable=*/false);
  1816. else
  1817. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1818. llvm::PointerType::getUnqual(DeclTy), 0);
  1819. // Create the new alias itself, but don't set a name yet.
  1820. llvm::GlobalValue *GA =
  1821. new llvm::GlobalAlias(Aliasee->getType(),
  1822. llvm::Function::ExternalLinkage,
  1823. "", Aliasee, &getModule());
  1824. if (Entry) {
  1825. assert(Entry->isDeclaration());
  1826. // If there is a declaration in the module, then we had an extern followed
  1827. // by the alias, as in:
  1828. // extern int test6();
  1829. // ...
  1830. // int test6() __attribute__((alias("test7")));
  1831. //
  1832. // Remove it and replace uses of it with the alias.
  1833. GA->takeName(Entry);
  1834. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1835. Entry->getType()));
  1836. Entry->eraseFromParent();
  1837. } else {
  1838. GA->setName(MangledName);
  1839. }
  1840. // Set attributes which are particular to an alias; this is a
  1841. // specialization of the attributes which may be set on a global
  1842. // variable/function.
  1843. if (D->hasAttr<DLLExportAttr>()) {
  1844. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1845. // The dllexport attribute is ignored for undefined symbols.
  1846. if (FD->hasBody())
  1847. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1848. } else {
  1849. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1850. }
  1851. } else if (D->hasAttr<WeakAttr>() ||
  1852. D->hasAttr<WeakRefAttr>() ||
  1853. D->isWeakImported()) {
  1854. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1855. }
  1856. SetCommonAttributes(D, GA);
  1857. }
  1858. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1859. ArrayRef<llvm::Type*> Tys) {
  1860. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1861. Tys);
  1862. }
  1863. static llvm::StringMapEntry<llvm::Constant*> &
  1864. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1865. const StringLiteral *Literal,
  1866. bool TargetIsLSB,
  1867. bool &IsUTF16,
  1868. unsigned &StringLength) {
  1869. StringRef String = Literal->getString();
  1870. unsigned NumBytes = String.size();
  1871. // Check for simple case.
  1872. if (!Literal->containsNonAsciiOrNull()) {
  1873. StringLength = NumBytes;
  1874. return Map.GetOrCreateValue(String);
  1875. }
  1876. // Otherwise, convert the UTF8 literals into a string of shorts.
  1877. IsUTF16 = true;
  1878. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1879. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1880. UTF16 *ToPtr = &ToBuf[0];
  1881. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1882. &ToPtr, ToPtr + NumBytes,
  1883. strictConversion);
  1884. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1885. StringLength = ToPtr - &ToBuf[0];
  1886. // Add an explicit null.
  1887. *ToPtr = 0;
  1888. return Map.
  1889. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1890. (StringLength + 1) * 2));
  1891. }
  1892. static llvm::StringMapEntry<llvm::Constant*> &
  1893. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1894. const StringLiteral *Literal,
  1895. unsigned &StringLength) {
  1896. StringRef String = Literal->getString();
  1897. StringLength = String.size();
  1898. return Map.GetOrCreateValue(String);
  1899. }
  1900. llvm::Constant *
  1901. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1902. unsigned StringLength = 0;
  1903. bool isUTF16 = false;
  1904. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1905. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1906. getDataLayout().isLittleEndian(),
  1907. isUTF16, StringLength);
  1908. if (llvm::Constant *C = Entry.getValue())
  1909. return C;
  1910. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1911. llvm::Constant *Zeros[] = { Zero, Zero };
  1912. llvm::Value *V;
  1913. // If we don't already have it, get __CFConstantStringClassReference.
  1914. if (!CFConstantStringClassRef) {
  1915. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1916. Ty = llvm::ArrayType::get(Ty, 0);
  1917. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1918. "__CFConstantStringClassReference");
  1919. // Decay array -> ptr
  1920. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1921. CFConstantStringClassRef = V;
  1922. }
  1923. else
  1924. V = CFConstantStringClassRef;
  1925. QualType CFTy = getContext().getCFConstantStringType();
  1926. llvm::StructType *STy =
  1927. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1928. llvm::Constant *Fields[4];
  1929. // Class pointer.
  1930. Fields[0] = cast<llvm::ConstantExpr>(V);
  1931. // Flags.
  1932. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1933. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1934. llvm::ConstantInt::get(Ty, 0x07C8);
  1935. // String pointer.
  1936. llvm::Constant *C = 0;
  1937. if (isUTF16) {
  1938. ArrayRef<uint16_t> Arr =
  1939. llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
  1940. const_cast<char *>(Entry.getKey().data())),
  1941. Entry.getKey().size() / 2);
  1942. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1943. } else {
  1944. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1945. }
  1946. llvm::GlobalValue::LinkageTypes Linkage;
  1947. if (isUTF16)
  1948. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1949. Linkage = llvm::GlobalValue::InternalLinkage;
  1950. else
  1951. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1952. // when using private linkage. It is not clear if this is a bug in ld
  1953. // or a reasonable new restriction.
  1954. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1955. // Note: -fwritable-strings doesn't make the backing store strings of
  1956. // CFStrings writable. (See <rdar://problem/10657500>)
  1957. llvm::GlobalVariable *GV =
  1958. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1959. Linkage, C, ".str");
  1960. GV->setUnnamedAddr(true);
  1961. // Don't enforce the target's minimum global alignment, since the only use
  1962. // of the string is via this class initializer.
  1963. if (isUTF16) {
  1964. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1965. GV->setAlignment(Align.getQuantity());
  1966. } else {
  1967. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1968. GV->setAlignment(Align.getQuantity());
  1969. }
  1970. // String.
  1971. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1972. if (isUTF16)
  1973. // Cast the UTF16 string to the correct type.
  1974. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1975. // String length.
  1976. Ty = getTypes().ConvertType(getContext().LongTy);
  1977. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1978. // The struct.
  1979. C = llvm::ConstantStruct::get(STy, Fields);
  1980. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1981. llvm::GlobalVariable::PrivateLinkage, C,
  1982. "_unnamed_cfstring_");
  1983. if (const char *Sect = getTarget().getCFStringSection())
  1984. GV->setSection(Sect);
  1985. Entry.setValue(GV);
  1986. return GV;
  1987. }
  1988. static RecordDecl *
  1989. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1990. DeclContext *DC, IdentifierInfo *Id) {
  1991. SourceLocation Loc;
  1992. if (Ctx.getLangOpts().CPlusPlus)
  1993. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1994. else
  1995. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1996. }
  1997. llvm::Constant *
  1998. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1999. unsigned StringLength = 0;
  2000. llvm::StringMapEntry<llvm::Constant*> &Entry =
  2001. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2002. if (llvm::Constant *C = Entry.getValue())
  2003. return C;
  2004. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2005. llvm::Constant *Zeros[] = { Zero, Zero };
  2006. llvm::Value *V;
  2007. // If we don't already have it, get _NSConstantStringClassReference.
  2008. if (!ConstantStringClassRef) {
  2009. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2010. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2011. llvm::Constant *GV;
  2012. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2013. std::string str =
  2014. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2015. : "OBJC_CLASS_$_" + StringClass;
  2016. GV = getObjCRuntime().GetClassGlobal(str);
  2017. // Make sure the result is of the correct type.
  2018. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2019. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2020. ConstantStringClassRef = V;
  2021. } else {
  2022. std::string str =
  2023. StringClass.empty() ? "_NSConstantStringClassReference"
  2024. : "_" + StringClass + "ClassReference";
  2025. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2026. GV = CreateRuntimeVariable(PTy, str);
  2027. // Decay array -> ptr
  2028. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2029. ConstantStringClassRef = V;
  2030. }
  2031. }
  2032. else
  2033. V = ConstantStringClassRef;
  2034. if (!NSConstantStringType) {
  2035. // Construct the type for a constant NSString.
  2036. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  2037. Context.getTranslationUnitDecl(),
  2038. &Context.Idents.get("__builtin_NSString"));
  2039. D->startDefinition();
  2040. QualType FieldTypes[3];
  2041. // const int *isa;
  2042. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2043. // const char *str;
  2044. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2045. // unsigned int length;
  2046. FieldTypes[2] = Context.UnsignedIntTy;
  2047. // Create fields
  2048. for (unsigned i = 0; i < 3; ++i) {
  2049. FieldDecl *Field = FieldDecl::Create(Context, D,
  2050. SourceLocation(),
  2051. SourceLocation(), 0,
  2052. FieldTypes[i], /*TInfo=*/0,
  2053. /*BitWidth=*/0,
  2054. /*Mutable=*/false,
  2055. ICIS_NoInit);
  2056. Field->setAccess(AS_public);
  2057. D->addDecl(Field);
  2058. }
  2059. D->completeDefinition();
  2060. QualType NSTy = Context.getTagDeclType(D);
  2061. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2062. }
  2063. llvm::Constant *Fields[3];
  2064. // Class pointer.
  2065. Fields[0] = cast<llvm::ConstantExpr>(V);
  2066. // String pointer.
  2067. llvm::Constant *C =
  2068. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  2069. llvm::GlobalValue::LinkageTypes Linkage;
  2070. bool isConstant;
  2071. Linkage = llvm::GlobalValue::PrivateLinkage;
  2072. isConstant = !LangOpts.WritableStrings;
  2073. llvm::GlobalVariable *GV =
  2074. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  2075. ".str");
  2076. GV->setUnnamedAddr(true);
  2077. // Don't enforce the target's minimum global alignment, since the only use
  2078. // of the string is via this class initializer.
  2079. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2080. GV->setAlignment(Align.getQuantity());
  2081. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2082. // String length.
  2083. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2084. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2085. // The struct.
  2086. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2087. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2088. llvm::GlobalVariable::PrivateLinkage, C,
  2089. "_unnamed_nsstring_");
  2090. // FIXME. Fix section.
  2091. if (const char *Sect =
  2092. LangOpts.ObjCRuntime.isNonFragile()
  2093. ? getTarget().getNSStringNonFragileABISection()
  2094. : getTarget().getNSStringSection())
  2095. GV->setSection(Sect);
  2096. Entry.setValue(GV);
  2097. return GV;
  2098. }
  2099. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2100. if (ObjCFastEnumerationStateType.isNull()) {
  2101. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  2102. Context.getTranslationUnitDecl(),
  2103. &Context.Idents.get("__objcFastEnumerationState"));
  2104. D->startDefinition();
  2105. QualType FieldTypes[] = {
  2106. Context.UnsignedLongTy,
  2107. Context.getPointerType(Context.getObjCIdType()),
  2108. Context.getPointerType(Context.UnsignedLongTy),
  2109. Context.getConstantArrayType(Context.UnsignedLongTy,
  2110. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2111. };
  2112. for (size_t i = 0; i < 4; ++i) {
  2113. FieldDecl *Field = FieldDecl::Create(Context,
  2114. D,
  2115. SourceLocation(),
  2116. SourceLocation(), 0,
  2117. FieldTypes[i], /*TInfo=*/0,
  2118. /*BitWidth=*/0,
  2119. /*Mutable=*/false,
  2120. ICIS_NoInit);
  2121. Field->setAccess(AS_public);
  2122. D->addDecl(Field);
  2123. }
  2124. D->completeDefinition();
  2125. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2126. }
  2127. return ObjCFastEnumerationStateType;
  2128. }
  2129. llvm::Constant *
  2130. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2131. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2132. // Don't emit it as the address of the string, emit the string data itself
  2133. // as an inline array.
  2134. if (E->getCharByteWidth() == 1) {
  2135. SmallString<64> Str(E->getString());
  2136. // Resize the string to the right size, which is indicated by its type.
  2137. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2138. Str.resize(CAT->getSize().getZExtValue());
  2139. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2140. }
  2141. llvm::ArrayType *AType =
  2142. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2143. llvm::Type *ElemTy = AType->getElementType();
  2144. unsigned NumElements = AType->getNumElements();
  2145. // Wide strings have either 2-byte or 4-byte elements.
  2146. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2147. SmallVector<uint16_t, 32> Elements;
  2148. Elements.reserve(NumElements);
  2149. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2150. Elements.push_back(E->getCodeUnit(i));
  2151. Elements.resize(NumElements);
  2152. return llvm::ConstantDataArray::get(VMContext, Elements);
  2153. }
  2154. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2155. SmallVector<uint32_t, 32> Elements;
  2156. Elements.reserve(NumElements);
  2157. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2158. Elements.push_back(E->getCodeUnit(i));
  2159. Elements.resize(NumElements);
  2160. return llvm::ConstantDataArray::get(VMContext, Elements);
  2161. }
  2162. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2163. /// constant array for the given string literal.
  2164. llvm::Constant *
  2165. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  2166. CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
  2167. if (S->isAscii() || S->isUTF8()) {
  2168. SmallString<64> Str(S->getString());
  2169. // Resize the string to the right size, which is indicated by its type.
  2170. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  2171. Str.resize(CAT->getSize().getZExtValue());
  2172. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  2173. }
  2174. // FIXME: the following does not memoize wide strings.
  2175. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2176. llvm::GlobalVariable *GV =
  2177. new llvm::GlobalVariable(getModule(),C->getType(),
  2178. !LangOpts.WritableStrings,
  2179. llvm::GlobalValue::PrivateLinkage,
  2180. C,".str");
  2181. GV->setAlignment(Align.getQuantity());
  2182. GV->setUnnamedAddr(true);
  2183. return GV;
  2184. }
  2185. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2186. /// array for the given ObjCEncodeExpr node.
  2187. llvm::Constant *
  2188. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2189. std::string Str;
  2190. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2191. return GetAddrOfConstantCString(Str);
  2192. }
  2193. /// GenerateWritableString -- Creates storage for a string literal.
  2194. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  2195. bool constant,
  2196. CodeGenModule &CGM,
  2197. const char *GlobalName,
  2198. unsigned Alignment) {
  2199. // Create Constant for this string literal. Don't add a '\0'.
  2200. llvm::Constant *C =
  2201. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  2202. // Create a global variable for this string
  2203. llvm::GlobalVariable *GV =
  2204. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  2205. llvm::GlobalValue::PrivateLinkage,
  2206. C, GlobalName);
  2207. GV->setAlignment(Alignment);
  2208. GV->setUnnamedAddr(true);
  2209. return GV;
  2210. }
  2211. /// GetAddrOfConstantString - Returns a pointer to a character array
  2212. /// containing the literal. This contents are exactly that of the
  2213. /// given string, i.e. it will not be null terminated automatically;
  2214. /// see GetAddrOfConstantCString. Note that whether the result is
  2215. /// actually a pointer to an LLVM constant depends on
  2216. /// Feature.WriteableStrings.
  2217. ///
  2218. /// The result has pointer to array type.
  2219. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2220. const char *GlobalName,
  2221. unsigned Alignment) {
  2222. // Get the default prefix if a name wasn't specified.
  2223. if (!GlobalName)
  2224. GlobalName = ".str";
  2225. if (Alignment == 0)
  2226. Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
  2227. .getQuantity();
  2228. // Don't share any string literals if strings aren't constant.
  2229. if (LangOpts.WritableStrings)
  2230. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2231. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2232. ConstantStringMap.GetOrCreateValue(Str);
  2233. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2234. if (Alignment > GV->getAlignment()) {
  2235. GV->setAlignment(Alignment);
  2236. }
  2237. return GV;
  2238. }
  2239. // Create a global variable for this.
  2240. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2241. Alignment);
  2242. Entry.setValue(GV);
  2243. return GV;
  2244. }
  2245. /// GetAddrOfConstantCString - Returns a pointer to a character
  2246. /// array containing the literal and a terminating '\0'
  2247. /// character. The result has pointer to array type.
  2248. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2249. const char *GlobalName,
  2250. unsigned Alignment) {
  2251. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2252. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2253. }
  2254. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2255. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2256. assert((E->getStorageDuration() == SD_Static ||
  2257. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2258. const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
  2259. // If we're not materializing a subobject of the temporary, keep the
  2260. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2261. QualType MaterializedType = Init->getType();
  2262. if (Init == E->GetTemporaryExpr())
  2263. MaterializedType = E->getType();
  2264. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2265. if (Slot)
  2266. return Slot;
  2267. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2268. // we need to give each temporary the same name in every translation unit (and
  2269. // we also need to make the temporaries externally-visible).
  2270. SmallString<256> Name;
  2271. llvm::raw_svector_ostream Out(Name);
  2272. getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
  2273. Out.flush();
  2274. APValue *Value = 0;
  2275. if (E->getStorageDuration() == SD_Static) {
  2276. // We might have a cached constant initializer for this temporary. Note
  2277. // that this might have a different value from the value computed by
  2278. // evaluating the initializer if the surrounding constant expression
  2279. // modifies the temporary.
  2280. Value = getContext().getMaterializedTemporaryValue(E, false);
  2281. if (Value && Value->isUninit())
  2282. Value = 0;
  2283. }
  2284. // Try evaluating it now, it might have a constant initializer.
  2285. Expr::EvalResult EvalResult;
  2286. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2287. !EvalResult.hasSideEffects())
  2288. Value = &EvalResult.Val;
  2289. llvm::Constant *InitialValue = 0;
  2290. bool Constant = false;
  2291. llvm::Type *Type;
  2292. if (Value) {
  2293. // The temporary has a constant initializer, use it.
  2294. InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
  2295. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2296. Type = InitialValue->getType();
  2297. } else {
  2298. // No initializer, the initialization will be provided when we
  2299. // initialize the declaration which performed lifetime extension.
  2300. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2301. }
  2302. // Create a global variable for this lifetime-extended temporary.
  2303. llvm::GlobalVariable *GV =
  2304. new llvm::GlobalVariable(getModule(), Type, Constant,
  2305. llvm::GlobalValue::PrivateLinkage,
  2306. InitialValue, Name.c_str());
  2307. GV->setAlignment(
  2308. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2309. if (VD->getTLSKind())
  2310. setTLSMode(GV, *VD);
  2311. Slot = GV;
  2312. return GV;
  2313. }
  2314. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2315. /// properties for an implementation.
  2316. void CodeGenModule::EmitObjCPropertyImplementations(const
  2317. ObjCImplementationDecl *D) {
  2318. for (ObjCImplementationDecl::propimpl_iterator
  2319. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2320. ObjCPropertyImplDecl *PID = *i;
  2321. // Dynamic is just for type-checking.
  2322. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2323. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2324. // Determine which methods need to be implemented, some may have
  2325. // been overridden. Note that ::isPropertyAccessor is not the method
  2326. // we want, that just indicates if the decl came from a
  2327. // property. What we want to know is if the method is defined in
  2328. // this implementation.
  2329. if (!D->getInstanceMethod(PD->getGetterName()))
  2330. CodeGenFunction(*this).GenerateObjCGetter(
  2331. const_cast<ObjCImplementationDecl *>(D), PID);
  2332. if (!PD->isReadOnly() &&
  2333. !D->getInstanceMethod(PD->getSetterName()))
  2334. CodeGenFunction(*this).GenerateObjCSetter(
  2335. const_cast<ObjCImplementationDecl *>(D), PID);
  2336. }
  2337. }
  2338. }
  2339. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2340. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2341. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2342. ivar; ivar = ivar->getNextIvar())
  2343. if (ivar->getType().isDestructedType())
  2344. return true;
  2345. return false;
  2346. }
  2347. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2348. /// for an implementation.
  2349. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2350. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2351. if (needsDestructMethod(D)) {
  2352. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2353. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2354. ObjCMethodDecl *DTORMethod =
  2355. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2356. cxxSelector, getContext().VoidTy, 0, D,
  2357. /*isInstance=*/true, /*isVariadic=*/false,
  2358. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2359. /*isDefined=*/false, ObjCMethodDecl::Required);
  2360. D->addInstanceMethod(DTORMethod);
  2361. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2362. D->setHasDestructors(true);
  2363. }
  2364. // If the implementation doesn't have any ivar initializers, we don't need
  2365. // a .cxx_construct.
  2366. if (D->getNumIvarInitializers() == 0)
  2367. return;
  2368. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2369. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2370. // The constructor returns 'self'.
  2371. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2372. D->getLocation(),
  2373. D->getLocation(),
  2374. cxxSelector,
  2375. getContext().getObjCIdType(), 0,
  2376. D, /*isInstance=*/true,
  2377. /*isVariadic=*/false,
  2378. /*isPropertyAccessor=*/true,
  2379. /*isImplicitlyDeclared=*/true,
  2380. /*isDefined=*/false,
  2381. ObjCMethodDecl::Required);
  2382. D->addInstanceMethod(CTORMethod);
  2383. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2384. D->setHasNonZeroConstructors(true);
  2385. }
  2386. /// EmitNamespace - Emit all declarations in a namespace.
  2387. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2388. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2389. I != E; ++I) {
  2390. if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
  2391. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2392. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2393. continue;
  2394. EmitTopLevelDecl(*I);
  2395. }
  2396. }
  2397. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2398. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2399. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2400. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2401. ErrorUnsupported(LSD, "linkage spec");
  2402. return;
  2403. }
  2404. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2405. I != E; ++I) {
  2406. // Meta-data for ObjC class includes references to implemented methods.
  2407. // Generate class's method definitions first.
  2408. if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
  2409. for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
  2410. MEnd = OID->meth_end();
  2411. M != MEnd; ++M)
  2412. EmitTopLevelDecl(*M);
  2413. }
  2414. EmitTopLevelDecl(*I);
  2415. }
  2416. }
  2417. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2418. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2419. // Ignore dependent declarations.
  2420. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2421. return;
  2422. switch (D->getKind()) {
  2423. case Decl::CXXConversion:
  2424. case Decl::CXXMethod:
  2425. case Decl::Function:
  2426. // Skip function templates
  2427. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2428. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2429. return;
  2430. EmitGlobal(cast<FunctionDecl>(D));
  2431. break;
  2432. case Decl::Var:
  2433. // Skip variable templates
  2434. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2435. return;
  2436. case Decl::VarTemplateSpecialization:
  2437. EmitGlobal(cast<VarDecl>(D));
  2438. break;
  2439. // Indirect fields from global anonymous structs and unions can be
  2440. // ignored; only the actual variable requires IR gen support.
  2441. case Decl::IndirectField:
  2442. break;
  2443. // C++ Decls
  2444. case Decl::Namespace:
  2445. EmitNamespace(cast<NamespaceDecl>(D));
  2446. break;
  2447. // No code generation needed.
  2448. case Decl::UsingShadow:
  2449. case Decl::Using:
  2450. case Decl::ClassTemplate:
  2451. case Decl::VarTemplate:
  2452. case Decl::VarTemplatePartialSpecialization:
  2453. case Decl::FunctionTemplate:
  2454. case Decl::TypeAliasTemplate:
  2455. case Decl::Block:
  2456. case Decl::Empty:
  2457. break;
  2458. case Decl::NamespaceAlias:
  2459. if (CGDebugInfo *DI = getModuleDebugInfo())
  2460. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2461. return;
  2462. case Decl::UsingDirective: // using namespace X; [C++]
  2463. if (CGDebugInfo *DI = getModuleDebugInfo())
  2464. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2465. return;
  2466. case Decl::CXXConstructor:
  2467. // Skip function templates
  2468. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2469. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2470. return;
  2471. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2472. break;
  2473. case Decl::CXXDestructor:
  2474. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2475. return;
  2476. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2477. break;
  2478. case Decl::StaticAssert:
  2479. // Nothing to do.
  2480. break;
  2481. // Objective-C Decls
  2482. // Forward declarations, no (immediate) code generation.
  2483. case Decl::ObjCInterface:
  2484. case Decl::ObjCCategory:
  2485. break;
  2486. case Decl::ObjCProtocol: {
  2487. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2488. if (Proto->isThisDeclarationADefinition())
  2489. ObjCRuntime->GenerateProtocol(Proto);
  2490. break;
  2491. }
  2492. case Decl::ObjCCategoryImpl:
  2493. // Categories have properties but don't support synthesize so we
  2494. // can ignore them here.
  2495. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2496. break;
  2497. case Decl::ObjCImplementation: {
  2498. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2499. EmitObjCPropertyImplementations(OMD);
  2500. EmitObjCIvarInitializations(OMD);
  2501. ObjCRuntime->GenerateClass(OMD);
  2502. // Emit global variable debug information.
  2503. if (CGDebugInfo *DI = getModuleDebugInfo())
  2504. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2505. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2506. OMD->getClassInterface()), OMD->getLocation());
  2507. break;
  2508. }
  2509. case Decl::ObjCMethod: {
  2510. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2511. // If this is not a prototype, emit the body.
  2512. if (OMD->getBody())
  2513. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2514. break;
  2515. }
  2516. case Decl::ObjCCompatibleAlias:
  2517. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2518. break;
  2519. case Decl::LinkageSpec:
  2520. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2521. break;
  2522. case Decl::FileScopeAsm: {
  2523. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2524. StringRef AsmString = AD->getAsmString()->getString();
  2525. const std::string &S = getModule().getModuleInlineAsm();
  2526. if (S.empty())
  2527. getModule().setModuleInlineAsm(AsmString);
  2528. else if (S.end()[-1] == '\n')
  2529. getModule().setModuleInlineAsm(S + AsmString.str());
  2530. else
  2531. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2532. break;
  2533. }
  2534. case Decl::Import: {
  2535. ImportDecl *Import = cast<ImportDecl>(D);
  2536. // Ignore import declarations that come from imported modules.
  2537. if (clang::Module *Owner = Import->getOwningModule()) {
  2538. if (getLangOpts().CurrentModule.empty() ||
  2539. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  2540. break;
  2541. }
  2542. ImportedModules.insert(Import->getImportedModule());
  2543. break;
  2544. }
  2545. default:
  2546. // Make sure we handled everything we should, every other kind is a
  2547. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2548. // function. Need to recode Decl::Kind to do that easily.
  2549. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2550. }
  2551. }
  2552. /// Turns the given pointer into a constant.
  2553. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2554. const void *Ptr) {
  2555. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2556. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2557. return llvm::ConstantInt::get(i64, PtrInt);
  2558. }
  2559. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2560. llvm::NamedMDNode *&GlobalMetadata,
  2561. GlobalDecl D,
  2562. llvm::GlobalValue *Addr) {
  2563. if (!GlobalMetadata)
  2564. GlobalMetadata =
  2565. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2566. // TODO: should we report variant information for ctors/dtors?
  2567. llvm::Value *Ops[] = {
  2568. Addr,
  2569. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2570. };
  2571. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2572. }
  2573. /// For each function which is declared within an extern "C" region and marked
  2574. /// as 'used', but has internal linkage, create an alias from the unmangled
  2575. /// name to the mangled name if possible. People expect to be able to refer
  2576. /// to such functions with an unmangled name from inline assembly within the
  2577. /// same translation unit.
  2578. void CodeGenModule::EmitStaticExternCAliases() {
  2579. for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
  2580. E = StaticExternCValues.end();
  2581. I != E; ++I) {
  2582. IdentifierInfo *Name = I->first;
  2583. llvm::GlobalValue *Val = I->second;
  2584. if (Val && !getModule().getNamedValue(Name->getName()))
  2585. AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
  2586. Name->getName(), Val, &getModule()));
  2587. }
  2588. }
  2589. /// Emits metadata nodes associating all the global values in the
  2590. /// current module with the Decls they came from. This is useful for
  2591. /// projects using IR gen as a subroutine.
  2592. ///
  2593. /// Since there's currently no way to associate an MDNode directly
  2594. /// with an llvm::GlobalValue, we create a global named metadata
  2595. /// with the name 'clang.global.decl.ptrs'.
  2596. void CodeGenModule::EmitDeclMetadata() {
  2597. llvm::NamedMDNode *GlobalMetadata = 0;
  2598. // StaticLocalDeclMap
  2599. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2600. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2601. I != E; ++I) {
  2602. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2603. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2604. }
  2605. }
  2606. /// Emits metadata nodes for all the local variables in the current
  2607. /// function.
  2608. void CodeGenFunction::EmitDeclMetadata() {
  2609. if (LocalDeclMap.empty()) return;
  2610. llvm::LLVMContext &Context = getLLVMContext();
  2611. // Find the unique metadata ID for this name.
  2612. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2613. llvm::NamedMDNode *GlobalMetadata = 0;
  2614. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2615. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2616. const Decl *D = I->first;
  2617. llvm::Value *Addr = I->second;
  2618. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2619. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2620. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2621. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2622. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2623. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2624. }
  2625. }
  2626. }
  2627. void CodeGenModule::EmitVersionIdentMetadata() {
  2628. llvm::NamedMDNode *IdentMetadata =
  2629. TheModule.getOrInsertNamedMetadata("llvm.ident");
  2630. std::string Version = getClangFullVersion();
  2631. llvm::LLVMContext &Ctx = TheModule.getContext();
  2632. llvm::Value *IdentNode[] = {
  2633. llvm::MDString::get(Ctx, Version)
  2634. };
  2635. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  2636. }
  2637. void CodeGenModule::EmitCoverageFile() {
  2638. if (!getCodeGenOpts().CoverageFile.empty()) {
  2639. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2640. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2641. llvm::LLVMContext &Ctx = TheModule.getContext();
  2642. llvm::MDString *CoverageFile =
  2643. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2644. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2645. llvm::MDNode *CU = CUNode->getOperand(i);
  2646. llvm::Value *node[] = { CoverageFile, CU };
  2647. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2648. GCov->addOperand(N);
  2649. }
  2650. }
  2651. }
  2652. }
  2653. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
  2654. QualType GuidType) {
  2655. // Sema has checked that all uuid strings are of the form
  2656. // "12345678-1234-1234-1234-1234567890ab".
  2657. assert(Uuid.size() == 36);
  2658. for (unsigned i = 0; i < 36; ++i) {
  2659. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  2660. else assert(isHexDigit(Uuid[i]));
  2661. }
  2662. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  2663. llvm::Constant *Field3[8];
  2664. for (unsigned Idx = 0; Idx < 8; ++Idx)
  2665. Field3[Idx] = llvm::ConstantInt::get(
  2666. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  2667. llvm::Constant *Fields[4] = {
  2668. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  2669. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  2670. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  2671. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  2672. };
  2673. return llvm::ConstantStruct::getAnon(Fields);
  2674. }