CodeGenModule.cpp 123 KB

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