CodeGenModule.cpp 142 KB

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