CodeGenModule.cpp 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012
  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 "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "ConstantEmitter.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/CodeGen/ConstantInitBuilder.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/IR/CallSite.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/ProfileData/InstrProfReader.h"
  55. #include "llvm/Support/ConvertUTF.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/MD5.h"
  58. using namespace clang;
  59. using namespace CodeGen;
  60. static llvm::cl::opt<bool> LimitedCoverage(
  61. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  62. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  63. llvm::cl::init(false));
  64. static const char AnnotationSection[] = "llvm.metadata";
  65. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  66. switch (CGM.getTarget().getCXXABI().getKind()) {
  67. case TargetCXXABI::GenericAArch64:
  68. case TargetCXXABI::GenericARM:
  69. case TargetCXXABI::iOS:
  70. case TargetCXXABI::iOS64:
  71. case TargetCXXABI::WatchOS:
  72. case TargetCXXABI::GenericMIPS:
  73. case TargetCXXABI::GenericItanium:
  74. case TargetCXXABI::WebAssembly:
  75. return CreateItaniumCXXABI(CGM);
  76. case TargetCXXABI::Microsoft:
  77. return CreateMicrosoftCXXABI(CGM);
  78. }
  79. llvm_unreachable("invalid C++ ABI kind");
  80. }
  81. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  82. const PreprocessorOptions &PPO,
  83. const CodeGenOptions &CGO, llvm::Module &M,
  84. DiagnosticsEngine &diags,
  85. CoverageSourceInfo *CoverageInfo)
  86. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  87. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  88. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  89. VMContext(M.getContext()), Types(*this), VTables(*this),
  90. SanitizerMD(new SanitizerMetadata(*this)) {
  91. // Initialize the type cache.
  92. llvm::LLVMContext &LLVMContext = M.getContext();
  93. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  94. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  95. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  96. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  97. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  98. HalfTy = llvm::Type::getHalfTy(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. SizeSizeInBytes =
  105. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  106. IntAlignInBytes =
  107. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  108. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  109. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  110. C.getTargetInfo().getMaxPointerWidth());
  111. Int8PtrTy = Int8Ty->getPointerTo(0);
  112. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  113. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  114. M.getDataLayout().getAllocaAddrSpace());
  115. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  116. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  117. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  118. if (LangOpts.ObjC1)
  119. createObjCRuntime();
  120. if (LangOpts.OpenCL)
  121. createOpenCLRuntime();
  122. if (LangOpts.OpenMP)
  123. createOpenMPRuntime();
  124. if (LangOpts.CUDA)
  125. createCUDARuntime();
  126. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  127. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  128. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  129. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  130. getCXXABI().getMangleContext()));
  131. // If debug info or coverage generation is enabled, create the CGDebugInfo
  132. // object.
  133. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  134. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  135. DebugInfo.reset(new CGDebugInfo(*this));
  136. Block.GlobalUniqueCount = 0;
  137. if (C.getLangOpts().ObjC1)
  138. ObjCData.reset(new ObjCEntrypoints());
  139. if (CodeGenOpts.hasProfileClangUse()) {
  140. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  141. CodeGenOpts.ProfileInstrumentUsePath);
  142. if (auto E = ReaderOrErr.takeError()) {
  143. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  144. "Could not read profile %0: %1");
  145. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  146. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  147. << EI.message();
  148. });
  149. } else
  150. PGOReader = std::move(ReaderOrErr.get());
  151. }
  152. // If coverage mapping generation is enabled, create the
  153. // CoverageMappingModuleGen object.
  154. if (CodeGenOpts.CoverageMapping)
  155. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  156. }
  157. CodeGenModule::~CodeGenModule() {}
  158. void CodeGenModule::createObjCRuntime() {
  159. // This is just isGNUFamily(), but we want to force implementors of
  160. // new ABIs to decide how best to do this.
  161. switch (LangOpts.ObjCRuntime.getKind()) {
  162. case ObjCRuntime::GNUstep:
  163. case ObjCRuntime::GCC:
  164. case ObjCRuntime::ObjFW:
  165. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  166. return;
  167. case ObjCRuntime::FragileMacOSX:
  168. case ObjCRuntime::MacOSX:
  169. case ObjCRuntime::iOS:
  170. case ObjCRuntime::WatchOS:
  171. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  172. return;
  173. }
  174. llvm_unreachable("bad runtime kind");
  175. }
  176. void CodeGenModule::createOpenCLRuntime() {
  177. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  178. }
  179. void CodeGenModule::createOpenMPRuntime() {
  180. // Select a specialized code generation class based on the target, if any.
  181. // If it does not exist use the default implementation.
  182. switch (getTriple().getArch()) {
  183. case llvm::Triple::nvptx:
  184. case llvm::Triple::nvptx64:
  185. assert(getLangOpts().OpenMPIsDevice &&
  186. "OpenMP NVPTX is only prepared to deal with device code.");
  187. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  188. break;
  189. default:
  190. if (LangOpts.OpenMPSimd)
  191. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  192. else
  193. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  194. break;
  195. }
  196. }
  197. void CodeGenModule::createCUDARuntime() {
  198. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  199. }
  200. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  201. Replacements[Name] = C;
  202. }
  203. void CodeGenModule::applyReplacements() {
  204. for (auto &I : Replacements) {
  205. StringRef MangledName = I.first();
  206. llvm::Constant *Replacement = I.second;
  207. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  208. if (!Entry)
  209. continue;
  210. auto *OldF = cast<llvm::Function>(Entry);
  211. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  212. if (!NewF) {
  213. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  214. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  215. } else {
  216. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  217. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  218. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  219. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  220. }
  221. }
  222. // Replace old with new, but keep the old order.
  223. OldF->replaceAllUsesWith(Replacement);
  224. if (NewF) {
  225. NewF->removeFromParent();
  226. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  227. NewF);
  228. }
  229. OldF->eraseFromParent();
  230. }
  231. }
  232. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  233. GlobalValReplacements.push_back(std::make_pair(GV, C));
  234. }
  235. void CodeGenModule::applyGlobalValReplacements() {
  236. for (auto &I : GlobalValReplacements) {
  237. llvm::GlobalValue *GV = I.first;
  238. llvm::Constant *C = I.second;
  239. GV->replaceAllUsesWith(C);
  240. GV->eraseFromParent();
  241. }
  242. }
  243. // This is only used in aliases that we created and we know they have a
  244. // linear structure.
  245. static const llvm::GlobalObject *getAliasedGlobal(
  246. const llvm::GlobalIndirectSymbol &GIS) {
  247. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  248. const llvm::Constant *C = &GIS;
  249. for (;;) {
  250. C = C->stripPointerCasts();
  251. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  252. return GO;
  253. // stripPointerCasts will not walk over weak aliases.
  254. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  255. if (!GIS2)
  256. return nullptr;
  257. if (!Visited.insert(GIS2).second)
  258. return nullptr;
  259. C = GIS2->getIndirectSymbol();
  260. }
  261. }
  262. void CodeGenModule::checkAliases() {
  263. // Check if the constructed aliases are well formed. It is really unfortunate
  264. // that we have to do this in CodeGen, but we only construct mangled names
  265. // and aliases during codegen.
  266. bool Error = false;
  267. DiagnosticsEngine &Diags = getDiags();
  268. for (const GlobalDecl &GD : Aliases) {
  269. const auto *D = cast<ValueDecl>(GD.getDecl());
  270. SourceLocation Location;
  271. bool IsIFunc = D->hasAttr<IFuncAttr>();
  272. if (const Attr *A = D->getDefiningAttr())
  273. Location = A->getLocation();
  274. else
  275. llvm_unreachable("Not an alias or ifunc?");
  276. StringRef MangledName = getMangledName(GD);
  277. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  278. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  279. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  280. if (!GV) {
  281. Error = true;
  282. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  283. } else if (GV->isDeclaration()) {
  284. Error = true;
  285. Diags.Report(Location, diag::err_alias_to_undefined)
  286. << IsIFunc << IsIFunc;
  287. } else if (IsIFunc) {
  288. // Check resolver function type.
  289. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  290. GV->getType()->getPointerElementType());
  291. assert(FTy);
  292. if (!FTy->getReturnType()->isPointerTy())
  293. Diags.Report(Location, diag::err_ifunc_resolver_return);
  294. if (FTy->getNumParams())
  295. Diags.Report(Location, diag::err_ifunc_resolver_params);
  296. }
  297. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  298. llvm::GlobalValue *AliaseeGV;
  299. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  300. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  301. else
  302. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  303. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  304. StringRef AliasSection = SA->getName();
  305. if (AliasSection != AliaseeGV->getSection())
  306. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  307. << AliasSection << IsIFunc << IsIFunc;
  308. }
  309. // We have to handle alias to weak aliases in here. LLVM itself disallows
  310. // this since the object semantics would not match the IL one. For
  311. // compatibility with gcc we implement it by just pointing the alias
  312. // to its aliasee's aliasee. We also warn, since the user is probably
  313. // expecting the link to be weak.
  314. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  315. if (GA->isInterposable()) {
  316. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  317. << GV->getName() << GA->getName() << IsIFunc;
  318. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  319. GA->getIndirectSymbol(), Alias->getType());
  320. Alias->setIndirectSymbol(Aliasee);
  321. }
  322. }
  323. }
  324. if (!Error)
  325. return;
  326. for (const GlobalDecl &GD : Aliases) {
  327. StringRef MangledName = getMangledName(GD);
  328. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  329. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  330. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  331. Alias->eraseFromParent();
  332. }
  333. }
  334. void CodeGenModule::clear() {
  335. DeferredDeclsToEmit.clear();
  336. if (OpenMPRuntime)
  337. OpenMPRuntime->clear();
  338. }
  339. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  340. StringRef MainFile) {
  341. if (!hasDiagnostics())
  342. return;
  343. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  344. if (MainFile.empty())
  345. MainFile = "<stdin>";
  346. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  347. } else {
  348. if (Mismatched > 0)
  349. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  350. if (Missing > 0)
  351. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  352. }
  353. }
  354. void CodeGenModule::Release() {
  355. EmitDeferred();
  356. EmitVTablesOpportunistically();
  357. applyGlobalValReplacements();
  358. applyReplacements();
  359. checkAliases();
  360. emitMultiVersionFunctions();
  361. EmitCXXGlobalInitFunc();
  362. EmitCXXGlobalDtorFunc();
  363. EmitCXXThreadLocalInitFunc();
  364. if (ObjCRuntime)
  365. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  366. AddGlobalCtor(ObjCInitFunction);
  367. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  368. CUDARuntime) {
  369. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  370. AddGlobalCtor(CudaCtorFunction);
  371. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  372. AddGlobalDtor(CudaDtorFunction);
  373. }
  374. if (OpenMPRuntime)
  375. if (llvm::Function *OpenMPRegistrationFunction =
  376. OpenMPRuntime->emitRegistrationFunction()) {
  377. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  378. OpenMPRegistrationFunction : nullptr;
  379. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  380. }
  381. if (PGOReader) {
  382. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  383. if (PGOStats.hasDiagnostics())
  384. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  385. }
  386. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  387. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  388. EmitGlobalAnnotations();
  389. EmitStaticExternCAliases();
  390. EmitDeferredUnusedCoverageMappings();
  391. if (CoverageMapping)
  392. CoverageMapping->emit();
  393. if (CodeGenOpts.SanitizeCfiCrossDso) {
  394. CodeGenFunction(*this).EmitCfiCheckFail();
  395. CodeGenFunction(*this).EmitCfiCheckStub();
  396. }
  397. emitAtAvailableLinkGuard();
  398. emitLLVMUsed();
  399. if (SanStats)
  400. SanStats->finish();
  401. if (CodeGenOpts.Autolink &&
  402. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  403. EmitModuleLinkOptions();
  404. }
  405. // Record mregparm value now so it is visible through rest of codegen.
  406. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  407. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  408. CodeGenOpts.NumRegisterParameters);
  409. if (CodeGenOpts.DwarfVersion) {
  410. // We actually want the latest version when there are conflicts.
  411. // We can change from Warning to Latest if such mode is supported.
  412. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  413. CodeGenOpts.DwarfVersion);
  414. }
  415. if (CodeGenOpts.EmitCodeView) {
  416. // Indicate that we want CodeView in the metadata.
  417. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  418. }
  419. if (CodeGenOpts.ControlFlowGuard) {
  420. // We want function ID tables for Control Flow Guard.
  421. getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
  422. }
  423. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  424. // We don't support LTO with 2 with different StrictVTablePointers
  425. // FIXME: we could support it by stripping all the information introduced
  426. // by StrictVTablePointers.
  427. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  428. llvm::Metadata *Ops[2] = {
  429. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  430. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  431. llvm::Type::getInt32Ty(VMContext), 1))};
  432. getModule().addModuleFlag(llvm::Module::Require,
  433. "StrictVTablePointersRequirement",
  434. llvm::MDNode::get(VMContext, Ops));
  435. }
  436. if (DebugInfo)
  437. // We support a single version in the linked module. The LLVM
  438. // parser will drop debug info with a different version number
  439. // (and warn about it, too).
  440. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  441. llvm::DEBUG_METADATA_VERSION);
  442. // We need to record the widths of enums and wchar_t, so that we can generate
  443. // the correct build attributes in the ARM backend. wchar_size is also used by
  444. // TargetLibraryInfo.
  445. uint64_t WCharWidth =
  446. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  447. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  448. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  449. if ( Arch == llvm::Triple::arm
  450. || Arch == llvm::Triple::armeb
  451. || Arch == llvm::Triple::thumb
  452. || Arch == llvm::Triple::thumbeb) {
  453. // The minimum width of an enum in bytes
  454. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  455. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  456. }
  457. if (CodeGenOpts.SanitizeCfiCrossDso) {
  458. // Indicate that we want cross-DSO control flow integrity checks.
  459. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  460. }
  461. if (CodeGenOpts.CFProtectionReturn &&
  462. Target.checkCFProtectionReturnSupported(getDiags())) {
  463. // Indicate that we want to instrument return control flow protection.
  464. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  465. 1);
  466. }
  467. if (CodeGenOpts.CFProtectionBranch &&
  468. Target.checkCFProtectionBranchSupported(getDiags())) {
  469. // Indicate that we want to instrument branch control flow protection.
  470. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  471. 1);
  472. }
  473. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  474. // Indicate whether __nvvm_reflect should be configured to flush denormal
  475. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  476. // property.)
  477. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  478. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  479. }
  480. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  481. if (LangOpts.OpenCL) {
  482. EmitOpenCLMetadata();
  483. // Emit SPIR version.
  484. if (getTriple().getArch() == llvm::Triple::spir ||
  485. getTriple().getArch() == llvm::Triple::spir64) {
  486. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  487. // opencl.spir.version named metadata.
  488. llvm::Metadata *SPIRVerElts[] = {
  489. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  490. Int32Ty, LangOpts.OpenCLVersion / 100)),
  491. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  492. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  493. llvm::NamedMDNode *SPIRVerMD =
  494. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  495. llvm::LLVMContext &Ctx = TheModule.getContext();
  496. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  497. }
  498. }
  499. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  500. assert(PLevel < 3 && "Invalid PIC Level");
  501. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  502. if (Context.getLangOpts().PIE)
  503. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  504. }
  505. if (CodeGenOpts.NoPLT)
  506. getModule().setRtLibUseGOT();
  507. SimplifyPersonality();
  508. if (getCodeGenOpts().EmitDeclMetadata)
  509. EmitDeclMetadata();
  510. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  511. EmitCoverageFile();
  512. if (DebugInfo)
  513. DebugInfo->finalize();
  514. EmitVersionIdentMetadata();
  515. EmitTargetMetadata();
  516. }
  517. void CodeGenModule::EmitOpenCLMetadata() {
  518. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  519. // opencl.ocl.version named metadata node.
  520. llvm::Metadata *OCLVerElts[] = {
  521. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  522. Int32Ty, LangOpts.OpenCLVersion / 100)),
  523. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  524. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  525. llvm::NamedMDNode *OCLVerMD =
  526. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  527. llvm::LLVMContext &Ctx = TheModule.getContext();
  528. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  529. }
  530. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  531. // Make sure that this type is translated.
  532. Types.UpdateCompletedType(TD);
  533. }
  534. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  535. // Make sure that this type is translated.
  536. Types.RefreshTypeCacheForClass(RD);
  537. }
  538. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  539. if (!TBAA)
  540. return nullptr;
  541. return TBAA->getTypeInfo(QTy);
  542. }
  543. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  544. if (!TBAA)
  545. return TBAAAccessInfo();
  546. return TBAA->getAccessInfo(AccessType);
  547. }
  548. TBAAAccessInfo
  549. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  550. if (!TBAA)
  551. return TBAAAccessInfo();
  552. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  553. }
  554. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  555. if (!TBAA)
  556. return nullptr;
  557. return TBAA->getTBAAStructInfo(QTy);
  558. }
  559. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  560. if (!TBAA)
  561. return nullptr;
  562. return TBAA->getBaseTypeInfo(QTy);
  563. }
  564. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  565. if (!TBAA)
  566. return nullptr;
  567. return TBAA->getAccessTagInfo(Info);
  568. }
  569. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  570. TBAAAccessInfo TargetInfo) {
  571. if (!TBAA)
  572. return TBAAAccessInfo();
  573. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  574. }
  575. TBAAAccessInfo
  576. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  577. TBAAAccessInfo InfoB) {
  578. if (!TBAA)
  579. return TBAAAccessInfo();
  580. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  581. }
  582. TBAAAccessInfo
  583. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  584. TBAAAccessInfo SrcInfo) {
  585. if (!TBAA)
  586. return TBAAAccessInfo();
  587. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  588. }
  589. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  590. TBAAAccessInfo TBAAInfo) {
  591. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  592. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  593. }
  594. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  595. llvm::Instruction *I, const CXXRecordDecl *RD) {
  596. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  597. llvm::MDNode::get(getLLVMContext(), {}));
  598. }
  599. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  600. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  601. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  602. }
  603. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  604. /// specified stmt yet.
  605. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  606. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  607. "cannot compile this %0 yet");
  608. std::string Msg = Type;
  609. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  610. << Msg << S->getSourceRange();
  611. }
  612. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  613. /// specified decl yet.
  614. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  615. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  616. "cannot compile this %0 yet");
  617. std::string Msg = Type;
  618. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  619. }
  620. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  621. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  622. }
  623. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  624. const NamedDecl *D) const {
  625. if (GV->hasDLLImportStorageClass())
  626. return;
  627. // Internal definitions always have default visibility.
  628. if (GV->hasLocalLinkage()) {
  629. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  630. return;
  631. }
  632. if (!D)
  633. return;
  634. // Set visibility for definitions.
  635. LinkageInfo LV = D->getLinkageAndVisibility();
  636. if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
  637. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  638. }
  639. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  640. llvm::GlobalValue *GV) {
  641. if (GV->hasLocalLinkage())
  642. return true;
  643. if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
  644. return true;
  645. // DLLImport explicitly marks the GV as external.
  646. if (GV->hasDLLImportStorageClass())
  647. return false;
  648. const llvm::Triple &TT = CGM.getTriple();
  649. // Every other GV is local on COFF.
  650. // Make an exception for windows OS in the triple: Some firmware builds use
  651. // *-win32-macho triples. This (accidentally?) produced windows relocations
  652. // without GOT tables in older clang versions; Keep this behaviour.
  653. // FIXME: even thread local variables?
  654. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  655. return true;
  656. // Only handle COFF and ELF for now.
  657. if (!TT.isOSBinFormatELF())
  658. return false;
  659. // If this is not an executable, don't assume anything is local.
  660. const auto &CGOpts = CGM.getCodeGenOpts();
  661. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  662. const auto &LOpts = CGM.getLangOpts();
  663. if (RM != llvm::Reloc::Static && !LOpts.PIE)
  664. return false;
  665. // A definition cannot be preempted from an executable.
  666. if (!GV->isDeclarationForLinker())
  667. return true;
  668. // Most PIC code sequences that assume that a symbol is local cannot produce a
  669. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  670. // depended, it seems worth it to handle it here.
  671. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  672. return false;
  673. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  674. llvm::Triple::ArchType Arch = TT.getArch();
  675. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  676. Arch == llvm::Triple::ppc64le)
  677. return false;
  678. // If we can use copy relocations we can assume it is local.
  679. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  680. if (!Var->isThreadLocal() &&
  681. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  682. return true;
  683. // If we can use a plt entry as the symbol address we can assume it
  684. // is local.
  685. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  686. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  687. return true;
  688. // Otherwise don't assue it is local.
  689. return false;
  690. }
  691. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  692. GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
  693. }
  694. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  695. GlobalDecl GD) const {
  696. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  697. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  698. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  699. // Don't dllexport/import destructor thunks.
  700. GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  701. return;
  702. }
  703. }
  704. setDLLImportDLLExport(GV, D);
  705. }
  706. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  707. const NamedDecl *D) const {
  708. if (D && D->isExternallyVisible()) {
  709. if (D->hasAttr<DLLImportAttr>())
  710. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  711. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  712. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  713. }
  714. }
  715. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  716. GlobalDecl GD) const {
  717. setDLLImportDLLExport(GV, GD);
  718. setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  719. }
  720. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  721. const NamedDecl *D) const {
  722. setDLLImportDLLExport(GV, D);
  723. setGlobalVisibilityAndLocal(GV, D);
  724. }
  725. void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
  726. const NamedDecl *D) const {
  727. setGlobalVisibility(GV, D);
  728. setDSOLocal(GV);
  729. }
  730. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  731. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  732. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  733. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  734. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  735. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  736. }
  737. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  738. CodeGenOptions::TLSModel M) {
  739. switch (M) {
  740. case CodeGenOptions::GeneralDynamicTLSModel:
  741. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  742. case CodeGenOptions::LocalDynamicTLSModel:
  743. return llvm::GlobalVariable::LocalDynamicTLSModel;
  744. case CodeGenOptions::InitialExecTLSModel:
  745. return llvm::GlobalVariable::InitialExecTLSModel;
  746. case CodeGenOptions::LocalExecTLSModel:
  747. return llvm::GlobalVariable::LocalExecTLSModel;
  748. }
  749. llvm_unreachable("Invalid TLS model!");
  750. }
  751. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  752. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  753. llvm::GlobalValue::ThreadLocalMode TLM;
  754. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  755. // Override the TLS model if it is explicitly specified.
  756. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  757. TLM = GetLLVMTLSModel(Attr->getModel());
  758. }
  759. GV->setThreadLocalMode(TLM);
  760. }
  761. static void AppendTargetMangling(const CodeGenModule &CGM,
  762. const TargetAttr *Attr, raw_ostream &Out) {
  763. if (Attr->isDefaultVersion())
  764. return;
  765. Out << '.';
  766. const auto &Target = CGM.getTarget();
  767. TargetAttr::ParsedTargetAttr Info =
  768. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  769. // Multiversioning doesn't allow "no-${feature}", so we can
  770. // only have "+" prefixes here.
  771. assert(LHS.startswith("+") && RHS.startswith("+") &&
  772. "Features should always have a prefix.");
  773. return Target.multiVersionSortPriority(LHS.substr(1)) >
  774. Target.multiVersionSortPriority(RHS.substr(1));
  775. });
  776. bool IsFirst = true;
  777. if (!Info.Architecture.empty()) {
  778. IsFirst = false;
  779. Out << "arch_" << Info.Architecture;
  780. }
  781. for (StringRef Feat : Info.Features) {
  782. if (!IsFirst)
  783. Out << '_';
  784. IsFirst = false;
  785. Out << Feat.substr(1);
  786. }
  787. }
  788. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  789. const NamedDecl *ND,
  790. bool OmitTargetMangling = false) {
  791. SmallString<256> Buffer;
  792. llvm::raw_svector_ostream Out(Buffer);
  793. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  794. if (MC.shouldMangleDeclName(ND)) {
  795. llvm::raw_svector_ostream Out(Buffer);
  796. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  797. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  798. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  799. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  800. else
  801. MC.mangleName(ND, Out);
  802. } else {
  803. IdentifierInfo *II = ND->getIdentifier();
  804. assert(II && "Attempt to mangle unnamed decl.");
  805. const auto *FD = dyn_cast<FunctionDecl>(ND);
  806. if (FD &&
  807. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  808. llvm::raw_svector_ostream Out(Buffer);
  809. Out << "__regcall3__" << II->getName();
  810. } else {
  811. Out << II->getName();
  812. }
  813. }
  814. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  815. if (FD->isMultiVersion() && !OmitTargetMangling)
  816. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  817. return Out.str();
  818. }
  819. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  820. const FunctionDecl *FD) {
  821. if (!FD->isMultiVersion())
  822. return;
  823. // Get the name of what this would be without the 'target' attribute. This
  824. // allows us to lookup the version that was emitted when this wasn't a
  825. // multiversion function.
  826. std::string NonTargetName =
  827. getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
  828. GlobalDecl OtherGD;
  829. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  830. assert(OtherGD.getCanonicalDecl()
  831. .getDecl()
  832. ->getAsFunction()
  833. ->isMultiVersion() &&
  834. "Other GD should now be a multiversioned function");
  835. // OtherFD is the version of this function that was mangled BEFORE
  836. // becoming a MultiVersion function. It potentially needs to be updated.
  837. const FunctionDecl *OtherFD =
  838. OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
  839. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  840. // This is so that if the initial version was already the 'default'
  841. // version, we don't try to update it.
  842. if (OtherName != NonTargetName) {
  843. // Remove instead of erase, since others may have stored the StringRef
  844. // to this.
  845. const auto ExistingRecord = Manglings.find(NonTargetName);
  846. if (ExistingRecord != std::end(Manglings))
  847. Manglings.remove(&(*ExistingRecord));
  848. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  849. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  850. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  851. Entry->setName(OtherName);
  852. }
  853. }
  854. }
  855. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  856. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  857. // Some ABIs don't have constructor variants. Make sure that base and
  858. // complete constructors get mangled the same.
  859. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  860. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  861. CXXCtorType OrigCtorType = GD.getCtorType();
  862. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  863. if (OrigCtorType == Ctor_Base)
  864. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  865. }
  866. }
  867. auto FoundName = MangledDeclNames.find(CanonicalGD);
  868. if (FoundName != MangledDeclNames.end())
  869. return FoundName->second;
  870. // Keep the first result in the case of a mangling collision.
  871. const auto *ND = cast<NamedDecl>(GD.getDecl());
  872. auto Result =
  873. Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
  874. return MangledDeclNames[CanonicalGD] = Result.first->first();
  875. }
  876. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  877. const BlockDecl *BD) {
  878. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  879. const Decl *D = GD.getDecl();
  880. SmallString<256> Buffer;
  881. llvm::raw_svector_ostream Out(Buffer);
  882. if (!D)
  883. MangleCtx.mangleGlobalBlock(BD,
  884. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  885. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  886. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  887. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  888. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  889. else
  890. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  891. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  892. return Result.first->first();
  893. }
  894. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  895. return getModule().getNamedValue(Name);
  896. }
  897. /// AddGlobalCtor - Add a function to the list that will be called before
  898. /// main() runs.
  899. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  900. llvm::Constant *AssociatedData) {
  901. // FIXME: Type coercion of void()* types.
  902. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  903. }
  904. /// AddGlobalDtor - Add a function to the list that will be called
  905. /// when the module is unloaded.
  906. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  907. // FIXME: Type coercion of void()* types.
  908. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  909. }
  910. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  911. if (Fns.empty()) return;
  912. // Ctor function type is void()*.
  913. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  914. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  915. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  916. llvm::StructType *CtorStructTy = llvm::StructType::get(
  917. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
  918. // Construct the constructor and destructor arrays.
  919. ConstantInitBuilder builder(*this);
  920. auto ctors = builder.beginArray(CtorStructTy);
  921. for (const auto &I : Fns) {
  922. auto ctor = ctors.beginStruct(CtorStructTy);
  923. ctor.addInt(Int32Ty, I.Priority);
  924. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  925. if (I.AssociatedData)
  926. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  927. else
  928. ctor.addNullPointer(VoidPtrTy);
  929. ctor.finishAndAddTo(ctors);
  930. }
  931. auto list =
  932. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  933. /*constant*/ false,
  934. llvm::GlobalValue::AppendingLinkage);
  935. // The LTO linker doesn't seem to like it when we set an alignment
  936. // on appending variables. Take it off as a workaround.
  937. list->setAlignment(0);
  938. Fns.clear();
  939. }
  940. llvm::GlobalValue::LinkageTypes
  941. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  942. const auto *D = cast<FunctionDecl>(GD.getDecl());
  943. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  944. if (isa<CXXDestructorDecl>(D) &&
  945. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  946. GD.getDtorType())) {
  947. // Destructor variants in the Microsoft C++ ABI are always internal or
  948. // linkonce_odr thunks emitted on an as-needed basis.
  949. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  950. : llvm::GlobalValue::LinkOnceODRLinkage;
  951. }
  952. if (isa<CXXConstructorDecl>(D) &&
  953. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  954. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  955. // Our approach to inheriting constructors is fundamentally different from
  956. // that used by the MS ABI, so keep our inheriting constructor thunks
  957. // internal rather than trying to pick an unambiguous mangling for them.
  958. return llvm::GlobalValue::InternalLinkage;
  959. }
  960. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  961. }
  962. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  963. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  964. if (!MDS) return nullptr;
  965. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  966. }
  967. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  968. const CGFunctionInfo &Info,
  969. llvm::Function *F) {
  970. unsigned CallingConv;
  971. llvm::AttributeList PAL;
  972. ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
  973. F->setAttributes(PAL);
  974. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  975. }
  976. /// Determines whether the language options require us to model
  977. /// unwind exceptions. We treat -fexceptions as mandating this
  978. /// except under the fragile ObjC ABI with only ObjC exceptions
  979. /// enabled. This means, for example, that C with -fexceptions
  980. /// enables this.
  981. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  982. // If exceptions are completely disabled, obviously this is false.
  983. if (!LangOpts.Exceptions) return false;
  984. // If C++ exceptions are enabled, this is true.
  985. if (LangOpts.CXXExceptions) return true;
  986. // If ObjC exceptions are enabled, this depends on the ABI.
  987. if (LangOpts.ObjCExceptions) {
  988. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  989. }
  990. return true;
  991. }
  992. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  993. llvm::Function *F) {
  994. llvm::AttrBuilder B;
  995. if (CodeGenOpts.UnwindTables)
  996. B.addAttribute(llvm::Attribute::UWTable);
  997. if (!hasUnwindExceptions(LangOpts))
  998. B.addAttribute(llvm::Attribute::NoUnwind);
  999. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  1000. B.addAttribute(llvm::Attribute::StackProtect);
  1001. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  1002. B.addAttribute(llvm::Attribute::StackProtectStrong);
  1003. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  1004. B.addAttribute(llvm::Attribute::StackProtectReq);
  1005. if (!D) {
  1006. // If we don't have a declaration to control inlining, the function isn't
  1007. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1008. // disabled, mark the function as noinline.
  1009. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1010. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1011. B.addAttribute(llvm::Attribute::NoInline);
  1012. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1013. return;
  1014. }
  1015. // Track whether we need to add the optnone LLVM attribute,
  1016. // starting with the default for this optimization level.
  1017. bool ShouldAddOptNone =
  1018. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1019. // We can't add optnone in the following cases, it won't pass the verifier.
  1020. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1021. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  1022. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1023. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  1024. B.addAttribute(llvm::Attribute::OptimizeNone);
  1025. // OptimizeNone implies noinline; we should not be inlining such functions.
  1026. B.addAttribute(llvm::Attribute::NoInline);
  1027. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1028. "OptimizeNone and AlwaysInline on same function!");
  1029. // We still need to handle naked functions even though optnone subsumes
  1030. // much of their semantics.
  1031. if (D->hasAttr<NakedAttr>())
  1032. B.addAttribute(llvm::Attribute::Naked);
  1033. // OptimizeNone wins over OptimizeForSize and MinSize.
  1034. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1035. F->removeFnAttr(llvm::Attribute::MinSize);
  1036. } else if (D->hasAttr<NakedAttr>()) {
  1037. // Naked implies noinline: we should not be inlining such functions.
  1038. B.addAttribute(llvm::Attribute::Naked);
  1039. B.addAttribute(llvm::Attribute::NoInline);
  1040. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1041. B.addAttribute(llvm::Attribute::NoDuplicate);
  1042. } else if (D->hasAttr<NoInlineAttr>()) {
  1043. B.addAttribute(llvm::Attribute::NoInline);
  1044. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1045. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1046. // (noinline wins over always_inline, and we can't specify both in IR)
  1047. B.addAttribute(llvm::Attribute::AlwaysInline);
  1048. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1049. // If we're not inlining, then force everything that isn't always_inline to
  1050. // carry an explicit noinline attribute.
  1051. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1052. B.addAttribute(llvm::Attribute::NoInline);
  1053. } else {
  1054. // Otherwise, propagate the inline hint attribute and potentially use its
  1055. // absence to mark things as noinline.
  1056. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1057. if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
  1058. return Redecl->isInlineSpecified();
  1059. })) {
  1060. B.addAttribute(llvm::Attribute::InlineHint);
  1061. } else if (CodeGenOpts.getInlining() ==
  1062. CodeGenOptions::OnlyHintInlining &&
  1063. !FD->isInlined() &&
  1064. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1065. B.addAttribute(llvm::Attribute::NoInline);
  1066. }
  1067. }
  1068. }
  1069. // Add other optimization related attributes if we are optimizing this
  1070. // function.
  1071. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1072. if (D->hasAttr<ColdAttr>()) {
  1073. if (!ShouldAddOptNone)
  1074. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1075. B.addAttribute(llvm::Attribute::Cold);
  1076. }
  1077. if (D->hasAttr<MinSizeAttr>())
  1078. B.addAttribute(llvm::Attribute::MinSize);
  1079. }
  1080. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1081. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1082. if (alignment)
  1083. F->setAlignment(alignment);
  1084. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1085. // reserve a bit for differentiating between virtual and non-virtual member
  1086. // functions. If the current target's C++ ABI requires this and this is a
  1087. // member function, set its alignment accordingly.
  1088. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1089. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1090. F->setAlignment(2);
  1091. }
  1092. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  1093. if (CodeGenOpts.SanitizeCfiCrossDso)
  1094. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1095. CreateFunctionTypeMetadata(FD, F);
  1096. }
  1097. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1098. const Decl *D = GD.getDecl();
  1099. if (dyn_cast_or_null<NamedDecl>(D))
  1100. setGVProperties(GV, GD);
  1101. else
  1102. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1103. if (D && D->hasAttr<UsedAttr>())
  1104. addUsedGlobal(GV);
  1105. }
  1106. bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
  1107. llvm::AttrBuilder &Attrs) {
  1108. // Add target-cpu and target-features attributes to functions. If
  1109. // we have a decl for the function and it has a target attribute then
  1110. // parse that and add it to the feature set.
  1111. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1112. std::vector<std::string> Features;
  1113. const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
  1114. FD = FD ? FD->getMostRecentDecl() : FD;
  1115. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1116. bool AddedAttr = false;
  1117. if (TD) {
  1118. llvm::StringMap<bool> FeatureMap;
  1119. getFunctionFeatureMap(FeatureMap, FD);
  1120. // Produce the canonical string for this set of features.
  1121. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1122. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1123. // Now add the target-cpu and target-features to the function.
  1124. // While we populated the feature map above, we still need to
  1125. // get and parse the target attribute so we can get the cpu for
  1126. // the function.
  1127. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1128. if (ParsedAttr.Architecture != "" &&
  1129. getTarget().isValidCPUName(ParsedAttr.Architecture))
  1130. TargetCPU = ParsedAttr.Architecture;
  1131. } else {
  1132. // Otherwise just add the existing target cpu and target features to the
  1133. // function.
  1134. Features = getTarget().getTargetOpts().Features;
  1135. }
  1136. if (TargetCPU != "") {
  1137. Attrs.addAttribute("target-cpu", TargetCPU);
  1138. AddedAttr = true;
  1139. }
  1140. if (!Features.empty()) {
  1141. std::sort(Features.begin(), Features.end());
  1142. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1143. AddedAttr = true;
  1144. }
  1145. return AddedAttr;
  1146. }
  1147. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1148. llvm::GlobalObject *GO) {
  1149. const Decl *D = GD.getDecl();
  1150. SetCommonAttributes(GD, GO);
  1151. if (D) {
  1152. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1153. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1154. GV->addAttribute("bss-section", SA->getName());
  1155. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1156. GV->addAttribute("data-section", SA->getName());
  1157. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1158. GV->addAttribute("rodata-section", SA->getName());
  1159. }
  1160. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1161. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1162. if (!D->getAttr<SectionAttr>())
  1163. F->addFnAttr("implicit-section-name", SA->getName());
  1164. llvm::AttrBuilder Attrs;
  1165. if (GetCPUAndFeaturesAttributes(D, Attrs)) {
  1166. // We know that GetCPUAndFeaturesAttributes will always have the
  1167. // newest set, since it has the newest possible FunctionDecl, so the
  1168. // new ones should replace the old.
  1169. F->removeFnAttr("target-cpu");
  1170. F->removeFnAttr("target-features");
  1171. F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
  1172. }
  1173. }
  1174. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  1175. GO->setSection(SA->getName());
  1176. }
  1177. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1178. }
  1179. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1180. llvm::Function *F,
  1181. const CGFunctionInfo &FI) {
  1182. const Decl *D = GD.getDecl();
  1183. SetLLVMFunctionAttributes(D, FI, F);
  1184. SetLLVMFunctionAttributesForDefinition(D, F);
  1185. F->setLinkage(llvm::Function::InternalLinkage);
  1186. setNonAliasAttributes(GD, F);
  1187. }
  1188. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1189. // Set linkage and visibility in case we never see a definition.
  1190. LinkageInfo LV = ND->getLinkageAndVisibility();
  1191. // Don't set internal linkage on declarations.
  1192. // "extern_weak" is overloaded in LLVM; we probably should have
  1193. // separate linkage types for this.
  1194. if (isExternallyVisible(LV.getLinkage()) &&
  1195. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1196. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1197. }
  1198. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  1199. llvm::Function *F) {
  1200. // Only if we are checking indirect calls.
  1201. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1202. return;
  1203. // Non-static class methods are handled via vtable pointer checks elsewhere.
  1204. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1205. return;
  1206. // Additionally, if building with cross-DSO support...
  1207. if (CodeGenOpts.SanitizeCfiCrossDso) {
  1208. // Skip available_externally functions. They won't be codegen'ed in the
  1209. // current module anyway.
  1210. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  1211. return;
  1212. }
  1213. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1214. F->addTypeMetadata(0, MD);
  1215. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1216. // Emit a hash-based bit set entry for cross-DSO calls.
  1217. if (CodeGenOpts.SanitizeCfiCrossDso)
  1218. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1219. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1220. }
  1221. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1222. bool IsIncompleteFunction,
  1223. bool IsThunk) {
  1224. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1225. // If this is an intrinsic function, set the function's attributes
  1226. // to the intrinsic's attributes.
  1227. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1228. return;
  1229. }
  1230. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1231. if (!IsIncompleteFunction) {
  1232. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  1233. // Setup target-specific attributes.
  1234. if (F->isDeclaration())
  1235. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1236. }
  1237. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1238. // where substantial code, including the libstdc++ dylib, was compiled with
  1239. // GCC and does not actually return "this".
  1240. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1241. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1242. assert(!F->arg_empty() &&
  1243. F->arg_begin()->getType()
  1244. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1245. "unexpected this return");
  1246. F->addAttribute(1, llvm::Attribute::Returned);
  1247. }
  1248. // Only a few attributes are set on declarations; these may later be
  1249. // overridden by a definition.
  1250. setLinkageForGV(F, FD);
  1251. setGVProperties(F, FD);
  1252. if (FD->getAttr<PragmaClangTextSectionAttr>()) {
  1253. F->addFnAttr("implicit-section-name");
  1254. }
  1255. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  1256. F->setSection(SA->getName());
  1257. if (FD->isReplaceableGlobalAllocationFunction()) {
  1258. // A replaceable global allocation function does not act like a builtin by
  1259. // default, only if it is invoked by a new-expression or delete-expression.
  1260. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1261. llvm::Attribute::NoBuiltin);
  1262. // A sane operator new returns a non-aliasing pointer.
  1263. // FIXME: Also add NonNull attribute to the return value
  1264. // for the non-nothrow forms?
  1265. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1266. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1267. (Kind == OO_New || Kind == OO_Array_New))
  1268. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1269. llvm::Attribute::NoAlias);
  1270. }
  1271. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1272. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1273. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1274. if (MD->isVirtual())
  1275. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1276. // Don't emit entries for function declarations in the cross-DSO mode. This
  1277. // is handled with better precision by the receiving DSO.
  1278. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1279. CreateFunctionTypeMetadata(FD, F);
  1280. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1281. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1282. }
  1283. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1284. assert(!GV->isDeclaration() &&
  1285. "Only globals with definition can force usage.");
  1286. LLVMUsed.emplace_back(GV);
  1287. }
  1288. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1289. assert(!GV->isDeclaration() &&
  1290. "Only globals with definition can force usage.");
  1291. LLVMCompilerUsed.emplace_back(GV);
  1292. }
  1293. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1294. std::vector<llvm::WeakTrackingVH> &List) {
  1295. // Don't create llvm.used if there is no need.
  1296. if (List.empty())
  1297. return;
  1298. // Convert List to what ConstantArray needs.
  1299. SmallVector<llvm::Constant*, 8> UsedArray;
  1300. UsedArray.resize(List.size());
  1301. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1302. UsedArray[i] =
  1303. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1304. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1305. }
  1306. if (UsedArray.empty())
  1307. return;
  1308. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1309. auto *GV = new llvm::GlobalVariable(
  1310. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1311. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1312. GV->setSection("llvm.metadata");
  1313. }
  1314. void CodeGenModule::emitLLVMUsed() {
  1315. emitUsed(*this, "llvm.used", LLVMUsed);
  1316. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1317. }
  1318. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1319. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1320. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1321. }
  1322. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1323. llvm::SmallString<32> Opt;
  1324. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1325. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1326. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1327. }
  1328. void CodeGenModule::AddELFLibDirective(StringRef Lib) {
  1329. auto &C = getLLVMContext();
  1330. LinkerOptionsMetadata.push_back(llvm::MDNode::get(
  1331. C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
  1332. }
  1333. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1334. llvm::SmallString<24> Opt;
  1335. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1336. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1337. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1338. }
  1339. /// \brief Add link options implied by the given module, including modules
  1340. /// it depends on, using a postorder walk.
  1341. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1342. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1343. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1344. // Import this module's parent.
  1345. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1346. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1347. }
  1348. // Import this module's dependencies.
  1349. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1350. if (Visited.insert(Mod->Imports[I - 1]).second)
  1351. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1352. }
  1353. // Add linker options to link against the libraries/frameworks
  1354. // described by this module.
  1355. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1356. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1357. // Link against a framework. Frameworks are currently Darwin only, so we
  1358. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1359. if (Mod->LinkLibraries[I-1].IsFramework) {
  1360. llvm::Metadata *Args[2] = {
  1361. llvm::MDString::get(Context, "-framework"),
  1362. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1363. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1364. continue;
  1365. }
  1366. // Link against a library.
  1367. llvm::SmallString<24> Opt;
  1368. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1369. Mod->LinkLibraries[I-1].Library, Opt);
  1370. auto *OptString = llvm::MDString::get(Context, Opt);
  1371. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1372. }
  1373. }
  1374. void CodeGenModule::EmitModuleLinkOptions() {
  1375. // Collect the set of all of the modules we want to visit to emit link
  1376. // options, which is essentially the imported modules and all of their
  1377. // non-explicit child modules.
  1378. llvm::SetVector<clang::Module *> LinkModules;
  1379. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1380. SmallVector<clang::Module *, 16> Stack;
  1381. // Seed the stack with imported modules.
  1382. for (Module *M : ImportedModules) {
  1383. // Do not add any link flags when an implementation TU of a module imports
  1384. // a header of that same module.
  1385. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1386. !getLangOpts().isCompilingModule())
  1387. continue;
  1388. if (Visited.insert(M).second)
  1389. Stack.push_back(M);
  1390. }
  1391. // Find all of the modules to import, making a little effort to prune
  1392. // non-leaf modules.
  1393. while (!Stack.empty()) {
  1394. clang::Module *Mod = Stack.pop_back_val();
  1395. bool AnyChildren = false;
  1396. // Visit the submodules of this module.
  1397. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1398. SubEnd = Mod->submodule_end();
  1399. Sub != SubEnd; ++Sub) {
  1400. // Skip explicit children; they need to be explicitly imported to be
  1401. // linked against.
  1402. if ((*Sub)->IsExplicit)
  1403. continue;
  1404. if (Visited.insert(*Sub).second) {
  1405. Stack.push_back(*Sub);
  1406. AnyChildren = true;
  1407. }
  1408. }
  1409. // We didn't find any children, so add this module to the list of
  1410. // modules to link against.
  1411. if (!AnyChildren) {
  1412. LinkModules.insert(Mod);
  1413. }
  1414. }
  1415. // Add link options for all of the imported modules in reverse topological
  1416. // order. We don't do anything to try to order import link flags with respect
  1417. // to linker options inserted by things like #pragma comment().
  1418. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1419. Visited.clear();
  1420. for (Module *M : LinkModules)
  1421. if (Visited.insert(M).second)
  1422. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1423. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1424. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1425. // Add the linker options metadata flag.
  1426. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1427. for (auto *MD : LinkerOptionsMetadata)
  1428. NMD->addOperand(MD);
  1429. }
  1430. void CodeGenModule::EmitDeferred() {
  1431. // Emit code for any potentially referenced deferred decls. Since a
  1432. // previously unused static decl may become used during the generation of code
  1433. // for a static function, iterate until no changes are made.
  1434. if (!DeferredVTables.empty()) {
  1435. EmitDeferredVTables();
  1436. // Emitting a vtable doesn't directly cause more vtables to
  1437. // become deferred, although it can cause functions to be
  1438. // emitted that then need those vtables.
  1439. assert(DeferredVTables.empty());
  1440. }
  1441. // Stop if we're out of both deferred vtables and deferred declarations.
  1442. if (DeferredDeclsToEmit.empty())
  1443. return;
  1444. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1445. // work, it will not interfere with this.
  1446. std::vector<GlobalDecl> CurDeclsToEmit;
  1447. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1448. for (GlobalDecl &D : CurDeclsToEmit) {
  1449. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1450. // to get GlobalValue with exactly the type we need, not something that
  1451. // might had been created for another decl with the same mangled name but
  1452. // different type.
  1453. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1454. GetAddrOfGlobal(D, ForDefinition));
  1455. // In case of different address spaces, we may still get a cast, even with
  1456. // IsForDefinition equal to true. Query mangled names table to get
  1457. // GlobalValue.
  1458. if (!GV)
  1459. GV = GetGlobalValue(getMangledName(D));
  1460. // Make sure GetGlobalValue returned non-null.
  1461. assert(GV);
  1462. // Check to see if we've already emitted this. This is necessary
  1463. // for a couple of reasons: first, decls can end up in the
  1464. // deferred-decls queue multiple times, and second, decls can end
  1465. // up with definitions in unusual ways (e.g. by an extern inline
  1466. // function acquiring a strong function redefinition). Just
  1467. // ignore these cases.
  1468. if (!GV->isDeclaration())
  1469. continue;
  1470. // Otherwise, emit the definition and move on to the next one.
  1471. EmitGlobalDefinition(D, GV);
  1472. // If we found out that we need to emit more decls, do that recursively.
  1473. // This has the advantage that the decls are emitted in a DFS and related
  1474. // ones are close together, which is convenient for testing.
  1475. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1476. EmitDeferred();
  1477. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1478. }
  1479. }
  1480. }
  1481. void CodeGenModule::EmitVTablesOpportunistically() {
  1482. // Try to emit external vtables as available_externally if they have emitted
  1483. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1484. // is not allowed to create new references to things that need to be emitted
  1485. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1486. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1487. && "Only emit opportunistic vtables with optimizations");
  1488. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1489. assert(getVTables().isVTableExternal(RD) &&
  1490. "This queue should only contain external vtables");
  1491. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1492. VTables.GenerateClassData(RD);
  1493. }
  1494. OpportunisticVTables.clear();
  1495. }
  1496. void CodeGenModule::EmitGlobalAnnotations() {
  1497. if (Annotations.empty())
  1498. return;
  1499. // Create a new global variable for the ConstantStruct in the Module.
  1500. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1501. Annotations[0]->getType(), Annotations.size()), Annotations);
  1502. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1503. llvm::GlobalValue::AppendingLinkage,
  1504. Array, "llvm.global.annotations");
  1505. gv->setSection(AnnotationSection);
  1506. }
  1507. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1508. llvm::Constant *&AStr = AnnotationStrings[Str];
  1509. if (AStr)
  1510. return AStr;
  1511. // Not found yet, create a new global.
  1512. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1513. auto *gv =
  1514. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1515. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1516. gv->setSection(AnnotationSection);
  1517. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1518. AStr = gv;
  1519. return gv;
  1520. }
  1521. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1522. SourceManager &SM = getContext().getSourceManager();
  1523. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1524. if (PLoc.isValid())
  1525. return EmitAnnotationString(PLoc.getFilename());
  1526. return EmitAnnotationString(SM.getBufferName(Loc));
  1527. }
  1528. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1529. SourceManager &SM = getContext().getSourceManager();
  1530. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1531. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1532. SM.getExpansionLineNumber(L);
  1533. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1534. }
  1535. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1536. const AnnotateAttr *AA,
  1537. SourceLocation L) {
  1538. // Get the globals for file name, annotation, and the line number.
  1539. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1540. *UnitGV = EmitAnnotationUnit(L),
  1541. *LineNoCst = EmitAnnotationLineNo(L);
  1542. // Create the ConstantStruct for the global annotation.
  1543. llvm::Constant *Fields[4] = {
  1544. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1545. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1546. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1547. LineNoCst
  1548. };
  1549. return llvm::ConstantStruct::getAnon(Fields);
  1550. }
  1551. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1552. llvm::GlobalValue *GV) {
  1553. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1554. // Get the struct elements for these annotations.
  1555. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1556. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1557. }
  1558. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1559. llvm::Function *Fn,
  1560. SourceLocation Loc) const {
  1561. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1562. // Blacklist by function name.
  1563. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1564. return true;
  1565. // Blacklist by location.
  1566. if (Loc.isValid())
  1567. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1568. // If location is unknown, this may be a compiler-generated function. Assume
  1569. // it's located in the main file.
  1570. auto &SM = Context.getSourceManager();
  1571. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1572. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1573. }
  1574. return false;
  1575. }
  1576. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1577. SourceLocation Loc, QualType Ty,
  1578. StringRef Category) const {
  1579. // For now globals can be blacklisted only in ASan and KASan.
  1580. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1581. (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
  1582. if (!EnabledAsanMask)
  1583. return false;
  1584. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1585. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1586. return true;
  1587. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1588. return true;
  1589. // Check global type.
  1590. if (!Ty.isNull()) {
  1591. // Drill down the array types: if global variable of a fixed type is
  1592. // blacklisted, we also don't instrument arrays of them.
  1593. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1594. Ty = AT->getElementType();
  1595. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1596. // We allow to blacklist only record types (classes, structs etc.)
  1597. if (Ty->isRecordType()) {
  1598. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1599. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1600. return true;
  1601. }
  1602. }
  1603. return false;
  1604. }
  1605. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1606. StringRef Category) const {
  1607. if (!LangOpts.XRayInstrument)
  1608. return false;
  1609. const auto &XRayFilter = getContext().getXRayFilter();
  1610. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1611. auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
  1612. if (Loc.isValid())
  1613. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1614. if (Attr == ImbueAttr::NONE)
  1615. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1616. switch (Attr) {
  1617. case ImbueAttr::NONE:
  1618. return false;
  1619. case ImbueAttr::ALWAYS:
  1620. Fn->addFnAttr("function-instrument", "xray-always");
  1621. break;
  1622. case ImbueAttr::ALWAYS_ARG1:
  1623. Fn->addFnAttr("function-instrument", "xray-always");
  1624. Fn->addFnAttr("xray-log-args", "1");
  1625. break;
  1626. case ImbueAttr::NEVER:
  1627. Fn->addFnAttr("function-instrument", "xray-never");
  1628. break;
  1629. }
  1630. return true;
  1631. }
  1632. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1633. // Never defer when EmitAllDecls is specified.
  1634. if (LangOpts.EmitAllDecls)
  1635. return true;
  1636. return getContext().DeclMustBeEmitted(Global);
  1637. }
  1638. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1639. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1640. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1641. // Implicit template instantiations may change linkage if they are later
  1642. // explicitly instantiated, so they should not be emitted eagerly.
  1643. return false;
  1644. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1645. if (Context.getInlineVariableDefinitionKind(VD) ==
  1646. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1647. // A definition of an inline constexpr static data member may change
  1648. // linkage later if it's redeclared outside the class.
  1649. return false;
  1650. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1651. // codegen for global variables, because they may be marked as threadprivate.
  1652. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1653. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1654. return false;
  1655. return true;
  1656. }
  1657. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1658. const CXXUuidofExpr* E) {
  1659. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1660. // well-formed.
  1661. StringRef Uuid = E->getUuidStr();
  1662. std::string Name = "_GUID_" + Uuid.lower();
  1663. std::replace(Name.begin(), Name.end(), '-', '_');
  1664. // The UUID descriptor should be pointer aligned.
  1665. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1666. // Look for an existing global.
  1667. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1668. return ConstantAddress(GV, Alignment);
  1669. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1670. assert(Init && "failed to initialize as constant");
  1671. auto *GV = new llvm::GlobalVariable(
  1672. getModule(), Init->getType(),
  1673. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1674. if (supportsCOMDAT())
  1675. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1676. return ConstantAddress(GV, Alignment);
  1677. }
  1678. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1679. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1680. assert(AA && "No alias?");
  1681. CharUnits Alignment = getContext().getDeclAlign(VD);
  1682. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1683. // See if there is already something with the target's name in the module.
  1684. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1685. if (Entry) {
  1686. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1687. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1688. return ConstantAddress(Ptr, Alignment);
  1689. }
  1690. llvm::Constant *Aliasee;
  1691. if (isa<llvm::FunctionType>(DeclTy))
  1692. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1693. GlobalDecl(cast<FunctionDecl>(VD)),
  1694. /*ForVTable=*/false);
  1695. else
  1696. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1697. llvm::PointerType::getUnqual(DeclTy),
  1698. nullptr);
  1699. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1700. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1701. WeakRefReferences.insert(F);
  1702. return ConstantAddress(Aliasee, Alignment);
  1703. }
  1704. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1705. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1706. // Weak references don't produce any output by themselves.
  1707. if (Global->hasAttr<WeakRefAttr>())
  1708. return;
  1709. // If this is an alias definition (which otherwise looks like a declaration)
  1710. // emit it now.
  1711. if (Global->hasAttr<AliasAttr>())
  1712. return EmitAliasDefinition(GD);
  1713. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1714. if (Global->hasAttr<IFuncAttr>())
  1715. return emitIFuncDefinition(GD);
  1716. // If this is CUDA, be selective about which declarations we emit.
  1717. if (LangOpts.CUDA) {
  1718. if (LangOpts.CUDAIsDevice) {
  1719. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1720. !Global->hasAttr<CUDAGlobalAttr>() &&
  1721. !Global->hasAttr<CUDAConstantAttr>() &&
  1722. !Global->hasAttr<CUDASharedAttr>())
  1723. return;
  1724. } else {
  1725. // We need to emit host-side 'shadows' for all global
  1726. // device-side variables because the CUDA runtime needs their
  1727. // size and host-side address in order to provide access to
  1728. // their device-side incarnations.
  1729. // So device-only functions are the only things we skip.
  1730. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1731. Global->hasAttr<CUDADeviceAttr>())
  1732. return;
  1733. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1734. "Expected Variable or Function");
  1735. }
  1736. }
  1737. if (LangOpts.OpenMP) {
  1738. // If this is OpenMP device, check if it is legal to emit this global
  1739. // normally.
  1740. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1741. return;
  1742. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1743. if (MustBeEmitted(Global))
  1744. EmitOMPDeclareReduction(DRD);
  1745. return;
  1746. }
  1747. }
  1748. // Ignore declarations, they will be emitted on their first use.
  1749. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1750. // Forward declarations are emitted lazily on first use.
  1751. if (!FD->doesThisDeclarationHaveABody()) {
  1752. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1753. return;
  1754. StringRef MangledName = getMangledName(GD);
  1755. // Compute the function info and LLVM type.
  1756. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1757. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1758. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1759. /*DontDefer=*/false);
  1760. return;
  1761. }
  1762. } else {
  1763. const auto *VD = cast<VarDecl>(Global);
  1764. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1765. // We need to emit device-side global CUDA variables even if a
  1766. // variable does not have a definition -- we still need to define
  1767. // host-side shadow for it.
  1768. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1769. !VD->hasDefinition() &&
  1770. (VD->hasAttr<CUDAConstantAttr>() ||
  1771. VD->hasAttr<CUDADeviceAttr>());
  1772. if (!MustEmitForCuda &&
  1773. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1774. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1775. // If this declaration may have caused an inline variable definition to
  1776. // change linkage, make sure that it's emitted.
  1777. if (Context.getInlineVariableDefinitionKind(VD) ==
  1778. ASTContext::InlineVariableDefinitionKind::Strong)
  1779. GetAddrOfGlobalVar(VD);
  1780. return;
  1781. }
  1782. }
  1783. // Defer code generation to first use when possible, e.g. if this is an inline
  1784. // function. If the global must always be emitted, do it eagerly if possible
  1785. // to benefit from cache locality.
  1786. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1787. // Emit the definition if it can't be deferred.
  1788. EmitGlobalDefinition(GD);
  1789. return;
  1790. }
  1791. // If we're deferring emission of a C++ variable with an
  1792. // initializer, remember the order in which it appeared in the file.
  1793. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1794. cast<VarDecl>(Global)->hasInit()) {
  1795. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1796. CXXGlobalInits.push_back(nullptr);
  1797. }
  1798. StringRef MangledName = getMangledName(GD);
  1799. if (GetGlobalValue(MangledName) != nullptr) {
  1800. // The value has already been used and should therefore be emitted.
  1801. addDeferredDeclToEmit(GD);
  1802. } else if (MustBeEmitted(Global)) {
  1803. // The value must be emitted, but cannot be emitted eagerly.
  1804. assert(!MayBeEmittedEagerly(Global));
  1805. addDeferredDeclToEmit(GD);
  1806. } else {
  1807. // Otherwise, remember that we saw a deferred decl with this name. The
  1808. // first use of the mangled name will cause it to move into
  1809. // DeferredDeclsToEmit.
  1810. DeferredDecls[MangledName] = GD;
  1811. }
  1812. }
  1813. // Check if T is a class type with a destructor that's not dllimport.
  1814. static bool HasNonDllImportDtor(QualType T) {
  1815. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1816. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1817. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1818. return true;
  1819. return false;
  1820. }
  1821. namespace {
  1822. struct FunctionIsDirectlyRecursive :
  1823. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1824. const StringRef Name;
  1825. const Builtin::Context &BI;
  1826. bool Result;
  1827. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1828. Name(N), BI(C), Result(false) {
  1829. }
  1830. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1831. bool TraverseCallExpr(CallExpr *E) {
  1832. const FunctionDecl *FD = E->getDirectCallee();
  1833. if (!FD)
  1834. return true;
  1835. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1836. if (Attr && Name == Attr->getLabel()) {
  1837. Result = true;
  1838. return false;
  1839. }
  1840. unsigned BuiltinID = FD->getBuiltinID();
  1841. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1842. return true;
  1843. StringRef BuiltinName = BI.getName(BuiltinID);
  1844. if (BuiltinName.startswith("__builtin_") &&
  1845. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1846. Result = true;
  1847. return false;
  1848. }
  1849. return true;
  1850. }
  1851. };
  1852. // Make sure we're not referencing non-imported vars or functions.
  1853. struct DLLImportFunctionVisitor
  1854. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1855. bool SafeToInline = true;
  1856. bool shouldVisitImplicitCode() const { return true; }
  1857. bool VisitVarDecl(VarDecl *VD) {
  1858. if (VD->getTLSKind()) {
  1859. // A thread-local variable cannot be imported.
  1860. SafeToInline = false;
  1861. return SafeToInline;
  1862. }
  1863. // A variable definition might imply a destructor call.
  1864. if (VD->isThisDeclarationADefinition())
  1865. SafeToInline = !HasNonDllImportDtor(VD->getType());
  1866. return SafeToInline;
  1867. }
  1868. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1869. if (const auto *D = E->getTemporary()->getDestructor())
  1870. SafeToInline = D->hasAttr<DLLImportAttr>();
  1871. return SafeToInline;
  1872. }
  1873. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1874. ValueDecl *VD = E->getDecl();
  1875. if (isa<FunctionDecl>(VD))
  1876. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1877. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1878. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1879. return SafeToInline;
  1880. }
  1881. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1882. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1883. return SafeToInline;
  1884. }
  1885. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  1886. CXXMethodDecl *M = E->getMethodDecl();
  1887. if (!M) {
  1888. // Call through a pointer to member function. This is safe to inline.
  1889. SafeToInline = true;
  1890. } else {
  1891. SafeToInline = M->hasAttr<DLLImportAttr>();
  1892. }
  1893. return SafeToInline;
  1894. }
  1895. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1896. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1897. return SafeToInline;
  1898. }
  1899. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1900. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1901. return SafeToInline;
  1902. }
  1903. };
  1904. }
  1905. // isTriviallyRecursive - Check if this function calls another
  1906. // decl that, because of the asm attribute or the other decl being a builtin,
  1907. // ends up pointing to itself.
  1908. bool
  1909. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1910. StringRef Name;
  1911. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1912. // asm labels are a special kind of mangling we have to support.
  1913. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1914. if (!Attr)
  1915. return false;
  1916. Name = Attr->getLabel();
  1917. } else {
  1918. Name = FD->getName();
  1919. }
  1920. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1921. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1922. return Walker.Result;
  1923. }
  1924. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1925. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1926. return true;
  1927. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1928. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1929. return false;
  1930. if (F->hasAttr<DLLImportAttr>()) {
  1931. // Check whether it would be safe to inline this dllimport function.
  1932. DLLImportFunctionVisitor Visitor;
  1933. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1934. if (!Visitor.SafeToInline)
  1935. return false;
  1936. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1937. // Implicit destructor invocations aren't captured in the AST, so the
  1938. // check above can't see them. Check for them manually here.
  1939. for (const Decl *Member : Dtor->getParent()->decls())
  1940. if (isa<FieldDecl>(Member))
  1941. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1942. return false;
  1943. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1944. if (HasNonDllImportDtor(B.getType()))
  1945. return false;
  1946. }
  1947. }
  1948. // PR9614. Avoid cases where the source code is lying to us. An available
  1949. // externally function should have an equivalent function somewhere else,
  1950. // but a function that calls itself is clearly not equivalent to the real
  1951. // implementation.
  1952. // This happens in glibc's btowc and in some configure checks.
  1953. return !isTriviallyRecursive(F);
  1954. }
  1955. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  1956. return CodeGenOpts.OptimizationLevel > 0;
  1957. }
  1958. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1959. const auto *D = cast<ValueDecl>(GD.getDecl());
  1960. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1961. Context.getSourceManager(),
  1962. "Generating code for declaration");
  1963. if (isa<FunctionDecl>(D)) {
  1964. // At -O0, don't generate IR for functions with available_externally
  1965. // linkage.
  1966. if (!shouldEmitFunction(GD))
  1967. return;
  1968. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1969. // Make sure to emit the definition(s) before we emit the thunks.
  1970. // This is necessary for the generation of certain thunks.
  1971. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1972. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1973. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1974. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1975. else
  1976. EmitGlobalFunctionDefinition(GD, GV);
  1977. if (Method->isVirtual())
  1978. getVTables().EmitThunks(GD);
  1979. return;
  1980. }
  1981. return EmitGlobalFunctionDefinition(GD, GV);
  1982. }
  1983. if (const auto *VD = dyn_cast<VarDecl>(D))
  1984. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1985. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1986. }
  1987. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1988. llvm::Function *NewFn);
  1989. void CodeGenModule::emitMultiVersionFunctions() {
  1990. for (GlobalDecl GD : MultiVersionFuncs) {
  1991. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  1992. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1993. getContext().forEachMultiversionedFunctionVersion(
  1994. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  1995. GlobalDecl CurGD{
  1996. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  1997. StringRef MangledName = getMangledName(CurGD);
  1998. llvm::Constant *Func = GetGlobalValue(MangledName);
  1999. if (!Func) {
  2000. if (CurFD->isDefined()) {
  2001. EmitGlobalFunctionDefinition(CurGD, nullptr);
  2002. Func = GetGlobalValue(MangledName);
  2003. } else {
  2004. const CGFunctionInfo &FI =
  2005. getTypes().arrangeGlobalDeclaration(GD);
  2006. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2007. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2008. /*DontDefer=*/false, ForDefinition);
  2009. }
  2010. assert(Func && "This should have just been created");
  2011. }
  2012. Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
  2013. CurFD->getAttr<TargetAttr>()->parse());
  2014. });
  2015. llvm::Function *ResolverFunc = cast<llvm::Function>(
  2016. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  2017. if (supportsCOMDAT())
  2018. ResolverFunc->setComdat(
  2019. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2020. std::stable_sort(
  2021. Options.begin(), Options.end(),
  2022. std::greater<CodeGenFunction::MultiVersionResolverOption>());
  2023. CodeGenFunction CGF(*this);
  2024. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2025. }
  2026. }
  2027. /// If an ifunc for the specified mangled name is not in the module, create and
  2028. /// return an llvm IFunc Function with the specified type.
  2029. llvm::Constant *
  2030. CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
  2031. StringRef MangledName,
  2032. const FunctionDecl *FD) {
  2033. std::string IFuncName = (MangledName + ".ifunc").str();
  2034. if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
  2035. return IFuncGV;
  2036. // Since this is the first time we've created this IFunc, make sure
  2037. // that we put this multiversioned function into the list to be
  2038. // replaced later.
  2039. MultiVersionFuncs.push_back(GD);
  2040. std::string ResolverName = (MangledName + ".resolver").str();
  2041. llvm::Type *ResolverType = llvm::FunctionType::get(
  2042. llvm::PointerType::get(DeclTy,
  2043. Context.getTargetAddressSpace(FD->getType())),
  2044. false);
  2045. llvm::Constant *Resolver =
  2046. GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
  2047. /*ForVTable=*/false);
  2048. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  2049. DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
  2050. GIF->setName(IFuncName);
  2051. SetCommonAttributes(FD, GIF);
  2052. return GIF;
  2053. }
  2054. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  2055. /// module, create and return an llvm Function with the specified type. If there
  2056. /// is something in the module with the specified name, return it potentially
  2057. /// bitcasted to the right type.
  2058. ///
  2059. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2060. /// to set the attributes on the function when it is first created.
  2061. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2062. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2063. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2064. ForDefinition_t IsForDefinition) {
  2065. const Decl *D = GD.getDecl();
  2066. // Any attempts to use a MultiVersion function should result in retrieving
  2067. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2068. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2069. // For the device mark the function as one that should be emitted.
  2070. if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
  2071. !OpenMPRuntime->markAsGlobalTarget(FD) && FD->isDefined() &&
  2072. !DontDefer && !IsForDefinition)
  2073. addDeferredDeclToEmit(GD);
  2074. if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
  2075. UpdateMultiVersionNames(GD, FD);
  2076. if (!IsForDefinition)
  2077. return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
  2078. }
  2079. }
  2080. // Lookup the entry, lazily creating it if necessary.
  2081. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2082. if (Entry) {
  2083. if (WeakRefReferences.erase(Entry)) {
  2084. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2085. if (FD && !FD->hasAttr<WeakAttr>())
  2086. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2087. }
  2088. // Handle dropped DLL attributes.
  2089. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2090. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2091. // If there are two attempts to define the same mangled name, issue an
  2092. // error.
  2093. if (IsForDefinition && !Entry->isDeclaration()) {
  2094. GlobalDecl OtherGD;
  2095. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2096. // to make sure that we issue an error only once.
  2097. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2098. (GD.getCanonicalDecl().getDecl() !=
  2099. OtherGD.getCanonicalDecl().getDecl()) &&
  2100. DiagnosedConflictingDefinitions.insert(GD).second) {
  2101. getDiags().Report(D->getLocation(),
  2102. diag::err_duplicate_mangled_name);
  2103. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2104. diag::note_previous_definition);
  2105. }
  2106. }
  2107. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2108. (Entry->getType()->getElementType() == Ty)) {
  2109. return Entry;
  2110. }
  2111. // Make sure the result is of the correct type.
  2112. // (If function is requested for a definition, we always need to create a new
  2113. // function, not just return a bitcast.)
  2114. if (!IsForDefinition)
  2115. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2116. }
  2117. // This function doesn't have a complete type (for example, the return
  2118. // type is an incomplete struct). Use a fake type instead, and make
  2119. // sure not to try to set attributes.
  2120. bool IsIncompleteFunction = false;
  2121. llvm::FunctionType *FTy;
  2122. if (isa<llvm::FunctionType>(Ty)) {
  2123. FTy = cast<llvm::FunctionType>(Ty);
  2124. } else {
  2125. FTy = llvm::FunctionType::get(VoidTy, false);
  2126. IsIncompleteFunction = true;
  2127. }
  2128. llvm::Function *F =
  2129. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2130. Entry ? StringRef() : MangledName, &getModule());
  2131. // If we already created a function with the same mangled name (but different
  2132. // type) before, take its name and add it to the list of functions to be
  2133. // replaced with F at the end of CodeGen.
  2134. //
  2135. // This happens if there is a prototype for a function (e.g. "int f()") and
  2136. // then a definition of a different type (e.g. "int f(int x)").
  2137. if (Entry) {
  2138. F->takeName(Entry);
  2139. // This might be an implementation of a function without a prototype, in
  2140. // which case, try to do special replacement of calls which match the new
  2141. // prototype. The really key thing here is that we also potentially drop
  2142. // arguments from the call site so as to make a direct call, which makes the
  2143. // inliner happier and suppresses a number of optimizer warnings (!) about
  2144. // dropping arguments.
  2145. if (!Entry->use_empty()) {
  2146. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2147. Entry->removeDeadConstantUsers();
  2148. }
  2149. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2150. F, Entry->getType()->getElementType()->getPointerTo());
  2151. addGlobalValReplacement(Entry, BC);
  2152. }
  2153. assert(F->getName() == MangledName && "name was uniqued!");
  2154. if (D)
  2155. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2156. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2157. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2158. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2159. }
  2160. if (!DontDefer) {
  2161. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2162. // each other bottoming out with the base dtor. Therefore we emit non-base
  2163. // dtors on usage, even if there is no dtor definition in the TU.
  2164. if (D && isa<CXXDestructorDecl>(D) &&
  2165. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2166. GD.getDtorType()))
  2167. addDeferredDeclToEmit(GD);
  2168. // This is the first use or definition of a mangled name. If there is a
  2169. // deferred decl with this name, remember that we need to emit it at the end
  2170. // of the file.
  2171. auto DDI = DeferredDecls.find(MangledName);
  2172. if (DDI != DeferredDecls.end()) {
  2173. // Move the potentially referenced deferred decl to the
  2174. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2175. // don't need it anymore).
  2176. addDeferredDeclToEmit(DDI->second);
  2177. DeferredDecls.erase(DDI);
  2178. // Otherwise, there are cases we have to worry about where we're
  2179. // using a declaration for which we must emit a definition but where
  2180. // we might not find a top-level definition:
  2181. // - member functions defined inline in their classes
  2182. // - friend functions defined inline in some class
  2183. // - special member functions with implicit definitions
  2184. // If we ever change our AST traversal to walk into class methods,
  2185. // this will be unnecessary.
  2186. //
  2187. // We also don't emit a definition for a function if it's going to be an
  2188. // entry in a vtable, unless it's already marked as used.
  2189. } else if (getLangOpts().CPlusPlus && D) {
  2190. // Look for a declaration that's lexically in a record.
  2191. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2192. FD = FD->getPreviousDecl()) {
  2193. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2194. if (FD->doesThisDeclarationHaveABody()) {
  2195. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2196. break;
  2197. }
  2198. }
  2199. }
  2200. }
  2201. }
  2202. // Make sure the result is of the requested type.
  2203. if (!IsIncompleteFunction) {
  2204. assert(F->getType()->getElementType() == Ty);
  2205. return F;
  2206. }
  2207. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2208. return llvm::ConstantExpr::getBitCast(F, PTy);
  2209. }
  2210. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2211. /// non-null, then this function will use the specified type if it has to
  2212. /// create it (this occurs when we see a definition of the function).
  2213. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2214. llvm::Type *Ty,
  2215. bool ForVTable,
  2216. bool DontDefer,
  2217. ForDefinition_t IsForDefinition) {
  2218. // If there was no specific requested type, just convert it now.
  2219. if (!Ty) {
  2220. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2221. auto CanonTy = Context.getCanonicalType(FD->getType());
  2222. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  2223. }
  2224. StringRef MangledName = getMangledName(GD);
  2225. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2226. /*IsThunk=*/false, llvm::AttributeList(),
  2227. IsForDefinition);
  2228. }
  2229. static const FunctionDecl *
  2230. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2231. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2232. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2233. IdentifierInfo &CII = C.Idents.get(Name);
  2234. for (const auto &Result : DC->lookup(&CII))
  2235. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2236. return FD;
  2237. if (!C.getLangOpts().CPlusPlus)
  2238. return nullptr;
  2239. // Demangle the premangled name from getTerminateFn()
  2240. IdentifierInfo &CXXII =
  2241. (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
  2242. ? C.Idents.get("terminate")
  2243. : C.Idents.get(Name);
  2244. for (const auto &N : {"__cxxabiv1", "std"}) {
  2245. IdentifierInfo &NS = C.Idents.get(N);
  2246. for (const auto &Result : DC->lookup(&NS)) {
  2247. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2248. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2249. for (const auto &Result : LSD->lookup(&NS))
  2250. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2251. break;
  2252. if (ND)
  2253. for (const auto &Result : ND->lookup(&CXXII))
  2254. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2255. return FD;
  2256. }
  2257. }
  2258. return nullptr;
  2259. }
  2260. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2261. /// type and name.
  2262. llvm::Constant *
  2263. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2264. llvm::AttributeList ExtraAttrs,
  2265. bool Local) {
  2266. llvm::Constant *C =
  2267. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2268. /*DontDefer=*/false, /*IsThunk=*/false,
  2269. ExtraAttrs);
  2270. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2271. if (F->empty()) {
  2272. F->setCallingConv(getRuntimeCC());
  2273. if (!Local && getTriple().isOSBinFormatCOFF() &&
  2274. !getCodeGenOpts().LTOVisibilityPublicStd &&
  2275. !getTriple().isWindowsGNUEnvironment()) {
  2276. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2277. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2278. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2279. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2280. }
  2281. }
  2282. }
  2283. }
  2284. return C;
  2285. }
  2286. /// CreateBuiltinFunction - Create a new builtin function with the specified
  2287. /// type and name.
  2288. llvm::Constant *
  2289. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
  2290. llvm::AttributeList ExtraAttrs) {
  2291. llvm::Constant *C =
  2292. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2293. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  2294. if (auto *F = dyn_cast<llvm::Function>(C))
  2295. if (F->empty())
  2296. F->setCallingConv(getBuiltinCC());
  2297. return C;
  2298. }
  2299. /// isTypeConstant - Determine whether an object of this type can be emitted
  2300. /// as a constant.
  2301. ///
  2302. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2303. /// will not be considered. The caller will need to verify that the object is
  2304. /// not written to during its construction.
  2305. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2306. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2307. return false;
  2308. if (Context.getLangOpts().CPlusPlus) {
  2309. if (const CXXRecordDecl *Record
  2310. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2311. return ExcludeCtor && !Record->hasMutableFields() &&
  2312. Record->hasTrivialDestructor();
  2313. }
  2314. return true;
  2315. }
  2316. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2317. /// create and return an llvm GlobalVariable with the specified type. If there
  2318. /// is something in the module with the specified name, return it potentially
  2319. /// bitcasted to the right type.
  2320. ///
  2321. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2322. /// to set the attributes on the global when it is first created.
  2323. ///
  2324. /// If IsForDefinition is true, it is guranteed that an actual global with
  2325. /// type Ty will be returned, not conversion of a variable with the same
  2326. /// mangled name but some other type.
  2327. llvm::Constant *
  2328. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2329. llvm::PointerType *Ty,
  2330. const VarDecl *D,
  2331. ForDefinition_t IsForDefinition) {
  2332. // Lookup the entry, lazily creating it if necessary.
  2333. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2334. if (Entry) {
  2335. if (WeakRefReferences.erase(Entry)) {
  2336. if (D && !D->hasAttr<WeakAttr>())
  2337. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2338. }
  2339. // Handle dropped DLL attributes.
  2340. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2341. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2342. if (Entry->getType() == Ty)
  2343. return Entry;
  2344. // If there are two attempts to define the same mangled name, issue an
  2345. // error.
  2346. if (IsForDefinition && !Entry->isDeclaration()) {
  2347. GlobalDecl OtherGD;
  2348. const VarDecl *OtherD;
  2349. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2350. // to make sure that we issue an error only once.
  2351. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2352. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2353. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2354. OtherD->hasInit() &&
  2355. DiagnosedConflictingDefinitions.insert(D).second) {
  2356. getDiags().Report(D->getLocation(),
  2357. diag::err_duplicate_mangled_name);
  2358. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2359. diag::note_previous_definition);
  2360. }
  2361. }
  2362. // Make sure the result is of the correct type.
  2363. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2364. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2365. // (If global is requested for a definition, we always need to create a new
  2366. // global, not just return a bitcast.)
  2367. if (!IsForDefinition)
  2368. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2369. }
  2370. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2371. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2372. auto *GV = new llvm::GlobalVariable(
  2373. getModule(), Ty->getElementType(), false,
  2374. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2375. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2376. // If we already created a global with the same mangled name (but different
  2377. // type) before, take its name and remove it from its parent.
  2378. if (Entry) {
  2379. GV->takeName(Entry);
  2380. if (!Entry->use_empty()) {
  2381. llvm::Constant *NewPtrForOldDecl =
  2382. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2383. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2384. }
  2385. Entry->eraseFromParent();
  2386. }
  2387. // This is the first use or definition of a mangled name. If there is a
  2388. // deferred decl with this name, remember that we need to emit it at the end
  2389. // of the file.
  2390. auto DDI = DeferredDecls.find(MangledName);
  2391. if (DDI != DeferredDecls.end()) {
  2392. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2393. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2394. addDeferredDeclToEmit(DDI->second);
  2395. DeferredDecls.erase(DDI);
  2396. }
  2397. // Handle things which are present even on external declarations.
  2398. if (D) {
  2399. // FIXME: This code is overly simple and should be merged with other global
  2400. // handling.
  2401. GV->setConstant(isTypeConstant(D->getType(), false));
  2402. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2403. setLinkageForGV(GV, D);
  2404. if (D->getTLSKind()) {
  2405. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2406. CXXThreadLocals.push_back(D);
  2407. setTLSMode(GV, *D);
  2408. }
  2409. setGVProperties(GV, D);
  2410. // If required by the ABI, treat declarations of static data members with
  2411. // inline initializers as definitions.
  2412. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2413. EmitGlobalVarDefinition(D);
  2414. }
  2415. // Emit section information for extern variables.
  2416. if (D->hasExternalStorage()) {
  2417. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2418. GV->setSection(SA->getName());
  2419. }
  2420. // Handle XCore specific ABI requirements.
  2421. if (getTriple().getArch() == llvm::Triple::xcore &&
  2422. D->getLanguageLinkage() == CLanguageLinkage &&
  2423. D->getType().isConstant(Context) &&
  2424. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2425. GV->setSection(".cp.rodata");
  2426. // Check if we a have a const declaration with an initializer, we may be
  2427. // able to emit it as available_externally to expose it's value to the
  2428. // optimizer.
  2429. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2430. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2431. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2432. const auto *Record =
  2433. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2434. bool HasMutableFields = Record && Record->hasMutableFields();
  2435. if (!HasMutableFields) {
  2436. const VarDecl *InitDecl;
  2437. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2438. if (InitExpr) {
  2439. ConstantEmitter emitter(*this);
  2440. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2441. if (Init) {
  2442. auto *InitType = Init->getType();
  2443. if (GV->getType()->getElementType() != InitType) {
  2444. // The type of the initializer does not match the definition.
  2445. // This happens when an initializer has a different type from
  2446. // the type of the global (because of padding at the end of a
  2447. // structure for instance).
  2448. GV->setName(StringRef());
  2449. // Make a new global with the correct type, this is now guaranteed
  2450. // to work.
  2451. auto *NewGV = cast<llvm::GlobalVariable>(
  2452. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2453. // Erase the old global, since it is no longer used.
  2454. GV->eraseFromParent();
  2455. GV = NewGV;
  2456. } else {
  2457. GV->setInitializer(Init);
  2458. GV->setConstant(true);
  2459. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2460. }
  2461. emitter.finalize(GV);
  2462. }
  2463. }
  2464. }
  2465. }
  2466. }
  2467. LangAS ExpectedAS =
  2468. D ? D->getType().getAddressSpace()
  2469. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  2470. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2471. Ty->getPointerAddressSpace());
  2472. if (AddrSpace != ExpectedAS)
  2473. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2474. ExpectedAS, Ty);
  2475. return GV;
  2476. }
  2477. llvm::Constant *
  2478. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2479. ForDefinition_t IsForDefinition) {
  2480. const Decl *D = GD.getDecl();
  2481. if (isa<CXXConstructorDecl>(D))
  2482. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2483. getFromCtorType(GD.getCtorType()),
  2484. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2485. /*DontDefer=*/false, IsForDefinition);
  2486. else if (isa<CXXDestructorDecl>(D))
  2487. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2488. getFromDtorType(GD.getDtorType()),
  2489. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2490. /*DontDefer=*/false, IsForDefinition);
  2491. else if (isa<CXXMethodDecl>(D)) {
  2492. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2493. cast<CXXMethodDecl>(D));
  2494. auto Ty = getTypes().GetFunctionType(*FInfo);
  2495. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2496. IsForDefinition);
  2497. } else if (isa<FunctionDecl>(D)) {
  2498. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2499. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2500. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2501. IsForDefinition);
  2502. } else
  2503. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2504. IsForDefinition);
  2505. }
  2506. llvm::GlobalVariable *
  2507. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  2508. llvm::Type *Ty,
  2509. llvm::GlobalValue::LinkageTypes Linkage) {
  2510. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2511. llvm::GlobalVariable *OldGV = nullptr;
  2512. if (GV) {
  2513. // Check if the variable has the right type.
  2514. if (GV->getType()->getElementType() == Ty)
  2515. return GV;
  2516. // Because C++ name mangling, the only way we can end up with an already
  2517. // existing global with the same name is if it has been declared extern "C".
  2518. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2519. OldGV = GV;
  2520. }
  2521. // Create a new variable.
  2522. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2523. Linkage, nullptr, Name);
  2524. if (OldGV) {
  2525. // Replace occurrences of the old variable if needed.
  2526. GV->takeName(OldGV);
  2527. if (!OldGV->use_empty()) {
  2528. llvm::Constant *NewPtrForOldDecl =
  2529. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2530. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2531. }
  2532. OldGV->eraseFromParent();
  2533. }
  2534. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2535. !GV->hasAvailableExternallyLinkage())
  2536. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2537. return GV;
  2538. }
  2539. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2540. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2541. /// then it will be created with the specified type instead of whatever the
  2542. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  2543. /// that an actual global with type Ty will be returned, not conversion of a
  2544. /// variable with the same mangled name but some other type.
  2545. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2546. llvm::Type *Ty,
  2547. ForDefinition_t IsForDefinition) {
  2548. assert(D->hasGlobalStorage() && "Not a global variable");
  2549. QualType ASTTy = D->getType();
  2550. if (!Ty)
  2551. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2552. llvm::PointerType *PTy =
  2553. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2554. StringRef MangledName = getMangledName(D);
  2555. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2556. }
  2557. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2558. /// specified type and name.
  2559. llvm::Constant *
  2560. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2561. StringRef Name) {
  2562. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2563. }
  2564. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2565. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2566. StringRef MangledName = getMangledName(D);
  2567. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2568. // We already have a definition, not declaration, with the same mangled name.
  2569. // Emitting of declaration is not required (and actually overwrites emitted
  2570. // definition).
  2571. if (GV && !GV->isDeclaration())
  2572. return;
  2573. // If we have not seen a reference to this variable yet, place it into the
  2574. // deferred declarations table to be emitted if needed later.
  2575. if (!MustBeEmitted(D) && !GV) {
  2576. DeferredDecls[MangledName] = D;
  2577. return;
  2578. }
  2579. // The tentative definition is the only definition.
  2580. EmitGlobalVarDefinition(D);
  2581. }
  2582. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2583. return Context.toCharUnitsFromBits(
  2584. getDataLayout().getTypeStoreSizeInBits(Ty));
  2585. }
  2586. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2587. LangAS AddrSpace = LangAS::Default;
  2588. if (LangOpts.OpenCL) {
  2589. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  2590. assert(AddrSpace == LangAS::opencl_global ||
  2591. AddrSpace == LangAS::opencl_constant ||
  2592. AddrSpace == LangAS::opencl_local ||
  2593. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2594. return AddrSpace;
  2595. }
  2596. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2597. if (D && D->hasAttr<CUDAConstantAttr>())
  2598. return LangAS::cuda_constant;
  2599. else if (D && D->hasAttr<CUDASharedAttr>())
  2600. return LangAS::cuda_shared;
  2601. else
  2602. return LangAS::cuda_device;
  2603. }
  2604. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2605. }
  2606. template<typename SomeDecl>
  2607. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2608. llvm::GlobalValue *GV) {
  2609. if (!getLangOpts().CPlusPlus)
  2610. return;
  2611. // Must have 'used' attribute, or else inline assembly can't rely on
  2612. // the name existing.
  2613. if (!D->template hasAttr<UsedAttr>())
  2614. return;
  2615. // Must have internal linkage and an ordinary name.
  2616. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2617. return;
  2618. // Must be in an extern "C" context. Entities declared directly within
  2619. // a record are not extern "C" even if the record is in such a context.
  2620. const SomeDecl *First = D->getFirstDecl();
  2621. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2622. return;
  2623. // OK, this is an internal linkage entity inside an extern "C" linkage
  2624. // specification. Make a note of that so we can give it the "expected"
  2625. // mangled name if nothing else is using that name.
  2626. std::pair<StaticExternCMap::iterator, bool> R =
  2627. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2628. // If we have multiple internal linkage entities with the same name
  2629. // in extern "C" regions, none of them gets that name.
  2630. if (!R.second)
  2631. R.first->second = nullptr;
  2632. }
  2633. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2634. if (!CGM.supportsCOMDAT())
  2635. return false;
  2636. if (D.hasAttr<SelectAnyAttr>())
  2637. return true;
  2638. GVALinkage Linkage;
  2639. if (auto *VD = dyn_cast<VarDecl>(&D))
  2640. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2641. else
  2642. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2643. switch (Linkage) {
  2644. case GVA_Internal:
  2645. case GVA_AvailableExternally:
  2646. case GVA_StrongExternal:
  2647. return false;
  2648. case GVA_DiscardableODR:
  2649. case GVA_StrongODR:
  2650. return true;
  2651. }
  2652. llvm_unreachable("No such linkage");
  2653. }
  2654. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2655. llvm::GlobalObject &GO) {
  2656. if (!shouldBeInCOMDAT(*this, D))
  2657. return;
  2658. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2659. }
  2660. /// Pass IsTentative as true if you want to create a tentative definition.
  2661. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2662. bool IsTentative) {
  2663. // OpenCL global variables of sampler type are translated to function calls,
  2664. // therefore no need to be translated.
  2665. QualType ASTTy = D->getType();
  2666. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2667. return;
  2668. // If this is OpenMP device, check if it is legal to emit this global
  2669. // normally.
  2670. if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
  2671. OpenMPRuntime->emitTargetGlobalVariable(D))
  2672. return;
  2673. llvm::Constant *Init = nullptr;
  2674. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2675. bool NeedsGlobalCtor = false;
  2676. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2677. const VarDecl *InitDecl;
  2678. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2679. Optional<ConstantEmitter> emitter;
  2680. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2681. // as part of their declaration." Sema has already checked for
  2682. // error cases, so we just need to set Init to UndefValue.
  2683. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2684. D->hasAttr<CUDASharedAttr>())
  2685. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2686. else if (!InitExpr) {
  2687. // This is a tentative definition; tentative definitions are
  2688. // implicitly initialized with { 0 }.
  2689. //
  2690. // Note that tentative definitions are only emitted at the end of
  2691. // a translation unit, so they should never have incomplete
  2692. // type. In addition, EmitTentativeDefinition makes sure that we
  2693. // never attempt to emit a tentative definition if a real one
  2694. // exists. A use may still exists, however, so we still may need
  2695. // to do a RAUW.
  2696. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2697. Init = EmitNullConstant(D->getType());
  2698. } else {
  2699. initializedGlobalDecl = GlobalDecl(D);
  2700. emitter.emplace(*this);
  2701. Init = emitter->tryEmitForInitializer(*InitDecl);
  2702. if (!Init) {
  2703. QualType T = InitExpr->getType();
  2704. if (D->getType()->isReferenceType())
  2705. T = D->getType();
  2706. if (getLangOpts().CPlusPlus) {
  2707. Init = EmitNullConstant(T);
  2708. NeedsGlobalCtor = true;
  2709. } else {
  2710. ErrorUnsupported(D, "static initializer");
  2711. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2712. }
  2713. } else {
  2714. // We don't need an initializer, so remove the entry for the delayed
  2715. // initializer position (just in case this entry was delayed) if we
  2716. // also don't need to register a destructor.
  2717. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2718. DelayedCXXInitPosition.erase(D);
  2719. }
  2720. }
  2721. llvm::Type* InitType = Init->getType();
  2722. llvm::Constant *Entry =
  2723. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2724. // Strip off a bitcast if we got one back.
  2725. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2726. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2727. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2728. // All zero index gep.
  2729. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2730. Entry = CE->getOperand(0);
  2731. }
  2732. // Entry is now either a Function or GlobalVariable.
  2733. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2734. // We have a definition after a declaration with the wrong type.
  2735. // We must make a new GlobalVariable* and update everything that used OldGV
  2736. // (a declaration or tentative definition) with the new GlobalVariable*
  2737. // (which will be a definition).
  2738. //
  2739. // This happens if there is a prototype for a global (e.g.
  2740. // "extern int x[];") and then a definition of a different type (e.g.
  2741. // "int x[10];"). This also happens when an initializer has a different type
  2742. // from the type of the global (this happens with unions).
  2743. if (!GV || GV->getType()->getElementType() != InitType ||
  2744. GV->getType()->getAddressSpace() !=
  2745. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  2746. // Move the old entry aside so that we'll create a new one.
  2747. Entry->setName(StringRef());
  2748. // Make a new global with the correct type, this is now guaranteed to work.
  2749. GV = cast<llvm::GlobalVariable>(
  2750. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2751. // Replace all uses of the old global with the new global
  2752. llvm::Constant *NewPtrForOldDecl =
  2753. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2754. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2755. // Erase the old global, since it is no longer used.
  2756. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2757. }
  2758. MaybeHandleStaticInExternC(D, GV);
  2759. if (D->hasAttr<AnnotateAttr>())
  2760. AddGlobalAnnotations(D, GV);
  2761. // Set the llvm linkage type as appropriate.
  2762. llvm::GlobalValue::LinkageTypes Linkage =
  2763. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2764. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2765. // the device. [...]"
  2766. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2767. // __device__, declares a variable that: [...]
  2768. // Is accessible from all the threads within the grid and from the host
  2769. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2770. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2771. if (GV && LangOpts.CUDA) {
  2772. if (LangOpts.CUDAIsDevice) {
  2773. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2774. GV->setExternallyInitialized(true);
  2775. } else {
  2776. // Host-side shadows of external declarations of device-side
  2777. // global variables become internal definitions. These have to
  2778. // be internal in order to prevent name conflicts with global
  2779. // host variables with the same name in a different TUs.
  2780. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2781. Linkage = llvm::GlobalValue::InternalLinkage;
  2782. // Shadow variables and their properties must be registered
  2783. // with CUDA runtime.
  2784. unsigned Flags = 0;
  2785. if (!D->hasDefinition())
  2786. Flags |= CGCUDARuntime::ExternDeviceVar;
  2787. if (D->hasAttr<CUDAConstantAttr>())
  2788. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2789. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2790. } else if (D->hasAttr<CUDASharedAttr>())
  2791. // __shared__ variables are odd. Shadows do get created, but
  2792. // they are not registered with the CUDA runtime, so they
  2793. // can't really be used to access their device-side
  2794. // counterparts. It's not clear yet whether it's nvcc's bug or
  2795. // a feature, but we've got to do the same for compatibility.
  2796. Linkage = llvm::GlobalValue::InternalLinkage;
  2797. }
  2798. }
  2799. GV->setInitializer(Init);
  2800. if (emitter) emitter->finalize(GV);
  2801. // If it is safe to mark the global 'constant', do so now.
  2802. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2803. isTypeConstant(D->getType(), true));
  2804. // If it is in a read-only section, mark it 'constant'.
  2805. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2806. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2807. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2808. GV->setConstant(true);
  2809. }
  2810. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2811. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2812. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2813. // copies within a linkage unit; otherwise, the backing variable has
  2814. // internal linkage and all accesses should just be calls to the
  2815. // Itanium-specified entry point, which has the normal linkage of the
  2816. // variable. This is to preserve the ability to change the implementation
  2817. // behind the scenes.
  2818. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2819. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2820. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2821. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2822. Linkage = llvm::GlobalValue::InternalLinkage;
  2823. GV->setLinkage(Linkage);
  2824. if (D->hasAttr<DLLImportAttr>())
  2825. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2826. else if (D->hasAttr<DLLExportAttr>())
  2827. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2828. else
  2829. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2830. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  2831. // common vars aren't constant even if declared const.
  2832. GV->setConstant(false);
  2833. // Tentative definition of global variables may be initialized with
  2834. // non-zero null pointers. In this case they should have weak linkage
  2835. // since common linkage must have zero initializer and must not have
  2836. // explicit section therefore cannot have non-zero initial value.
  2837. if (!GV->getInitializer()->isNullValue())
  2838. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  2839. }
  2840. setNonAliasAttributes(D, GV);
  2841. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2842. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2843. CXXThreadLocals.push_back(D);
  2844. setTLSMode(GV, *D);
  2845. }
  2846. maybeSetTrivialComdat(*D, *GV);
  2847. // Emit the initializer function if necessary.
  2848. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2849. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2850. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2851. // Emit global variable debug information.
  2852. if (CGDebugInfo *DI = getModuleDebugInfo())
  2853. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2854. DI->EmitGlobalVariable(GV, D);
  2855. }
  2856. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2857. CodeGenModule &CGM, const VarDecl *D,
  2858. bool NoCommon) {
  2859. // Don't give variables common linkage if -fno-common was specified unless it
  2860. // was overridden by a NoCommon attribute.
  2861. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2862. return true;
  2863. // C11 6.9.2/2:
  2864. // A declaration of an identifier for an object that has file scope without
  2865. // an initializer, and without a storage-class specifier or with the
  2866. // storage-class specifier static, constitutes a tentative definition.
  2867. if (D->getInit() || D->hasExternalStorage())
  2868. return true;
  2869. // A variable cannot be both common and exist in a section.
  2870. if (D->hasAttr<SectionAttr>())
  2871. return true;
  2872. // A variable cannot be both common and exist in a section.
  2873. // We dont try to determine which is the right section in the front-end.
  2874. // If no specialized section name is applicable, it will resort to default.
  2875. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  2876. D->hasAttr<PragmaClangDataSectionAttr>() ||
  2877. D->hasAttr<PragmaClangRodataSectionAttr>())
  2878. return true;
  2879. // Thread local vars aren't considered common linkage.
  2880. if (D->getTLSKind())
  2881. return true;
  2882. // Tentative definitions marked with WeakImportAttr are true definitions.
  2883. if (D->hasAttr<WeakImportAttr>())
  2884. return true;
  2885. // A variable cannot be both common and exist in a comdat.
  2886. if (shouldBeInCOMDAT(CGM, *D))
  2887. return true;
  2888. // Declarations with a required alignment do not have common linkage in MSVC
  2889. // mode.
  2890. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2891. if (D->hasAttr<AlignedAttr>())
  2892. return true;
  2893. QualType VarType = D->getType();
  2894. if (Context.isAlignmentRequired(VarType))
  2895. return true;
  2896. if (const auto *RT = VarType->getAs<RecordType>()) {
  2897. const RecordDecl *RD = RT->getDecl();
  2898. for (const FieldDecl *FD : RD->fields()) {
  2899. if (FD->isBitField())
  2900. continue;
  2901. if (FD->hasAttr<AlignedAttr>())
  2902. return true;
  2903. if (Context.isAlignmentRequired(FD->getType()))
  2904. return true;
  2905. }
  2906. }
  2907. }
  2908. return false;
  2909. }
  2910. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2911. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2912. if (Linkage == GVA_Internal)
  2913. return llvm::Function::InternalLinkage;
  2914. if (D->hasAttr<WeakAttr>()) {
  2915. if (IsConstantVariable)
  2916. return llvm::GlobalVariable::WeakODRLinkage;
  2917. else
  2918. return llvm::GlobalVariable::WeakAnyLinkage;
  2919. }
  2920. // We are guaranteed to have a strong definition somewhere else,
  2921. // so we can use available_externally linkage.
  2922. if (Linkage == GVA_AvailableExternally)
  2923. return llvm::GlobalValue::AvailableExternallyLinkage;
  2924. // Note that Apple's kernel linker doesn't support symbol
  2925. // coalescing, so we need to avoid linkonce and weak linkages there.
  2926. // Normally, this means we just map to internal, but for explicit
  2927. // instantiations we'll map to external.
  2928. // In C++, the compiler has to emit a definition in every translation unit
  2929. // that references the function. We should use linkonce_odr because
  2930. // a) if all references in this translation unit are optimized away, we
  2931. // don't need to codegen it. b) if the function persists, it needs to be
  2932. // merged with other definitions. c) C++ has the ODR, so we know the
  2933. // definition is dependable.
  2934. if (Linkage == GVA_DiscardableODR)
  2935. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2936. : llvm::Function::InternalLinkage;
  2937. // An explicit instantiation of a template has weak linkage, since
  2938. // explicit instantiations can occur in multiple translation units
  2939. // and must all be equivalent. However, we are not allowed to
  2940. // throw away these explicit instantiations.
  2941. //
  2942. // We don't currently support CUDA device code spread out across multiple TUs,
  2943. // so say that CUDA templates are either external (for kernels) or internal.
  2944. // This lets llvm perform aggressive inter-procedural optimizations.
  2945. if (Linkage == GVA_StrongODR) {
  2946. if (Context.getLangOpts().AppleKext)
  2947. return llvm::Function::ExternalLinkage;
  2948. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2949. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2950. : llvm::Function::InternalLinkage;
  2951. return llvm::Function::WeakODRLinkage;
  2952. }
  2953. // C++ doesn't have tentative definitions and thus cannot have common
  2954. // linkage.
  2955. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2956. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2957. CodeGenOpts.NoCommon))
  2958. return llvm::GlobalVariable::CommonLinkage;
  2959. // selectany symbols are externally visible, so use weak instead of
  2960. // linkonce. MSVC optimizes away references to const selectany globals, so
  2961. // all definitions should be the same and ODR linkage should be used.
  2962. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2963. if (D->hasAttr<SelectAnyAttr>())
  2964. return llvm::GlobalVariable::WeakODRLinkage;
  2965. // Otherwise, we have strong external linkage.
  2966. assert(Linkage == GVA_StrongExternal);
  2967. return llvm::GlobalVariable::ExternalLinkage;
  2968. }
  2969. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2970. const VarDecl *VD, bool IsConstant) {
  2971. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2972. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2973. }
  2974. /// Replace the uses of a function that was declared with a non-proto type.
  2975. /// We want to silently drop extra arguments from call sites
  2976. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2977. llvm::Function *newFn) {
  2978. // Fast path.
  2979. if (old->use_empty()) return;
  2980. llvm::Type *newRetTy = newFn->getReturnType();
  2981. SmallVector<llvm::Value*, 4> newArgs;
  2982. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2983. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2984. ui != ue; ) {
  2985. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2986. llvm::User *user = use->getUser();
  2987. // Recognize and replace uses of bitcasts. Most calls to
  2988. // unprototyped functions will use bitcasts.
  2989. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2990. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2991. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2992. continue;
  2993. }
  2994. // Recognize calls to the function.
  2995. llvm::CallSite callSite(user);
  2996. if (!callSite) continue;
  2997. if (!callSite.isCallee(&*use)) continue;
  2998. // If the return types don't match exactly, then we can't
  2999. // transform this call unless it's dead.
  3000. if (callSite->getType() != newRetTy && !callSite->use_empty())
  3001. continue;
  3002. // Get the call site's attribute list.
  3003. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  3004. llvm::AttributeList oldAttrs = callSite.getAttributes();
  3005. // If the function was passed too few arguments, don't transform.
  3006. unsigned newNumArgs = newFn->arg_size();
  3007. if (callSite.arg_size() < newNumArgs) continue;
  3008. // If extra arguments were passed, we silently drop them.
  3009. // If any of the types mismatch, we don't transform.
  3010. unsigned argNo = 0;
  3011. bool dontTransform = false;
  3012. for (llvm::Argument &A : newFn->args()) {
  3013. if (callSite.getArgument(argNo)->getType() != A.getType()) {
  3014. dontTransform = true;
  3015. break;
  3016. }
  3017. // Add any parameter attributes.
  3018. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  3019. argNo++;
  3020. }
  3021. if (dontTransform)
  3022. continue;
  3023. // Okay, we can transform this. Create the new call instruction and copy
  3024. // over the required information.
  3025. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  3026. // Copy over any operand bundles.
  3027. callSite.getOperandBundlesAsDefs(newBundles);
  3028. llvm::CallSite newCall;
  3029. if (callSite.isCall()) {
  3030. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  3031. callSite.getInstruction());
  3032. } else {
  3033. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  3034. newCall = llvm::InvokeInst::Create(newFn,
  3035. oldInvoke->getNormalDest(),
  3036. oldInvoke->getUnwindDest(),
  3037. newArgs, newBundles, "",
  3038. callSite.getInstruction());
  3039. }
  3040. newArgs.clear(); // for the next iteration
  3041. if (!newCall->getType()->isVoidTy())
  3042. newCall->takeName(callSite.getInstruction());
  3043. newCall.setAttributes(llvm::AttributeList::get(
  3044. newFn->getContext(), oldAttrs.getFnAttributes(),
  3045. oldAttrs.getRetAttributes(), newArgAttrs));
  3046. newCall.setCallingConv(callSite.getCallingConv());
  3047. // Finally, remove the old call, replacing any uses with the new one.
  3048. if (!callSite->use_empty())
  3049. callSite->replaceAllUsesWith(newCall.getInstruction());
  3050. // Copy debug location attached to CI.
  3051. if (callSite->getDebugLoc())
  3052. newCall->setDebugLoc(callSite->getDebugLoc());
  3053. callSite->eraseFromParent();
  3054. }
  3055. }
  3056. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  3057. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  3058. /// existing call uses of the old function in the module, this adjusts them to
  3059. /// call the new function directly.
  3060. ///
  3061. /// This is not just a cleanup: the always_inline pass requires direct calls to
  3062. /// functions to be able to inline them. If there is a bitcast in the way, it
  3063. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  3064. /// run at -O0.
  3065. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  3066. llvm::Function *NewFn) {
  3067. // If we're redefining a global as a function, don't transform it.
  3068. if (!isa<llvm::Function>(Old)) return;
  3069. replaceUsesOfNonProtoConstant(Old, NewFn);
  3070. }
  3071. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3072. auto DK = VD->isThisDeclarationADefinition();
  3073. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3074. return;
  3075. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3076. // If we have a definition, this might be a deferred decl. If the
  3077. // instantiation is explicit, make sure we emit it at the end.
  3078. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3079. GetAddrOfGlobalVar(VD);
  3080. EmitTopLevelDecl(VD);
  3081. }
  3082. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3083. llvm::GlobalValue *GV) {
  3084. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3085. // Compute the function info and LLVM type.
  3086. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3087. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3088. // Get or create the prototype for the function.
  3089. if (!GV || (GV->getType()->getElementType() != Ty))
  3090. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3091. /*DontDefer=*/true,
  3092. ForDefinition));
  3093. // Already emitted.
  3094. if (!GV->isDeclaration())
  3095. return;
  3096. // We need to set linkage and visibility on the function before
  3097. // generating code for it because various parts of IR generation
  3098. // want to propagate this information down (e.g. to local static
  3099. // declarations).
  3100. auto *Fn = cast<llvm::Function>(GV);
  3101. setFunctionLinkage(GD, Fn);
  3102. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3103. setGVProperties(Fn, GD);
  3104. MaybeHandleStaticInExternC(D, Fn);
  3105. maybeSetTrivialComdat(*D, *Fn);
  3106. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3107. setNonAliasAttributes(GD, Fn);
  3108. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3109. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3110. AddGlobalCtor(Fn, CA->getPriority());
  3111. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3112. AddGlobalDtor(Fn, DA->getPriority());
  3113. if (D->hasAttr<AnnotateAttr>())
  3114. AddGlobalAnnotations(D, Fn);
  3115. }
  3116. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3117. const auto *D = cast<ValueDecl>(GD.getDecl());
  3118. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3119. assert(AA && "Not an alias?");
  3120. StringRef MangledName = getMangledName(GD);
  3121. if (AA->getAliasee() == MangledName) {
  3122. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3123. return;
  3124. }
  3125. // If there is a definition in the module, then it wins over the alias.
  3126. // This is dubious, but allow it to be safe. Just ignore the alias.
  3127. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3128. if (Entry && !Entry->isDeclaration())
  3129. return;
  3130. Aliases.push_back(GD);
  3131. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3132. // Create a reference to the named value. This ensures that it is emitted
  3133. // if a deferred decl.
  3134. llvm::Constant *Aliasee;
  3135. if (isa<llvm::FunctionType>(DeclTy))
  3136. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3137. /*ForVTable=*/false);
  3138. else
  3139. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3140. llvm::PointerType::getUnqual(DeclTy),
  3141. /*D=*/nullptr);
  3142. // Create the new alias itself, but don't set a name yet.
  3143. auto *GA = llvm::GlobalAlias::create(
  3144. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  3145. if (Entry) {
  3146. if (GA->getAliasee() == Entry) {
  3147. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3148. return;
  3149. }
  3150. assert(Entry->isDeclaration());
  3151. // If there is a declaration in the module, then we had an extern followed
  3152. // by the alias, as in:
  3153. // extern int test6();
  3154. // ...
  3155. // int test6() __attribute__((alias("test7")));
  3156. //
  3157. // Remove it and replace uses of it with the alias.
  3158. GA->takeName(Entry);
  3159. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3160. Entry->getType()));
  3161. Entry->eraseFromParent();
  3162. } else {
  3163. GA->setName(MangledName);
  3164. }
  3165. // Set attributes which are particular to an alias; this is a
  3166. // specialization of the attributes which may be set on a global
  3167. // variable/function.
  3168. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3169. D->isWeakImported()) {
  3170. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3171. }
  3172. if (const auto *VD = dyn_cast<VarDecl>(D))
  3173. if (VD->getTLSKind())
  3174. setTLSMode(GA, *VD);
  3175. SetCommonAttributes(GD, GA);
  3176. }
  3177. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3178. const auto *D = cast<ValueDecl>(GD.getDecl());
  3179. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3180. assert(IFA && "Not an ifunc?");
  3181. StringRef MangledName = getMangledName(GD);
  3182. if (IFA->getResolver() == MangledName) {
  3183. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3184. return;
  3185. }
  3186. // Report an error if some definition overrides ifunc.
  3187. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3188. if (Entry && !Entry->isDeclaration()) {
  3189. GlobalDecl OtherGD;
  3190. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3191. DiagnosedConflictingDefinitions.insert(GD).second) {
  3192. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  3193. Diags.Report(OtherGD.getDecl()->getLocation(),
  3194. diag::note_previous_definition);
  3195. }
  3196. return;
  3197. }
  3198. Aliases.push_back(GD);
  3199. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3200. llvm::Constant *Resolver =
  3201. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3202. /*ForVTable=*/false);
  3203. llvm::GlobalIFunc *GIF =
  3204. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3205. "", Resolver, &getModule());
  3206. if (Entry) {
  3207. if (GIF->getResolver() == Entry) {
  3208. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3209. return;
  3210. }
  3211. assert(Entry->isDeclaration());
  3212. // If there is a declaration in the module, then we had an extern followed
  3213. // by the ifunc, as in:
  3214. // extern int test();
  3215. // ...
  3216. // int test() __attribute__((ifunc("resolver")));
  3217. //
  3218. // Remove it and replace uses of it with the ifunc.
  3219. GIF->takeName(Entry);
  3220. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3221. Entry->getType()));
  3222. Entry->eraseFromParent();
  3223. } else
  3224. GIF->setName(MangledName);
  3225. SetCommonAttributes(GD, GIF);
  3226. }
  3227. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3228. ArrayRef<llvm::Type*> Tys) {
  3229. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3230. Tys);
  3231. }
  3232. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3233. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3234. const StringLiteral *Literal, bool TargetIsLSB,
  3235. bool &IsUTF16, unsigned &StringLength) {
  3236. StringRef String = Literal->getString();
  3237. unsigned NumBytes = String.size();
  3238. // Check for simple case.
  3239. if (!Literal->containsNonAsciiOrNull()) {
  3240. StringLength = NumBytes;
  3241. return *Map.insert(std::make_pair(String, nullptr)).first;
  3242. }
  3243. // Otherwise, convert the UTF8 literals into a string of shorts.
  3244. IsUTF16 = true;
  3245. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3246. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3247. llvm::UTF16 *ToPtr = &ToBuf[0];
  3248. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3249. ToPtr + NumBytes, llvm::strictConversion);
  3250. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3251. StringLength = ToPtr - &ToBuf[0];
  3252. // Add an explicit null.
  3253. *ToPtr = 0;
  3254. return *Map.insert(std::make_pair(
  3255. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3256. (StringLength + 1) * 2),
  3257. nullptr)).first;
  3258. }
  3259. ConstantAddress
  3260. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3261. unsigned StringLength = 0;
  3262. bool isUTF16 = false;
  3263. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3264. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3265. getDataLayout().isLittleEndian(), isUTF16,
  3266. StringLength);
  3267. if (auto *C = Entry.second)
  3268. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3269. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3270. llvm::Constant *Zeros[] = { Zero, Zero };
  3271. // If we don't already have it, get __CFConstantStringClassReference.
  3272. if (!CFConstantStringClassRef) {
  3273. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3274. Ty = llvm::ArrayType::get(Ty, 0);
  3275. llvm::Constant *GV =
  3276. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  3277. if (getTriple().isOSBinFormatCOFF()) {
  3278. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  3279. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  3280. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3281. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  3282. const VarDecl *VD = nullptr;
  3283. for (const auto &Result : DC->lookup(&II))
  3284. if ((VD = dyn_cast<VarDecl>(Result)))
  3285. break;
  3286. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  3287. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3288. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3289. } else {
  3290. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3291. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3292. }
  3293. }
  3294. // Decay array -> ptr
  3295. CFConstantStringClassRef =
  3296. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  3297. }
  3298. QualType CFTy = getContext().getCFConstantStringType();
  3299. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  3300. ConstantInitBuilder Builder(*this);
  3301. auto Fields = Builder.beginStruct(STy);
  3302. // Class pointer.
  3303. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3304. // Flags.
  3305. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3306. // String pointer.
  3307. llvm::Constant *C = nullptr;
  3308. if (isUTF16) {
  3309. auto Arr = llvm::makeArrayRef(
  3310. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3311. Entry.first().size() / 2);
  3312. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3313. } else {
  3314. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3315. }
  3316. // Note: -fwritable-strings doesn't make the backing store strings of
  3317. // CFStrings writable. (See <rdar://problem/10657500>)
  3318. auto *GV =
  3319. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3320. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3321. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3322. // Don't enforce the target's minimum global alignment, since the only use
  3323. // of the string is via this class initializer.
  3324. CharUnits Align = isUTF16
  3325. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  3326. : getContext().getTypeAlignInChars(getContext().CharTy);
  3327. GV->setAlignment(Align.getQuantity());
  3328. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3329. // Without it LLVM can merge the string with a non unnamed_addr one during
  3330. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3331. if (getTriple().isOSBinFormatMachO())
  3332. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3333. : "__TEXT,__cstring,cstring_literals");
  3334. // String.
  3335. llvm::Constant *Str =
  3336. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3337. if (isUTF16)
  3338. // Cast the UTF16 string to the correct type.
  3339. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3340. Fields.add(Str);
  3341. // String length.
  3342. auto Ty = getTypes().ConvertType(getContext().LongTy);
  3343. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  3344. CharUnits Alignment = getPointerAlign();
  3345. // The struct.
  3346. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3347. /*isConstant=*/false,
  3348. llvm::GlobalVariable::PrivateLinkage);
  3349. switch (getTriple().getObjectFormat()) {
  3350. case llvm::Triple::UnknownObjectFormat:
  3351. llvm_unreachable("unknown file format");
  3352. case llvm::Triple::COFF:
  3353. case llvm::Triple::ELF:
  3354. case llvm::Triple::Wasm:
  3355. GV->setSection("cfstring");
  3356. break;
  3357. case llvm::Triple::MachO:
  3358. GV->setSection("__DATA,__cfstring");
  3359. break;
  3360. }
  3361. Entry.second = GV;
  3362. return ConstantAddress(GV, Alignment);
  3363. }
  3364. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3365. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3366. }
  3367. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3368. if (ObjCFastEnumerationStateType.isNull()) {
  3369. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3370. D->startDefinition();
  3371. QualType FieldTypes[] = {
  3372. Context.UnsignedLongTy,
  3373. Context.getPointerType(Context.getObjCIdType()),
  3374. Context.getPointerType(Context.UnsignedLongTy),
  3375. Context.getConstantArrayType(Context.UnsignedLongTy,
  3376. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3377. };
  3378. for (size_t i = 0; i < 4; ++i) {
  3379. FieldDecl *Field = FieldDecl::Create(Context,
  3380. D,
  3381. SourceLocation(),
  3382. SourceLocation(), nullptr,
  3383. FieldTypes[i], /*TInfo=*/nullptr,
  3384. /*BitWidth=*/nullptr,
  3385. /*Mutable=*/false,
  3386. ICIS_NoInit);
  3387. Field->setAccess(AS_public);
  3388. D->addDecl(Field);
  3389. }
  3390. D->completeDefinition();
  3391. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3392. }
  3393. return ObjCFastEnumerationStateType;
  3394. }
  3395. llvm::Constant *
  3396. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3397. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3398. // Don't emit it as the address of the string, emit the string data itself
  3399. // as an inline array.
  3400. if (E->getCharByteWidth() == 1) {
  3401. SmallString<64> Str(E->getString());
  3402. // Resize the string to the right size, which is indicated by its type.
  3403. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3404. Str.resize(CAT->getSize().getZExtValue());
  3405. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3406. }
  3407. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3408. llvm::Type *ElemTy = AType->getElementType();
  3409. unsigned NumElements = AType->getNumElements();
  3410. // Wide strings have either 2-byte or 4-byte elements.
  3411. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3412. SmallVector<uint16_t, 32> Elements;
  3413. Elements.reserve(NumElements);
  3414. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3415. Elements.push_back(E->getCodeUnit(i));
  3416. Elements.resize(NumElements);
  3417. return llvm::ConstantDataArray::get(VMContext, Elements);
  3418. }
  3419. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3420. SmallVector<uint32_t, 32> Elements;
  3421. Elements.reserve(NumElements);
  3422. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3423. Elements.push_back(E->getCodeUnit(i));
  3424. Elements.resize(NumElements);
  3425. return llvm::ConstantDataArray::get(VMContext, Elements);
  3426. }
  3427. static llvm::GlobalVariable *
  3428. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3429. CodeGenModule &CGM, StringRef GlobalName,
  3430. CharUnits Alignment) {
  3431. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3432. unsigned AddrSpace = 0;
  3433. if (CGM.getLangOpts().OpenCL)
  3434. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  3435. llvm::Module &M = CGM.getModule();
  3436. // Create a global variable for this string
  3437. auto *GV = new llvm::GlobalVariable(
  3438. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3439. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3440. GV->setAlignment(Alignment.getQuantity());
  3441. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3442. if (GV->isWeakForLinker()) {
  3443. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3444. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3445. }
  3446. return GV;
  3447. }
  3448. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3449. /// constant array for the given string literal.
  3450. ConstantAddress
  3451. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3452. StringRef Name) {
  3453. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3454. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3455. llvm::GlobalVariable **Entry = nullptr;
  3456. if (!LangOpts.WritableStrings) {
  3457. Entry = &ConstantStringMap[C];
  3458. if (auto GV = *Entry) {
  3459. if (Alignment.getQuantity() > GV->getAlignment())
  3460. GV->setAlignment(Alignment.getQuantity());
  3461. return ConstantAddress(GV, Alignment);
  3462. }
  3463. }
  3464. SmallString<256> MangledNameBuffer;
  3465. StringRef GlobalVariableName;
  3466. llvm::GlobalValue::LinkageTypes LT;
  3467. // Mangle the string literal if the ABI allows for it. However, we cannot
  3468. // do this if we are compiling with ASan or -fwritable-strings because they
  3469. // rely on strings having normal linkage.
  3470. if (!LangOpts.WritableStrings &&
  3471. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  3472. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  3473. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3474. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3475. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3476. GlobalVariableName = MangledNameBuffer;
  3477. } else {
  3478. LT = llvm::GlobalValue::PrivateLinkage;
  3479. GlobalVariableName = Name;
  3480. }
  3481. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3482. if (Entry)
  3483. *Entry = GV;
  3484. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3485. QualType());
  3486. return ConstantAddress(GV, Alignment);
  3487. }
  3488. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3489. /// array for the given ObjCEncodeExpr node.
  3490. ConstantAddress
  3491. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3492. std::string Str;
  3493. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3494. return GetAddrOfConstantCString(Str);
  3495. }
  3496. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3497. /// the literal and a terminating '\0' character.
  3498. /// The result has pointer to array type.
  3499. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3500. const std::string &Str, const char *GlobalName) {
  3501. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3502. CharUnits Alignment =
  3503. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3504. llvm::Constant *C =
  3505. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3506. // Don't share any string literals if strings aren't constant.
  3507. llvm::GlobalVariable **Entry = nullptr;
  3508. if (!LangOpts.WritableStrings) {
  3509. Entry = &ConstantStringMap[C];
  3510. if (auto GV = *Entry) {
  3511. if (Alignment.getQuantity() > GV->getAlignment())
  3512. GV->setAlignment(Alignment.getQuantity());
  3513. return ConstantAddress(GV, Alignment);
  3514. }
  3515. }
  3516. // Get the default prefix if a name wasn't specified.
  3517. if (!GlobalName)
  3518. GlobalName = ".str";
  3519. // Create a global variable for this.
  3520. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3521. GlobalName, Alignment);
  3522. if (Entry)
  3523. *Entry = GV;
  3524. return ConstantAddress(GV, Alignment);
  3525. }
  3526. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3527. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3528. assert((E->getStorageDuration() == SD_Static ||
  3529. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3530. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3531. // If we're not materializing a subobject of the temporary, keep the
  3532. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3533. QualType MaterializedType = Init->getType();
  3534. if (Init == E->GetTemporaryExpr())
  3535. MaterializedType = E->getType();
  3536. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3537. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3538. return ConstantAddress(Slot, Align);
  3539. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3540. // we need to give each temporary the same name in every translation unit (and
  3541. // we also need to make the temporaries externally-visible).
  3542. SmallString<256> Name;
  3543. llvm::raw_svector_ostream Out(Name);
  3544. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3545. VD, E->getManglingNumber(), Out);
  3546. APValue *Value = nullptr;
  3547. if (E->getStorageDuration() == SD_Static) {
  3548. // We might have a cached constant initializer for this temporary. Note
  3549. // that this might have a different value from the value computed by
  3550. // evaluating the initializer if the surrounding constant expression
  3551. // modifies the temporary.
  3552. Value = getContext().getMaterializedTemporaryValue(E, false);
  3553. if (Value && Value->isUninit())
  3554. Value = nullptr;
  3555. }
  3556. // Try evaluating it now, it might have a constant initializer.
  3557. Expr::EvalResult EvalResult;
  3558. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3559. !EvalResult.hasSideEffects())
  3560. Value = &EvalResult.Val;
  3561. LangAS AddrSpace =
  3562. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  3563. Optional<ConstantEmitter> emitter;
  3564. llvm::Constant *InitialValue = nullptr;
  3565. bool Constant = false;
  3566. llvm::Type *Type;
  3567. if (Value) {
  3568. // The temporary has a constant initializer, use it.
  3569. emitter.emplace(*this);
  3570. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  3571. MaterializedType);
  3572. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3573. Type = InitialValue->getType();
  3574. } else {
  3575. // No initializer, the initialization will be provided when we
  3576. // initialize the declaration which performed lifetime extension.
  3577. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3578. }
  3579. // Create a global variable for this lifetime-extended temporary.
  3580. llvm::GlobalValue::LinkageTypes Linkage =
  3581. getLLVMLinkageVarDefinition(VD, Constant);
  3582. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3583. const VarDecl *InitVD;
  3584. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3585. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3586. // Temporaries defined inside a class get linkonce_odr linkage because the
  3587. // class can be defined in multipe translation units.
  3588. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3589. } else {
  3590. // There is no need for this temporary to have external linkage if the
  3591. // VarDecl has external linkage.
  3592. Linkage = llvm::GlobalVariable::InternalLinkage;
  3593. }
  3594. }
  3595. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  3596. auto *GV = new llvm::GlobalVariable(
  3597. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3598. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  3599. if (emitter) emitter->finalize(GV);
  3600. setGVProperties(GV, VD);
  3601. GV->setAlignment(Align.getQuantity());
  3602. if (supportsCOMDAT() && GV->isWeakForLinker())
  3603. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3604. if (VD->getTLSKind())
  3605. setTLSMode(GV, *VD);
  3606. llvm::Constant *CV = GV;
  3607. if (AddrSpace != LangAS::Default)
  3608. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  3609. *this, GV, AddrSpace, LangAS::Default,
  3610. Type->getPointerTo(
  3611. getContext().getTargetAddressSpace(LangAS::Default)));
  3612. MaterializedGlobalTemporaryMap[E] = CV;
  3613. return ConstantAddress(CV, Align);
  3614. }
  3615. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3616. /// properties for an implementation.
  3617. void CodeGenModule::EmitObjCPropertyImplementations(const
  3618. ObjCImplementationDecl *D) {
  3619. for (const auto *PID : D->property_impls()) {
  3620. // Dynamic is just for type-checking.
  3621. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3622. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3623. // Determine which methods need to be implemented, some may have
  3624. // been overridden. Note that ::isPropertyAccessor is not the method
  3625. // we want, that just indicates if the decl came from a
  3626. // property. What we want to know is if the method is defined in
  3627. // this implementation.
  3628. if (!D->getInstanceMethod(PD->getGetterName()))
  3629. CodeGenFunction(*this).GenerateObjCGetter(
  3630. const_cast<ObjCImplementationDecl *>(D), PID);
  3631. if (!PD->isReadOnly() &&
  3632. !D->getInstanceMethod(PD->getSetterName()))
  3633. CodeGenFunction(*this).GenerateObjCSetter(
  3634. const_cast<ObjCImplementationDecl *>(D), PID);
  3635. }
  3636. }
  3637. }
  3638. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3639. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3640. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3641. ivar; ivar = ivar->getNextIvar())
  3642. if (ivar->getType().isDestructedType())
  3643. return true;
  3644. return false;
  3645. }
  3646. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3647. ObjCImplementationDecl *D) {
  3648. CodeGenFunction CGF(CGM);
  3649. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3650. E = D->init_end(); B != E; ++B) {
  3651. CXXCtorInitializer *CtorInitExp = *B;
  3652. Expr *Init = CtorInitExp->getInit();
  3653. if (!CGF.isTrivialInitializer(Init))
  3654. return false;
  3655. }
  3656. return true;
  3657. }
  3658. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3659. /// for an implementation.
  3660. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3661. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3662. if (needsDestructMethod(D)) {
  3663. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3664. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3665. ObjCMethodDecl *DTORMethod =
  3666. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3667. cxxSelector, getContext().VoidTy, nullptr, D,
  3668. /*isInstance=*/true, /*isVariadic=*/false,
  3669. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3670. /*isDefined=*/false, ObjCMethodDecl::Required);
  3671. D->addInstanceMethod(DTORMethod);
  3672. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3673. D->setHasDestructors(true);
  3674. }
  3675. // If the implementation doesn't have any ivar initializers, we don't need
  3676. // a .cxx_construct.
  3677. if (D->getNumIvarInitializers() == 0 ||
  3678. AllTrivialInitializers(*this, D))
  3679. return;
  3680. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3681. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3682. // The constructor returns 'self'.
  3683. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3684. D->getLocation(),
  3685. D->getLocation(),
  3686. cxxSelector,
  3687. getContext().getObjCIdType(),
  3688. nullptr, D, /*isInstance=*/true,
  3689. /*isVariadic=*/false,
  3690. /*isPropertyAccessor=*/true,
  3691. /*isImplicitlyDeclared=*/true,
  3692. /*isDefined=*/false,
  3693. ObjCMethodDecl::Required);
  3694. D->addInstanceMethod(CTORMethod);
  3695. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3696. D->setHasNonZeroConstructors(true);
  3697. }
  3698. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3699. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3700. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3701. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3702. ErrorUnsupported(LSD, "linkage spec");
  3703. return;
  3704. }
  3705. EmitDeclContext(LSD);
  3706. }
  3707. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3708. for (auto *I : DC->decls()) {
  3709. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3710. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3711. // ObjCImplDecl does not recursively visit them. We need to do that in
  3712. // case they're nested inside another construct (LinkageSpecDecl /
  3713. // ExportDecl) that does stop them from being considered "top-level".
  3714. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3715. for (auto *M : OID->methods())
  3716. EmitTopLevelDecl(M);
  3717. }
  3718. EmitTopLevelDecl(I);
  3719. }
  3720. }
  3721. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3722. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3723. // Ignore dependent declarations.
  3724. if (D->isTemplated())
  3725. return;
  3726. switch (D->getKind()) {
  3727. case Decl::CXXConversion:
  3728. case Decl::CXXMethod:
  3729. case Decl::Function:
  3730. EmitGlobal(cast<FunctionDecl>(D));
  3731. // Always provide some coverage mapping
  3732. // even for the functions that aren't emitted.
  3733. AddDeferredUnusedCoverageMapping(D);
  3734. break;
  3735. case Decl::CXXDeductionGuide:
  3736. // Function-like, but does not result in code emission.
  3737. break;
  3738. case Decl::Var:
  3739. case Decl::Decomposition:
  3740. case Decl::VarTemplateSpecialization:
  3741. EmitGlobal(cast<VarDecl>(D));
  3742. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3743. for (auto *B : DD->bindings())
  3744. if (auto *HD = B->getHoldingVar())
  3745. EmitGlobal(HD);
  3746. break;
  3747. // Indirect fields from global anonymous structs and unions can be
  3748. // ignored; only the actual variable requires IR gen support.
  3749. case Decl::IndirectField:
  3750. break;
  3751. // C++ Decls
  3752. case Decl::Namespace:
  3753. EmitDeclContext(cast<NamespaceDecl>(D));
  3754. break;
  3755. case Decl::ClassTemplateSpecialization: {
  3756. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3757. if (DebugInfo &&
  3758. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3759. Spec->hasDefinition())
  3760. DebugInfo->completeTemplateDefinition(*Spec);
  3761. } LLVM_FALLTHROUGH;
  3762. case Decl::CXXRecord:
  3763. if (DebugInfo) {
  3764. if (auto *ES = D->getASTContext().getExternalSource())
  3765. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  3766. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  3767. }
  3768. // Emit any static data members, they may be definitions.
  3769. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3770. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3771. EmitTopLevelDecl(I);
  3772. break;
  3773. // No code generation needed.
  3774. case Decl::UsingShadow:
  3775. case Decl::ClassTemplate:
  3776. case Decl::VarTemplate:
  3777. case Decl::VarTemplatePartialSpecialization:
  3778. case Decl::FunctionTemplate:
  3779. case Decl::TypeAliasTemplate:
  3780. case Decl::Block:
  3781. case Decl::Empty:
  3782. break;
  3783. case Decl::Using: // using X; [C++]
  3784. if (CGDebugInfo *DI = getModuleDebugInfo())
  3785. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3786. return;
  3787. case Decl::NamespaceAlias:
  3788. if (CGDebugInfo *DI = getModuleDebugInfo())
  3789. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3790. return;
  3791. case Decl::UsingDirective: // using namespace X; [C++]
  3792. if (CGDebugInfo *DI = getModuleDebugInfo())
  3793. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3794. return;
  3795. case Decl::CXXConstructor:
  3796. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3797. break;
  3798. case Decl::CXXDestructor:
  3799. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3800. break;
  3801. case Decl::StaticAssert:
  3802. // Nothing to do.
  3803. break;
  3804. // Objective-C Decls
  3805. // Forward declarations, no (immediate) code generation.
  3806. case Decl::ObjCInterface:
  3807. case Decl::ObjCCategory:
  3808. break;
  3809. case Decl::ObjCProtocol: {
  3810. auto *Proto = cast<ObjCProtocolDecl>(D);
  3811. if (Proto->isThisDeclarationADefinition())
  3812. ObjCRuntime->GenerateProtocol(Proto);
  3813. break;
  3814. }
  3815. case Decl::ObjCCategoryImpl:
  3816. // Categories have properties but don't support synthesize so we
  3817. // can ignore them here.
  3818. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3819. break;
  3820. case Decl::ObjCImplementation: {
  3821. auto *OMD = cast<ObjCImplementationDecl>(D);
  3822. EmitObjCPropertyImplementations(OMD);
  3823. EmitObjCIvarInitializations(OMD);
  3824. ObjCRuntime->GenerateClass(OMD);
  3825. // Emit global variable debug information.
  3826. if (CGDebugInfo *DI = getModuleDebugInfo())
  3827. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3828. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3829. OMD->getClassInterface()), OMD->getLocation());
  3830. break;
  3831. }
  3832. case Decl::ObjCMethod: {
  3833. auto *OMD = cast<ObjCMethodDecl>(D);
  3834. // If this is not a prototype, emit the body.
  3835. if (OMD->getBody())
  3836. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3837. break;
  3838. }
  3839. case Decl::ObjCCompatibleAlias:
  3840. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3841. break;
  3842. case Decl::PragmaComment: {
  3843. const auto *PCD = cast<PragmaCommentDecl>(D);
  3844. switch (PCD->getCommentKind()) {
  3845. case PCK_Unknown:
  3846. llvm_unreachable("unexpected pragma comment kind");
  3847. case PCK_Linker:
  3848. AppendLinkerOptions(PCD->getArg());
  3849. break;
  3850. case PCK_Lib:
  3851. if (getTarget().getTriple().isOSBinFormatELF() &&
  3852. !getTarget().getTriple().isPS4())
  3853. AddELFLibDirective(PCD->getArg());
  3854. else
  3855. AddDependentLib(PCD->getArg());
  3856. break;
  3857. case PCK_Compiler:
  3858. case PCK_ExeStr:
  3859. case PCK_User:
  3860. break; // We ignore all of these.
  3861. }
  3862. break;
  3863. }
  3864. case Decl::PragmaDetectMismatch: {
  3865. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3866. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3867. break;
  3868. }
  3869. case Decl::LinkageSpec:
  3870. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3871. break;
  3872. case Decl::FileScopeAsm: {
  3873. // File-scope asm is ignored during device-side CUDA compilation.
  3874. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3875. break;
  3876. // File-scope asm is ignored during device-side OpenMP compilation.
  3877. if (LangOpts.OpenMPIsDevice)
  3878. break;
  3879. auto *AD = cast<FileScopeAsmDecl>(D);
  3880. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3881. break;
  3882. }
  3883. case Decl::Import: {
  3884. auto *Import = cast<ImportDecl>(D);
  3885. // If we've already imported this module, we're done.
  3886. if (!ImportedModules.insert(Import->getImportedModule()))
  3887. break;
  3888. // Emit debug information for direct imports.
  3889. if (!Import->getImportedOwningModule()) {
  3890. if (CGDebugInfo *DI = getModuleDebugInfo())
  3891. DI->EmitImportDecl(*Import);
  3892. }
  3893. // Find all of the submodules and emit the module initializers.
  3894. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3895. SmallVector<clang::Module *, 16> Stack;
  3896. Visited.insert(Import->getImportedModule());
  3897. Stack.push_back(Import->getImportedModule());
  3898. while (!Stack.empty()) {
  3899. clang::Module *Mod = Stack.pop_back_val();
  3900. if (!EmittedModuleInitializers.insert(Mod).second)
  3901. continue;
  3902. for (auto *D : Context.getModuleInitializers(Mod))
  3903. EmitTopLevelDecl(D);
  3904. // Visit the submodules of this module.
  3905. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3906. SubEnd = Mod->submodule_end();
  3907. Sub != SubEnd; ++Sub) {
  3908. // Skip explicit children; they need to be explicitly imported to emit
  3909. // the initializers.
  3910. if ((*Sub)->IsExplicit)
  3911. continue;
  3912. if (Visited.insert(*Sub).second)
  3913. Stack.push_back(*Sub);
  3914. }
  3915. }
  3916. break;
  3917. }
  3918. case Decl::Export:
  3919. EmitDeclContext(cast<ExportDecl>(D));
  3920. break;
  3921. case Decl::OMPThreadPrivate:
  3922. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3923. break;
  3924. case Decl::OMPDeclareReduction:
  3925. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3926. break;
  3927. default:
  3928. // Make sure we handled everything we should, every other kind is a
  3929. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3930. // function. Need to recode Decl::Kind to do that easily.
  3931. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3932. break;
  3933. }
  3934. }
  3935. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3936. // Do we need to generate coverage mapping?
  3937. if (!CodeGenOpts.CoverageMapping)
  3938. return;
  3939. switch (D->getKind()) {
  3940. case Decl::CXXConversion:
  3941. case Decl::CXXMethod:
  3942. case Decl::Function:
  3943. case Decl::ObjCMethod:
  3944. case Decl::CXXConstructor:
  3945. case Decl::CXXDestructor: {
  3946. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3947. return;
  3948. SourceManager &SM = getContext().getSourceManager();
  3949. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
  3950. return;
  3951. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3952. if (I == DeferredEmptyCoverageMappingDecls.end())
  3953. DeferredEmptyCoverageMappingDecls[D] = true;
  3954. break;
  3955. }
  3956. default:
  3957. break;
  3958. };
  3959. }
  3960. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3961. // Do we need to generate coverage mapping?
  3962. if (!CodeGenOpts.CoverageMapping)
  3963. return;
  3964. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3965. if (Fn->isTemplateInstantiation())
  3966. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3967. }
  3968. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3969. if (I == DeferredEmptyCoverageMappingDecls.end())
  3970. DeferredEmptyCoverageMappingDecls[D] = false;
  3971. else
  3972. I->second = false;
  3973. }
  3974. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3975. // We call takeVector() here to avoid use-after-free.
  3976. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  3977. // we deserialize function bodies to emit coverage info for them, and that
  3978. // deserializes more declarations. How should we handle that case?
  3979. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  3980. if (!Entry.second)
  3981. continue;
  3982. const Decl *D = Entry.first;
  3983. switch (D->getKind()) {
  3984. case Decl::CXXConversion:
  3985. case Decl::CXXMethod:
  3986. case Decl::Function:
  3987. case Decl::ObjCMethod: {
  3988. CodeGenPGO PGO(*this);
  3989. GlobalDecl GD(cast<FunctionDecl>(D));
  3990. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3991. getFunctionLinkage(GD));
  3992. break;
  3993. }
  3994. case Decl::CXXConstructor: {
  3995. CodeGenPGO PGO(*this);
  3996. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3997. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3998. getFunctionLinkage(GD));
  3999. break;
  4000. }
  4001. case Decl::CXXDestructor: {
  4002. CodeGenPGO PGO(*this);
  4003. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  4004. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4005. getFunctionLinkage(GD));
  4006. break;
  4007. }
  4008. default:
  4009. break;
  4010. };
  4011. }
  4012. }
  4013. /// Turns the given pointer into a constant.
  4014. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  4015. const void *Ptr) {
  4016. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  4017. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  4018. return llvm::ConstantInt::get(i64, PtrInt);
  4019. }
  4020. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  4021. llvm::NamedMDNode *&GlobalMetadata,
  4022. GlobalDecl D,
  4023. llvm::GlobalValue *Addr) {
  4024. if (!GlobalMetadata)
  4025. GlobalMetadata =
  4026. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  4027. // TODO: should we report variant information for ctors/dtors?
  4028. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  4029. llvm::ConstantAsMetadata::get(GetPointerConstant(
  4030. CGM.getLLVMContext(), D.getDecl()))};
  4031. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  4032. }
  4033. /// For each function which is declared within an extern "C" region and marked
  4034. /// as 'used', but has internal linkage, create an alias from the unmangled
  4035. /// name to the mangled name if possible. People expect to be able to refer
  4036. /// to such functions with an unmangled name from inline assembly within the
  4037. /// same translation unit.
  4038. void CodeGenModule::EmitStaticExternCAliases() {
  4039. // Don't do anything if we're generating CUDA device code -- the NVPTX
  4040. // assembly target doesn't support aliases.
  4041. if (Context.getTargetInfo().getTriple().isNVPTX())
  4042. return;
  4043. for (auto &I : StaticExternCValues) {
  4044. IdentifierInfo *Name = I.first;
  4045. llvm::GlobalValue *Val = I.second;
  4046. if (Val && !getModule().getNamedValue(Name->getName()))
  4047. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  4048. }
  4049. }
  4050. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  4051. GlobalDecl &Result) const {
  4052. auto Res = Manglings.find(MangledName);
  4053. if (Res == Manglings.end())
  4054. return false;
  4055. Result = Res->getValue();
  4056. return true;
  4057. }
  4058. /// Emits metadata nodes associating all the global values in the
  4059. /// current module with the Decls they came from. This is useful for
  4060. /// projects using IR gen as a subroutine.
  4061. ///
  4062. /// Since there's currently no way to associate an MDNode directly
  4063. /// with an llvm::GlobalValue, we create a global named metadata
  4064. /// with the name 'clang.global.decl.ptrs'.
  4065. void CodeGenModule::EmitDeclMetadata() {
  4066. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4067. for (auto &I : MangledDeclNames) {
  4068. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4069. // Some mangled names don't necessarily have an associated GlobalValue
  4070. // in this module, e.g. if we mangled it for DebugInfo.
  4071. if (Addr)
  4072. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4073. }
  4074. }
  4075. /// Emits metadata nodes for all the local variables in the current
  4076. /// function.
  4077. void CodeGenFunction::EmitDeclMetadata() {
  4078. if (LocalDeclMap.empty()) return;
  4079. llvm::LLVMContext &Context = getLLVMContext();
  4080. // Find the unique metadata ID for this name.
  4081. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4082. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4083. for (auto &I : LocalDeclMap) {
  4084. const Decl *D = I.first;
  4085. llvm::Value *Addr = I.second.getPointer();
  4086. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4087. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4088. Alloca->setMetadata(
  4089. DeclPtrKind, llvm::MDNode::get(
  4090. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4091. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4092. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4093. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4094. }
  4095. }
  4096. }
  4097. void CodeGenModule::EmitVersionIdentMetadata() {
  4098. llvm::NamedMDNode *IdentMetadata =
  4099. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4100. std::string Version = getClangFullVersion();
  4101. llvm::LLVMContext &Ctx = TheModule.getContext();
  4102. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4103. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4104. }
  4105. void CodeGenModule::EmitTargetMetadata() {
  4106. // Warning, new MangledDeclNames may be appended within this loop.
  4107. // We rely on MapVector insertions adding new elements to the end
  4108. // of the container.
  4109. // FIXME: Move this loop into the one target that needs it, and only
  4110. // loop over those declarations for which we couldn't emit the target
  4111. // metadata when we emitted the declaration.
  4112. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4113. auto Val = *(MangledDeclNames.begin() + I);
  4114. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4115. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4116. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4117. }
  4118. }
  4119. void CodeGenModule::EmitCoverageFile() {
  4120. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4121. getCodeGenOpts().CoverageNotesFile.empty())
  4122. return;
  4123. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4124. if (!CUNode)
  4125. return;
  4126. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4127. llvm::LLVMContext &Ctx = TheModule.getContext();
  4128. auto *CoverageDataFile =
  4129. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4130. auto *CoverageNotesFile =
  4131. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4132. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4133. llvm::MDNode *CU = CUNode->getOperand(i);
  4134. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4135. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4136. }
  4137. }
  4138. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4139. // Sema has checked that all uuid strings are of the form
  4140. // "12345678-1234-1234-1234-1234567890ab".
  4141. assert(Uuid.size() == 36);
  4142. for (unsigned i = 0; i < 36; ++i) {
  4143. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4144. else assert(isHexDigit(Uuid[i]));
  4145. }
  4146. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4147. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4148. llvm::Constant *Field3[8];
  4149. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4150. Field3[Idx] = llvm::ConstantInt::get(
  4151. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4152. llvm::Constant *Fields[4] = {
  4153. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4154. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4155. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4156. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4157. };
  4158. return llvm::ConstantStruct::getAnon(Fields);
  4159. }
  4160. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4161. bool ForEH) {
  4162. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4163. // FIXME: should we even be calling this method if RTTI is disabled
  4164. // and it's not for EH?
  4165. if (!ForEH && !getLangOpts().RTTI)
  4166. return llvm::Constant::getNullValue(Int8PtrTy);
  4167. if (ForEH && Ty->isObjCObjectPointerType() &&
  4168. LangOpts.ObjCRuntime.isGNUFamily())
  4169. return ObjCRuntime->GetEHType(Ty);
  4170. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4171. }
  4172. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4173. // Do not emit threadprivates in simd-only mode.
  4174. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4175. return;
  4176. for (auto RefExpr : D->varlists()) {
  4177. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4178. bool PerformInit =
  4179. VD->getAnyInitializer() &&
  4180. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4181. /*ForRef=*/false);
  4182. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4183. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4184. VD, Addr, RefExpr->getLocStart(), PerformInit))
  4185. CXXGlobalInits.push_back(InitFunction);
  4186. }
  4187. }
  4188. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4189. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  4190. if (InternalId)
  4191. return InternalId;
  4192. if (isExternallyVisible(T->getLinkage())) {
  4193. std::string OutName;
  4194. llvm::raw_string_ostream Out(OutName);
  4195. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4196. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4197. } else {
  4198. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4199. llvm::ArrayRef<llvm::Metadata *>());
  4200. }
  4201. return InternalId;
  4202. }
  4203. // Generalize pointer types to a void pointer with the qualifiers of the
  4204. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4205. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4206. // 'void *'.
  4207. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4208. if (!Ty->isPointerType())
  4209. return Ty;
  4210. return Ctx.getPointerType(
  4211. QualType(Ctx.VoidTy).withCVRQualifiers(
  4212. Ty->getPointeeType().getCVRQualifiers()));
  4213. }
  4214. // Apply type generalization to a FunctionType's return and argument types
  4215. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4216. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4217. SmallVector<QualType, 8> GeneralizedParams;
  4218. for (auto &Param : FnType->param_types())
  4219. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4220. return Ctx.getFunctionType(
  4221. GeneralizeType(Ctx, FnType->getReturnType()),
  4222. GeneralizedParams, FnType->getExtProtoInfo());
  4223. }
  4224. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4225. return Ctx.getFunctionNoProtoType(
  4226. GeneralizeType(Ctx, FnType->getReturnType()));
  4227. llvm_unreachable("Encountered unknown FunctionType");
  4228. }
  4229. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4230. T = GeneralizeFunctionType(getContext(), T);
  4231. llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
  4232. if (InternalId)
  4233. return InternalId;
  4234. if (isExternallyVisible(T->getLinkage())) {
  4235. std::string OutName;
  4236. llvm::raw_string_ostream Out(OutName);
  4237. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4238. Out << ".generalized";
  4239. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4240. } else {
  4241. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4242. llvm::ArrayRef<llvm::Metadata *>());
  4243. }
  4244. return InternalId;
  4245. }
  4246. /// Returns whether this module needs the "all-vtables" type identifier.
  4247. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4248. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4249. // is not in the trapping mode.
  4250. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4251. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4252. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4253. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4254. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4255. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4256. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4257. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4258. }
  4259. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4260. CharUnits Offset,
  4261. const CXXRecordDecl *RD) {
  4262. llvm::Metadata *MD =
  4263. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  4264. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4265. if (CodeGenOpts.SanitizeCfiCrossDso)
  4266. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  4267. VTable->addTypeMetadata(Offset.getQuantity(),
  4268. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  4269. if (NeedAllVtablesTypeId()) {
  4270. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  4271. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  4272. }
  4273. }
  4274. // Fills in the supplied string map with the set of target features for the
  4275. // passed in function.
  4276. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  4277. const FunctionDecl *FD) {
  4278. StringRef TargetCPU = Target.getTargetOpts().CPU;
  4279. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  4280. // If we have a TargetAttr build up the feature map based on that.
  4281. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  4282. ParsedAttr.Features.erase(
  4283. llvm::remove_if(ParsedAttr.Features,
  4284. [&](const std::string &Feat) {
  4285. return !Target.isValidFeatureName(
  4286. StringRef{Feat}.substr(1));
  4287. }),
  4288. ParsedAttr.Features.end());
  4289. // Make a copy of the features as passed on the command line into the
  4290. // beginning of the additional features from the function to override.
  4291. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  4292. Target.getTargetOpts().FeaturesAsWritten.begin(),
  4293. Target.getTargetOpts().FeaturesAsWritten.end());
  4294. if (ParsedAttr.Architecture != "" &&
  4295. Target.isValidCPUName(ParsedAttr.Architecture))
  4296. TargetCPU = ParsedAttr.Architecture;
  4297. // Now populate the feature map, first with the TargetCPU which is either
  4298. // the default or a new one from the target attribute string. Then we'll use
  4299. // the passed in features (FeaturesAsWritten) along with the new ones from
  4300. // the attribute.
  4301. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4302. ParsedAttr.Features);
  4303. } else {
  4304. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  4305. Target.getTargetOpts().Features);
  4306. }
  4307. }
  4308. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  4309. if (!SanStats)
  4310. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  4311. return *SanStats;
  4312. }
  4313. llvm::Value *
  4314. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  4315. CodeGenFunction &CGF) {
  4316. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  4317. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  4318. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  4319. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  4320. "__translate_sampler_initializer"),
  4321. {C});
  4322. }