CodeGenFunction.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-function state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGBlocks.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCleanup.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/ASTLambda.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/AST/DeclCXX.h"
  27. #include "clang/AST/Expr.h"
  28. #include "clang/AST/StmtCXX.h"
  29. #include "clang/AST/StmtObjC.h"
  30. #include "clang/Basic/Builtins.h"
  31. #include "clang/Basic/CodeGenOptions.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/CodeGen/CGFunctionInfo.h"
  34. #include "clang/Frontend/FrontendDiagnostic.h"
  35. #include "llvm/ADT/ArrayRef.h"
  36. #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
  37. #include "llvm/IR/DataLayout.h"
  38. #include "llvm/IR/Dominators.h"
  39. #include "llvm/IR/FPEnv.h"
  40. #include "llvm/IR/IntrinsicInst.h"
  41. #include "llvm/IR/Intrinsics.h"
  42. #include "llvm/IR/MDBuilder.h"
  43. #include "llvm/IR/Operator.h"
  44. #include "llvm/Support/CRC.h"
  45. #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
  46. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  47. using namespace clang;
  48. using namespace CodeGen;
  49. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  50. /// markers.
  51. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  52. const LangOptions &LangOpts) {
  53. if (CGOpts.DisableLifetimeMarkers)
  54. return false;
  55. // Sanitizers may use markers.
  56. if (CGOpts.SanitizeAddressUseAfterScope ||
  57. LangOpts.Sanitize.has(SanitizerKind::HWAddress) ||
  58. LangOpts.Sanitize.has(SanitizerKind::Memory))
  59. return true;
  60. // For now, only in optimized builds.
  61. return CGOpts.OptimizationLevel != 0;
  62. }
  63. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  64. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  65. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  66. CGBuilderInserterTy(this)),
  67. SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
  68. DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
  69. ShouldEmitLifetimeMarkers(
  70. shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  71. if (!suppressNewContext)
  72. CGM.getCXXABI().getMangleContext().startNewFunction();
  73. EHStack.setCGF(this);
  74. SetFastMathFlags(CurFPFeatures);
  75. }
  76. CodeGenFunction::~CodeGenFunction() {
  77. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  78. if (getLangOpts().OpenMP && CurFn)
  79. CGM.getOpenMPRuntime().functionFinished(*this);
  80. // If we have an OpenMPIRBuilder we want to finalize functions (incl.
  81. // outlining etc) at some point. Doing it once the function codegen is done
  82. // seems to be a reasonable spot. We do it here, as opposed to the deletion
  83. // time of the CodeGenModule, because we have to ensure the IR has not yet
  84. // been "emitted" to the outside, thus, modifications are still sensible.
  85. if (CGM.getLangOpts().OpenMPIRBuilder && CurFn)
  86. CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn);
  87. }
  88. // Map the LangOption for exception behavior into
  89. // the corresponding enum in the IR.
  90. llvm::fp::ExceptionBehavior
  91. clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) {
  92. switch (Kind) {
  93. case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore;
  94. case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap;
  95. case LangOptions::FPE_Strict: return llvm::fp::ebStrict;
  96. }
  97. llvm_unreachable("Unsupported FP Exception Behavior");
  98. }
  99. void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) {
  100. llvm::FastMathFlags FMF;
  101. FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
  102. FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
  103. FMF.setNoInfs(FPFeatures.getNoHonorInfs());
  104. FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
  105. FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
  106. FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
  107. FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
  108. Builder.setFastMathFlags(FMF);
  109. }
  110. CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
  111. const Expr *E)
  112. : CGF(CGF) {
  113. ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts()));
  114. }
  115. CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF,
  116. FPOptions FPFeatures)
  117. : CGF(CGF) {
  118. ConstructorHelper(FPFeatures);
  119. }
  120. void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) {
  121. OldFPFeatures = CGF.CurFPFeatures;
  122. CGF.CurFPFeatures = FPFeatures;
  123. OldExcept = CGF.Builder.getDefaultConstrainedExcept();
  124. OldRounding = CGF.Builder.getDefaultConstrainedRounding();
  125. if (OldFPFeatures == FPFeatures)
  126. return;
  127. FMFGuard.emplace(CGF.Builder);
  128. llvm::RoundingMode NewRoundingBehavior =
  129. static_cast<llvm::RoundingMode>(FPFeatures.getRoundingMode());
  130. CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
  131. auto NewExceptionBehavior =
  132. ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>(
  133. FPFeatures.getFPExceptionMode()));
  134. CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
  135. CGF.SetFastMathFlags(FPFeatures);
  136. assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() ||
  137. isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
  138. isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
  139. (NewExceptionBehavior == llvm::fp::ebIgnore &&
  140. NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
  141. "FPConstrained should be enabled on entire function");
  142. auto mergeFnAttrValue = [&](StringRef Name, bool Value) {
  143. auto OldValue =
  144. CGF.CurFn->getFnAttribute(Name).getValueAsBool();
  145. auto NewValue = OldValue & Value;
  146. if (OldValue != NewValue)
  147. CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
  148. };
  149. mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs());
  150. mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs());
  151. mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
  152. mergeFnAttrValue("unsafe-fp-math", FPFeatures.getAllowFPReassociate() &&
  153. FPFeatures.getAllowReciprocal() &&
  154. FPFeatures.getAllowApproxFunc() &&
  155. FPFeatures.getNoSignedZero());
  156. }
  157. CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() {
  158. CGF.CurFPFeatures = OldFPFeatures;
  159. CGF.Builder.setDefaultConstrainedExcept(OldExcept);
  160. CGF.Builder.setDefaultConstrainedRounding(OldRounding);
  161. }
  162. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  163. LValueBaseInfo BaseInfo;
  164. TBAAAccessInfo TBAAInfo;
  165. CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  166. Address Addr(V, ConvertTypeForMem(T), Alignment);
  167. return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
  168. }
  169. /// Given a value of type T* that may not be to a complete object,
  170. /// construct an l-value with the natural pointee alignment of T.
  171. LValue
  172. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  173. LValueBaseInfo BaseInfo;
  174. TBAAAccessInfo TBAAInfo;
  175. CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  176. /* forPointeeType= */ true);
  177. Address Addr(V, ConvertTypeForMem(T), Align);
  178. return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
  179. }
  180. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  181. return CGM.getTypes().ConvertTypeForMem(T);
  182. }
  183. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  184. return CGM.getTypes().ConvertType(T);
  185. }
  186. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  187. type = type.getCanonicalType();
  188. while (true) {
  189. switch (type->getTypeClass()) {
  190. #define TYPE(name, parent)
  191. #define ABSTRACT_TYPE(name, parent)
  192. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  193. #define DEPENDENT_TYPE(name, parent) case Type::name:
  194. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  195. #include "clang/AST/TypeNodes.inc"
  196. llvm_unreachable("non-canonical or dependent type in IR-generation");
  197. case Type::Auto:
  198. case Type::DeducedTemplateSpecialization:
  199. llvm_unreachable("undeduced type in IR-generation");
  200. // Various scalar types.
  201. case Type::Builtin:
  202. case Type::Pointer:
  203. case Type::BlockPointer:
  204. case Type::LValueReference:
  205. case Type::RValueReference:
  206. case Type::MemberPointer:
  207. case Type::Vector:
  208. case Type::ExtVector:
  209. case Type::ConstantMatrix:
  210. case Type::FunctionProto:
  211. case Type::FunctionNoProto:
  212. case Type::Enum:
  213. case Type::ObjCObjectPointer:
  214. case Type::Pipe:
  215. case Type::BitInt:
  216. return TEK_Scalar;
  217. // Complexes.
  218. case Type::Complex:
  219. return TEK_Complex;
  220. // Arrays, records, and Objective-C objects.
  221. case Type::ConstantArray:
  222. case Type::IncompleteArray:
  223. case Type::VariableArray:
  224. case Type::Record:
  225. case Type::ObjCObject:
  226. case Type::ObjCInterface:
  227. return TEK_Aggregate;
  228. // We operate on atomic values according to their underlying type.
  229. case Type::Atomic:
  230. type = cast<AtomicType>(type)->getValueType();
  231. continue;
  232. }
  233. llvm_unreachable("unknown type kind!");
  234. }
  235. }
  236. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  237. // For cleanliness, we try to avoid emitting the return block for
  238. // simple cases.
  239. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  240. if (CurBB) {
  241. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  242. // We have a valid insert point, reuse it if it is empty or there are no
  243. // explicit jumps to the return block.
  244. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  245. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  246. delete ReturnBlock.getBlock();
  247. ReturnBlock = JumpDest();
  248. } else
  249. EmitBlock(ReturnBlock.getBlock());
  250. return llvm::DebugLoc();
  251. }
  252. // Otherwise, if the return block is the target of a single direct
  253. // branch then we can just put the code in that block instead. This
  254. // cleans up functions which started with a unified return block.
  255. if (ReturnBlock.getBlock()->hasOneUse()) {
  256. llvm::BranchInst *BI =
  257. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  258. if (BI && BI->isUnconditional() &&
  259. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  260. // Record/return the DebugLoc of the simple 'return' expression to be used
  261. // later by the actual 'ret' instruction.
  262. llvm::DebugLoc Loc = BI->getDebugLoc();
  263. Builder.SetInsertPoint(BI->getParent());
  264. BI->eraseFromParent();
  265. delete ReturnBlock.getBlock();
  266. ReturnBlock = JumpDest();
  267. return Loc;
  268. }
  269. }
  270. // FIXME: We are at an unreachable point, there is no reason to emit the block
  271. // unless it has uses. However, we still need a place to put the debug
  272. // region.end for now.
  273. EmitBlock(ReturnBlock.getBlock());
  274. return llvm::DebugLoc();
  275. }
  276. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  277. if (!BB) return;
  278. if (!BB->use_empty())
  279. return CGF.CurFn->getBasicBlockList().push_back(BB);
  280. delete BB;
  281. }
  282. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  283. assert(BreakContinueStack.empty() &&
  284. "mismatched push/pop in break/continue stack!");
  285. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  286. && NumSimpleReturnExprs == NumReturnExprs
  287. && ReturnBlock.getBlock()->use_empty();
  288. // Usually the return expression is evaluated before the cleanup
  289. // code. If the function contains only a simple return statement,
  290. // such as a constant, the location before the cleanup code becomes
  291. // the last useful breakpoint in the function, because the simple
  292. // return expression will be evaluated after the cleanup code. To be
  293. // safe, set the debug location for cleanup code to the location of
  294. // the return statement. Otherwise the cleanup code should be at the
  295. // end of the function's lexical scope.
  296. //
  297. // If there are multiple branches to the return block, the branch
  298. // instructions will get the location of the return statements and
  299. // all will be fine.
  300. if (CGDebugInfo *DI = getDebugInfo()) {
  301. if (OnlySimpleReturnStmts)
  302. DI->EmitLocation(Builder, LastStopPoint);
  303. else
  304. DI->EmitLocation(Builder, EndLoc);
  305. }
  306. // Pop any cleanups that might have been associated with the
  307. // parameters. Do this in whatever block we're currently in; it's
  308. // important to do this before we enter the return block or return
  309. // edges will be *really* confused.
  310. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  311. bool HasOnlyLifetimeMarkers =
  312. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  313. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  314. if (HasCleanups) {
  315. // Make sure the line table doesn't jump back into the body for
  316. // the ret after it's been at EndLoc.
  317. Optional<ApplyDebugLocation> AL;
  318. if (CGDebugInfo *DI = getDebugInfo()) {
  319. if (OnlySimpleReturnStmts)
  320. DI->EmitLocation(Builder, EndLoc);
  321. else
  322. // We may not have a valid end location. Try to apply it anyway, and
  323. // fall back to an artificial location if needed.
  324. AL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc);
  325. }
  326. PopCleanupBlocks(PrologueCleanupDepth);
  327. }
  328. // Emit function epilog (to return).
  329. llvm::DebugLoc Loc = EmitReturnBlock();
  330. if (ShouldInstrumentFunction()) {
  331. if (CGM.getCodeGenOpts().InstrumentFunctions)
  332. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  333. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  334. CurFn->addFnAttr("instrument-function-exit-inlined",
  335. "__cyg_profile_func_exit");
  336. }
  337. if (ShouldSkipSanitizerInstrumentation())
  338. CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
  339. // Emit debug descriptor for function end.
  340. if (CGDebugInfo *DI = getDebugInfo())
  341. DI->EmitFunctionEnd(Builder, CurFn);
  342. // Reset the debug location to that of the simple 'return' expression, if any
  343. // rather than that of the end of the function's scope '}'.
  344. ApplyDebugLocation AL(*this, Loc);
  345. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  346. EmitEndEHSpec(CurCodeDecl);
  347. assert(EHStack.empty() &&
  348. "did not remove all scopes from cleanup stack!");
  349. // If someone did an indirect goto, emit the indirect goto block at the end of
  350. // the function.
  351. if (IndirectBranch) {
  352. EmitBlock(IndirectBranch->getParent());
  353. Builder.ClearInsertionPoint();
  354. }
  355. // If some of our locals escaped, insert a call to llvm.localescape in the
  356. // entry block.
  357. if (!EscapedLocals.empty()) {
  358. // Invert the map from local to index into a simple vector. There should be
  359. // no holes.
  360. SmallVector<llvm::Value *, 4> EscapeArgs;
  361. EscapeArgs.resize(EscapedLocals.size());
  362. for (auto &Pair : EscapedLocals)
  363. EscapeArgs[Pair.second] = Pair.first;
  364. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  365. &CGM.getModule(), llvm::Intrinsic::localescape);
  366. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  367. }
  368. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  369. llvm::Instruction *Ptr = AllocaInsertPt;
  370. AllocaInsertPt = nullptr;
  371. Ptr->eraseFromParent();
  372. // PostAllocaInsertPt, if created, was lazily created when it was required,
  373. // remove it now since it was just created for our own convenience.
  374. if (PostAllocaInsertPt) {
  375. llvm::Instruction *PostPtr = PostAllocaInsertPt;
  376. PostAllocaInsertPt = nullptr;
  377. PostPtr->eraseFromParent();
  378. }
  379. // If someone took the address of a label but never did an indirect goto, we
  380. // made a zero entry PHI node, which is illegal, zap it now.
  381. if (IndirectBranch) {
  382. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  383. if (PN->getNumIncomingValues() == 0) {
  384. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  385. PN->eraseFromParent();
  386. }
  387. }
  388. EmitIfUsed(*this, EHResumeBlock);
  389. EmitIfUsed(*this, TerminateLandingPad);
  390. EmitIfUsed(*this, TerminateHandler);
  391. EmitIfUsed(*this, UnreachableBlock);
  392. for (const auto &FuncletAndParent : TerminateFunclets)
  393. EmitIfUsed(*this, FuncletAndParent.second);
  394. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  395. EmitDeclMetadata();
  396. for (const auto &R : DeferredReplacements) {
  397. if (llvm::Value *Old = R.first) {
  398. Old->replaceAllUsesWith(R.second);
  399. cast<llvm::Instruction>(Old)->eraseFromParent();
  400. }
  401. }
  402. DeferredReplacements.clear();
  403. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  404. // PHIs if the current function is a coroutine. We don't do it for all
  405. // functions as it may result in slight increase in numbers of instructions
  406. // if compiled with no optimizations. We do it for coroutine as the lifetime
  407. // of CleanupDestSlot alloca make correct coroutine frame building very
  408. // difficult.
  409. if (NormalCleanupDest.isValid() && isCoroutine()) {
  410. llvm::DominatorTree DT(*CurFn);
  411. llvm::PromoteMemToReg(
  412. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  413. NormalCleanupDest = Address::invalid();
  414. }
  415. // Scan function arguments for vector width.
  416. for (llvm::Argument &A : CurFn->args())
  417. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  418. LargestVectorWidth =
  419. std::max((uint64_t)LargestVectorWidth,
  420. VT->getPrimitiveSizeInBits().getKnownMinSize());
  421. // Update vector width based on return type.
  422. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  423. LargestVectorWidth =
  424. std::max((uint64_t)LargestVectorWidth,
  425. VT->getPrimitiveSizeInBits().getKnownMinSize());
  426. // Add the required-vector-width attribute. This contains the max width from:
  427. // 1. min-vector-width attribute used in the source program.
  428. // 2. Any builtins used that have a vector width specified.
  429. // 3. Values passed in and out of inline assembly.
  430. // 4. Width of vector arguments and return types for this function.
  431. // 5. Width of vector aguments and return types for functions called by this
  432. // function.
  433. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  434. // Add vscale_range attribute if appropriate.
  435. Optional<std::pair<unsigned, unsigned>> VScaleRange =
  436. getContext().getTargetInfo().getVScaleRange(getLangOpts());
  437. if (VScaleRange) {
  438. CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
  439. getLLVMContext(), VScaleRange.getValue().first,
  440. VScaleRange.getValue().second));
  441. }
  442. // If we generated an unreachable return block, delete it now.
  443. if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) {
  444. Builder.ClearInsertionPoint();
  445. ReturnBlock.getBlock()->eraseFromParent();
  446. }
  447. if (ReturnValue.isValid()) {
  448. auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer());
  449. if (RetAlloca && RetAlloca->use_empty()) {
  450. RetAlloca->eraseFromParent();
  451. ReturnValue = Address::invalid();
  452. }
  453. }
  454. }
  455. /// ShouldInstrumentFunction - Return true if the current function should be
  456. /// instrumented with __cyg_profile_func_* calls
  457. bool CodeGenFunction::ShouldInstrumentFunction() {
  458. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  459. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  460. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  461. return false;
  462. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  463. return false;
  464. return true;
  465. }
  466. bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() {
  467. if (!CurFuncDecl)
  468. return false;
  469. return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>();
  470. }
  471. /// ShouldXRayInstrument - Return true if the current function should be
  472. /// instrumented with XRay nop sleds.
  473. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  474. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  475. }
  476. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  477. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  478. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  479. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  480. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  481. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  482. XRayInstrKind::Custom);
  483. }
  484. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  485. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  486. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  487. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  488. XRayInstrKind::Typed);
  489. }
  490. llvm::Constant *
  491. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  492. llvm::Constant *Addr) {
  493. // Addresses stored in prologue data can't require run-time fixups and must
  494. // be PC-relative. Run-time fixups are undesirable because they necessitate
  495. // writable text segments, which are unsafe. And absolute addresses are
  496. // undesirable because they break PIE mode.
  497. // Add a layer of indirection through a private global. Taking its address
  498. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  499. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  500. /*isConstant=*/true,
  501. llvm::GlobalValue::PrivateLinkage, Addr);
  502. // Create a PC-relative address.
  503. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  504. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  505. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  506. return (IntPtrTy == Int32Ty)
  507. ? PCRelAsInt
  508. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  509. }
  510. llvm::Value *
  511. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  512. llvm::Value *EncodedAddr) {
  513. // Reconstruct the address of the global.
  514. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  515. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  516. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  517. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  518. // Load the original pointer through the global.
  519. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  520. "decoded_addr");
  521. }
  522. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  523. llvm::Function *Fn)
  524. {
  525. if (!FD->hasAttr<OpenCLKernelAttr>())
  526. return;
  527. llvm::LLVMContext &Context = getLLVMContext();
  528. CGM.GenOpenCLArgMetadata(Fn, FD, this);
  529. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  530. QualType HintQTy = A->getTypeHint();
  531. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  532. bool IsSignedInteger =
  533. HintQTy->isSignedIntegerType() ||
  534. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  535. llvm::Metadata *AttrMDArgs[] = {
  536. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  537. CGM.getTypes().ConvertType(A->getTypeHint()))),
  538. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  539. llvm::IntegerType::get(Context, 32),
  540. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  541. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  542. }
  543. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  544. llvm::Metadata *AttrMDArgs[] = {
  545. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  546. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  547. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  548. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  549. }
  550. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  551. llvm::Metadata *AttrMDArgs[] = {
  552. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  553. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  554. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  555. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  556. }
  557. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  558. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  559. llvm::Metadata *AttrMDArgs[] = {
  560. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  561. Fn->setMetadata("intel_reqd_sub_group_size",
  562. llvm::MDNode::get(Context, AttrMDArgs));
  563. }
  564. }
  565. /// Determine whether the function F ends with a return stmt.
  566. static bool endsWithReturn(const Decl* F) {
  567. const Stmt *Body = nullptr;
  568. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  569. Body = FD->getBody();
  570. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  571. Body = OMD->getBody();
  572. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  573. auto LastStmt = CS->body_rbegin();
  574. if (LastStmt != CS->body_rend())
  575. return isa<ReturnStmt>(*LastStmt);
  576. }
  577. return false;
  578. }
  579. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  580. if (SanOpts.has(SanitizerKind::Thread)) {
  581. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  582. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  583. }
  584. }
  585. /// Check if the return value of this function requires sanitization.
  586. bool CodeGenFunction::requiresReturnValueCheck() const {
  587. return requiresReturnValueNullabilityCheck() ||
  588. (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl &&
  589. CurCodeDecl->getAttr<ReturnsNonNullAttr>());
  590. }
  591. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  592. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  593. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  594. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  595. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  596. return false;
  597. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  598. return false;
  599. if (MD->getNumParams() == 2) {
  600. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  601. if (!PT || !PT->isVoidPointerType() ||
  602. !PT->getPointeeType().isConstQualified())
  603. return false;
  604. }
  605. return true;
  606. }
  607. /// Return the UBSan prologue signature for \p FD if one is available.
  608. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  609. const FunctionDecl *FD) {
  610. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  611. if (!MD->isStatic())
  612. return nullptr;
  613. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  614. }
  615. void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
  616. llvm::Function *Fn,
  617. const CGFunctionInfo &FnInfo,
  618. const FunctionArgList &Args,
  619. SourceLocation Loc,
  620. SourceLocation StartLoc) {
  621. assert(!CurFn &&
  622. "Do not use a CodeGenFunction object for more than one function");
  623. const Decl *D = GD.getDecl();
  624. DidCallStackSave = false;
  625. CurCodeDecl = D;
  626. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  627. if (FD && FD->usesSEHTry())
  628. CurSEHParent = FD;
  629. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  630. FnRetTy = RetTy;
  631. CurFn = Fn;
  632. CurFnInfo = &FnInfo;
  633. assert(CurFn->isDeclaration() && "Function already has body?");
  634. // If this function is ignored for any of the enabled sanitizers,
  635. // disable the sanitizer for the function.
  636. do {
  637. #define SANITIZER(NAME, ID) \
  638. if (SanOpts.empty()) \
  639. break; \
  640. if (SanOpts.has(SanitizerKind::ID)) \
  641. if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
  642. SanOpts.set(SanitizerKind::ID, false);
  643. #include "clang/Basic/Sanitizers.def"
  644. #undef SANITIZER
  645. } while (false);
  646. if (D) {
  647. bool NoSanitizeCoverage = false;
  648. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  649. // Apply the no_sanitize* attributes to SanOpts.
  650. SanitizerMask mask = Attr->getMask();
  651. SanOpts.Mask &= ~mask;
  652. if (mask & SanitizerKind::Address)
  653. SanOpts.set(SanitizerKind::KernelAddress, false);
  654. if (mask & SanitizerKind::KernelAddress)
  655. SanOpts.set(SanitizerKind::Address, false);
  656. if (mask & SanitizerKind::HWAddress)
  657. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  658. if (mask & SanitizerKind::KernelHWAddress)
  659. SanOpts.set(SanitizerKind::HWAddress, false);
  660. // SanitizeCoverage is not handled by SanOpts.
  661. if (Attr->hasCoverage())
  662. NoSanitizeCoverage = true;
  663. }
  664. if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage())
  665. Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
  666. }
  667. // Apply sanitizer attributes to the function.
  668. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  669. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  670. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  671. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  672. if (SanOpts.has(SanitizerKind::MemTag))
  673. Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
  674. if (SanOpts.has(SanitizerKind::Thread))
  675. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  676. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  677. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  678. if (SanOpts.has(SanitizerKind::SafeStack))
  679. Fn->addFnAttr(llvm::Attribute::SafeStack);
  680. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  681. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  682. // Apply fuzzing attribute to the function.
  683. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  684. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  685. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  686. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  687. if (SanOpts.has(SanitizerKind::Thread)) {
  688. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  689. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  690. if (OMD->getMethodFamily() == OMF_dealloc ||
  691. OMD->getMethodFamily() == OMF_initialize ||
  692. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  693. markAsIgnoreThreadCheckingAtRuntime(Fn);
  694. }
  695. }
  696. }
  697. // Ignore unrelated casts in STL allocate() since the allocator must cast
  698. // from void* to T* before object initialization completes. Don't match on the
  699. // namespace because not all allocators are in std::
  700. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  701. if (matchesStlAllocatorFn(D, getContext()))
  702. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  703. }
  704. // Ignore null checks in coroutine functions since the coroutines passes
  705. // are not aware of how to move the extra UBSan instructions across the split
  706. // coroutine boundaries.
  707. if (D && SanOpts.has(SanitizerKind::Null))
  708. if (FD && FD->getBody() &&
  709. FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass)
  710. SanOpts.Mask &= ~SanitizerKind::Null;
  711. // Apply xray attributes to the function (as a string, for now)
  712. bool AlwaysXRayAttr = false;
  713. if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) {
  714. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  715. XRayInstrKind::FunctionEntry) ||
  716. CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  717. XRayInstrKind::FunctionExit)) {
  718. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) {
  719. Fn->addFnAttr("function-instrument", "xray-always");
  720. AlwaysXRayAttr = true;
  721. }
  722. if (XRayAttr->neverXRayInstrument())
  723. Fn->addFnAttr("function-instrument", "xray-never");
  724. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  725. if (ShouldXRayInstrumentFunction())
  726. Fn->addFnAttr("xray-log-args",
  727. llvm::utostr(LogArgs->getArgumentCount()));
  728. }
  729. } else {
  730. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  731. Fn->addFnAttr(
  732. "xray-instruction-threshold",
  733. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  734. }
  735. if (ShouldXRayInstrumentFunction()) {
  736. if (CGM.getCodeGenOpts().XRayIgnoreLoops)
  737. Fn->addFnAttr("xray-ignore-loops");
  738. if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  739. XRayInstrKind::FunctionExit))
  740. Fn->addFnAttr("xray-skip-exit");
  741. if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  742. XRayInstrKind::FunctionEntry))
  743. Fn->addFnAttr("xray-skip-entry");
  744. auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups;
  745. if (FuncGroups > 1) {
  746. auto FuncName = llvm::makeArrayRef<uint8_t>(
  747. CurFn->getName().bytes_begin(), CurFn->getName().bytes_end());
  748. auto Group = crc32(FuncName) % FuncGroups;
  749. if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup &&
  750. !AlwaysXRayAttr)
  751. Fn->addFnAttr("function-instrument", "xray-never");
  752. }
  753. }
  754. if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone)
  755. if (CGM.isProfileInstrExcluded(Fn, Loc))
  756. Fn->addFnAttr(llvm::Attribute::NoProfile);
  757. unsigned Count, Offset;
  758. if (const auto *Attr =
  759. D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) {
  760. Count = Attr->getCount();
  761. Offset = Attr->getOffset();
  762. } else {
  763. Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount;
  764. Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset;
  765. }
  766. if (Count && Offset <= Count) {
  767. Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset));
  768. if (Offset)
  769. Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset));
  770. }
  771. // Instruct that functions for COFF/CodeView targets should start with a
  772. // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64
  773. // backends as they don't need it -- instructions on these architectures are
  774. // always atomically patchable at runtime.
  775. if (CGM.getCodeGenOpts().HotPatch &&
  776. getContext().getTargetInfo().getTriple().isX86())
  777. Fn->addFnAttr("patchable-function", "prologue-short-redirect");
  778. // Add no-jump-tables value.
  779. if (CGM.getCodeGenOpts().NoUseJumpTables)
  780. Fn->addFnAttr("no-jump-tables", "true");
  781. // Add no-inline-line-tables value.
  782. if (CGM.getCodeGenOpts().NoInlineLineTables)
  783. Fn->addFnAttr("no-inline-line-tables");
  784. // Add profile-sample-accurate value.
  785. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  786. Fn->addFnAttr("profile-sample-accurate");
  787. if (!CGM.getCodeGenOpts().SampleProfileFile.empty())
  788. Fn->addFnAttr("use-sample-profile");
  789. if (D && D->hasAttr<CFICanonicalJumpTableAttr>())
  790. Fn->addFnAttr("cfi-canonical-jump-table");
  791. if (D && D->hasAttr<NoProfileFunctionAttr>())
  792. Fn->addFnAttr(llvm::Attribute::NoProfile);
  793. if (FD && getLangOpts().OpenCL) {
  794. // Add metadata for a kernel function.
  795. EmitOpenCLKernelMetadata(FD, Fn);
  796. }
  797. // If we are checking function types, emit a function type signature as
  798. // prologue data.
  799. if (FD && getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  800. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  801. // Remove any (C++17) exception specifications, to allow calling e.g. a
  802. // noexcept function through a non-noexcept pointer.
  803. auto ProtoTy = getContext().getFunctionTypeWithExceptionSpec(
  804. FD->getType(), EST_None);
  805. llvm::Constant *FTRTTIConst =
  806. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  807. llvm::Constant *FTRTTIConstEncoded =
  808. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  809. llvm::Constant *PrologueStructElems[] = {PrologueSig, FTRTTIConstEncoded};
  810. llvm::Constant *PrologueStructConst =
  811. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  812. Fn->setPrologueData(PrologueStructConst);
  813. }
  814. }
  815. // If we're checking nullability, we need to know whether we can check the
  816. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  817. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  818. auto Nullability = FnRetTy->getNullability(getContext());
  819. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  820. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  821. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  822. RetValNullabilityPrecondition =
  823. llvm::ConstantInt::getTrue(getLLVMContext());
  824. }
  825. }
  826. // If we're in C++ mode and the function name is "main", it is guaranteed
  827. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  828. // used within a program").
  829. //
  830. // OpenCL C 2.0 v2.2-11 s6.9.i:
  831. // Recursion is not supported.
  832. //
  833. // SYCL v1.2.1 s3.10:
  834. // kernels cannot include RTTI information, exception classes,
  835. // recursive code, virtual functions or make use of C++ libraries that
  836. // are not compiled for the device.
  837. if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) ||
  838. getLangOpts().OpenCL || getLangOpts().SYCLIsDevice ||
  839. (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>())))
  840. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  841. llvm::RoundingMode RM = getLangOpts().getFPRoundingMode();
  842. llvm::fp::ExceptionBehavior FPExceptionBehavior =
  843. ToConstrainedExceptMD(getLangOpts().getFPExceptionMode());
  844. Builder.setDefaultConstrainedRounding(RM);
  845. Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
  846. if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) ||
  847. (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
  848. RM != llvm::RoundingMode::NearestTiesToEven))) {
  849. Builder.setIsFPConstrained(true);
  850. Fn->addFnAttr(llvm::Attribute::StrictFP);
  851. }
  852. // If a custom alignment is used, force realigning to this alignment on
  853. // any main function which certainly will need it.
  854. if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  855. CGM.getCodeGenOpts().StackAlignment))
  856. Fn->addFnAttr("stackrealign");
  857. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  858. // Create a marker to make it easy to insert allocas into the entryblock
  859. // later. Don't create this with the builder, because we don't want it
  860. // folded.
  861. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  862. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  863. ReturnBlock = getJumpDestInCurrentScope("return");
  864. Builder.SetInsertPoint(EntryBB);
  865. // If we're checking the return value, allocate space for a pointer to a
  866. // precise source location of the checked return statement.
  867. if (requiresReturnValueCheck()) {
  868. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  869. Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy),
  870. ReturnLocation);
  871. }
  872. // Emit subprogram debug descriptor.
  873. if (CGDebugInfo *DI = getDebugInfo()) {
  874. // Reconstruct the type from the argument list so that implicit parameters,
  875. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  876. // convention.
  877. DI->emitFunctionStart(GD, Loc, StartLoc,
  878. DI->getFunctionType(FD, RetTy, Args), CurFn,
  879. CurFuncIsThunk);
  880. }
  881. if (ShouldInstrumentFunction()) {
  882. if (CGM.getCodeGenOpts().InstrumentFunctions)
  883. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  884. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  885. CurFn->addFnAttr("instrument-function-entry-inlined",
  886. "__cyg_profile_func_enter");
  887. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  888. CurFn->addFnAttr("instrument-function-entry-inlined",
  889. "__cyg_profile_func_enter_bare");
  890. }
  891. // Since emitting the mcount call here impacts optimizations such as function
  892. // inlining, we just add an attribute to insert a mcount call in backend.
  893. // The attribute "counting-function" is set to mcount function name which is
  894. // architecture dependent.
  895. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  896. // Calls to fentry/mcount should not be generated if function has
  897. // the no_instrument_function attribute.
  898. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  899. if (CGM.getCodeGenOpts().CallFEntry)
  900. Fn->addFnAttr("fentry-call", "true");
  901. else {
  902. Fn->addFnAttr("instrument-function-entry-inlined",
  903. getTarget().getMCountName());
  904. }
  905. if (CGM.getCodeGenOpts().MNopMCount) {
  906. if (!CGM.getCodeGenOpts().CallFEntry)
  907. CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
  908. << "-mnop-mcount" << "-mfentry";
  909. Fn->addFnAttr("mnop-mcount");
  910. }
  911. if (CGM.getCodeGenOpts().RecordMCount) {
  912. if (!CGM.getCodeGenOpts().CallFEntry)
  913. CGM.getDiags().Report(diag::err_opt_not_valid_without_opt)
  914. << "-mrecord-mcount" << "-mfentry";
  915. Fn->addFnAttr("mrecord-mcount");
  916. }
  917. }
  918. }
  919. if (CGM.getCodeGenOpts().PackedStack) {
  920. if (getContext().getTargetInfo().getTriple().getArch() !=
  921. llvm::Triple::systemz)
  922. CGM.getDiags().Report(diag::err_opt_not_valid_on_target)
  923. << "-mpacked-stack";
  924. Fn->addFnAttr("packed-stack");
  925. }
  926. if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX &&
  927. !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc))
  928. Fn->addFnAttr("warn-stack-size",
  929. std::to_string(CGM.getCodeGenOpts().WarnStackSize));
  930. if (RetTy->isVoidType()) {
  931. // Void type; nothing to return.
  932. ReturnValue = Address::invalid();
  933. // Count the implicit return.
  934. if (!endsWithReturn(D))
  935. ++NumReturnExprs;
  936. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
  937. // Indirect return; emit returned value directly into sret slot.
  938. // This reduces code size, and affects correctness in C++.
  939. auto AI = CurFn->arg_begin();
  940. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  941. ++AI;
  942. ReturnValue = Address(&*AI, ConvertType(RetTy),
  943. CurFnInfo->getReturnInfo().getIndirectAlign());
  944. if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
  945. ReturnValuePointer =
  946. CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
  947. Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
  948. ReturnValue.getPointer(), Int8PtrTy),
  949. ReturnValuePointer);
  950. }
  951. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  952. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  953. // Load the sret pointer from the argument struct and return into that.
  954. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  955. llvm::Function::arg_iterator EI = CurFn->arg_end();
  956. --EI;
  957. llvm::Value *Addr = Builder.CreateStructGEP(
  958. EI->getType()->getPointerElementType(), &*EI, Idx);
  959. llvm::Type *Ty =
  960. cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
  961. ReturnValuePointer = Address(Addr, getPointerAlign());
  962. Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result");
  963. ReturnValue = Address(Addr, CGM.getNaturalTypeAlignment(RetTy));
  964. } else {
  965. ReturnValue = CreateIRTemp(RetTy, "retval");
  966. // Tell the epilog emitter to autorelease the result. We do this
  967. // now so that various specialized functions can suppress it
  968. // during their IR-generation.
  969. if (getLangOpts().ObjCAutoRefCount &&
  970. !CurFnInfo->isReturnsRetained() &&
  971. RetTy->isObjCRetainableType())
  972. AutoreleaseResult = true;
  973. }
  974. EmitStartEHSpec(CurCodeDecl);
  975. PrologueCleanupDepth = EHStack.stable_begin();
  976. // Emit OpenMP specific initialization of the device functions.
  977. if (getLangOpts().OpenMP && CurCodeDecl)
  978. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  979. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  980. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  981. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  982. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  983. if (MD->getParent()->isLambda() &&
  984. MD->getOverloadedOperator() == OO_Call) {
  985. // We're in a lambda; figure out the captures.
  986. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  987. LambdaThisCaptureField);
  988. if (LambdaThisCaptureField) {
  989. // If the lambda captures the object referred to by '*this' - either by
  990. // value or by reference, make sure CXXThisValue points to the correct
  991. // object.
  992. // Get the lvalue for the field (which is a copy of the enclosing object
  993. // or contains the address of the enclosing object).
  994. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  995. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  996. // If the enclosing object was captured by value, just use its address.
  997. CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer();
  998. } else {
  999. // Load the lvalue pointed to by the field, since '*this' was captured
  1000. // by reference.
  1001. CXXThisValue =
  1002. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  1003. }
  1004. }
  1005. for (auto *FD : MD->getParent()->fields()) {
  1006. if (FD->hasCapturedVLAType()) {
  1007. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  1008. SourceLocation()).getScalarVal();
  1009. auto VAT = FD->getCapturedVLAType();
  1010. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  1011. }
  1012. }
  1013. } else {
  1014. // Not in a lambda; just use 'this' from the method.
  1015. // FIXME: Should we generate a new load for each use of 'this'? The
  1016. // fast register allocator would be happier...
  1017. CXXThisValue = CXXABIThisValue;
  1018. }
  1019. // Check the 'this' pointer once per function, if it's available.
  1020. if (CXXABIThisValue) {
  1021. SanitizerSet SkippedChecks;
  1022. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  1023. QualType ThisTy = MD->getThisType();
  1024. // If this is the call operator of a lambda with no capture-default, it
  1025. // may have a static invoker function, which may call this operator with
  1026. // a null 'this' pointer.
  1027. if (isLambdaCallOperator(MD) &&
  1028. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  1029. SkippedChecks.set(SanitizerKind::Null, true);
  1030. EmitTypeCheck(
  1031. isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall,
  1032. Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
  1033. }
  1034. }
  1035. // If any of the arguments have a variably modified type, make sure to
  1036. // emit the type size.
  1037. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1038. i != e; ++i) {
  1039. const VarDecl *VD = *i;
  1040. // Dig out the type as written from ParmVarDecls; it's unclear whether
  1041. // the standard (C99 6.9.1p10) requires this, but we're following the
  1042. // precedent set by gcc.
  1043. QualType Ty;
  1044. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  1045. Ty = PVD->getOriginalType();
  1046. else
  1047. Ty = VD->getType();
  1048. if (Ty->isVariablyModifiedType())
  1049. EmitVariablyModifiedType(Ty);
  1050. }
  1051. // Emit a location at the end of the prologue.
  1052. if (CGDebugInfo *DI = getDebugInfo())
  1053. DI->EmitLocation(Builder, StartLoc);
  1054. // TODO: Do we need to handle this in two places like we do with
  1055. // target-features/target-cpu?
  1056. if (CurFuncDecl)
  1057. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  1058. LargestVectorWidth = VecWidth->getVectorWidth();
  1059. }
  1060. void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
  1061. incrementProfileCounter(Body);
  1062. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  1063. EmitCompoundStmtWithoutScope(*S);
  1064. else
  1065. EmitStmt(Body);
  1066. // This is checked after emitting the function body so we know if there
  1067. // are any permitted infinite loops.
  1068. if (checkIfFunctionMustProgress())
  1069. CurFn->addFnAttr(llvm::Attribute::MustProgress);
  1070. }
  1071. /// When instrumenting to collect profile data, the counts for some blocks
  1072. /// such as switch cases need to not include the fall-through counts, so
  1073. /// emit a branch around the instrumentation code. When not instrumenting,
  1074. /// this just calls EmitBlock().
  1075. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  1076. const Stmt *S) {
  1077. llvm::BasicBlock *SkipCountBB = nullptr;
  1078. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  1079. // When instrumenting for profiling, the fallthrough to certain
  1080. // statements needs to skip over the instrumentation code so that we
  1081. // get an accurate count.
  1082. SkipCountBB = createBasicBlock("skipcount");
  1083. EmitBranch(SkipCountBB);
  1084. }
  1085. EmitBlock(BB);
  1086. uint64_t CurrentCount = getCurrentProfileCount();
  1087. incrementProfileCounter(S);
  1088. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  1089. if (SkipCountBB)
  1090. EmitBlock(SkipCountBB);
  1091. }
  1092. /// Tries to mark the given function nounwind based on the
  1093. /// non-existence of any throwing calls within it. We believe this is
  1094. /// lightweight enough to do at -O0.
  1095. static void TryMarkNoThrow(llvm::Function *F) {
  1096. // LLVM treats 'nounwind' on a function as part of the type, so we
  1097. // can't do this on functions that can be overwritten.
  1098. if (F->isInterposable()) return;
  1099. for (llvm::BasicBlock &BB : *F)
  1100. for (llvm::Instruction &I : BB)
  1101. if (I.mayThrow())
  1102. return;
  1103. F->setDoesNotThrow();
  1104. }
  1105. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  1106. FunctionArgList &Args) {
  1107. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1108. QualType ResTy = FD->getReturnType();
  1109. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1110. if (MD && MD->isInstance()) {
  1111. if (CGM.getCXXABI().HasThisReturn(GD))
  1112. ResTy = MD->getThisType();
  1113. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  1114. ResTy = CGM.getContext().VoidPtrTy;
  1115. CGM.getCXXABI().buildThisParam(*this, Args);
  1116. }
  1117. // The base version of an inheriting constructor whose constructed base is a
  1118. // virtual base is not passed any arguments (because it doesn't actually call
  1119. // the inherited constructor).
  1120. bool PassedParams = true;
  1121. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  1122. if (auto Inherited = CD->getInheritedConstructor())
  1123. PassedParams =
  1124. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  1125. if (PassedParams) {
  1126. for (auto *Param : FD->parameters()) {
  1127. Args.push_back(Param);
  1128. if (!Param->hasAttr<PassObjectSizeAttr>())
  1129. continue;
  1130. auto *Implicit = ImplicitParamDecl::Create(
  1131. getContext(), Param->getDeclContext(), Param->getLocation(),
  1132. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  1133. SizeArguments[Param] = Implicit;
  1134. Args.push_back(Implicit);
  1135. }
  1136. }
  1137. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  1138. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  1139. return ResTy;
  1140. }
  1141. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1142. const CGFunctionInfo &FnInfo) {
  1143. assert(Fn && "generating code for null Function");
  1144. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1145. CurGD = GD;
  1146. FunctionArgList Args;
  1147. QualType ResTy = BuildFunctionArgList(GD, Args);
  1148. if (FD->isInlineBuiltinDeclaration()) {
  1149. // When generating code for a builtin with an inline declaration, use a
  1150. // mangled name to hold the actual body, while keeping an external
  1151. // definition in case the function pointer is referenced somewhere.
  1152. std::string FDInlineName = (Fn->getName() + ".inline").str();
  1153. llvm::Module *M = Fn->getParent();
  1154. llvm::Function *Clone = M->getFunction(FDInlineName);
  1155. if (!Clone) {
  1156. Clone = llvm::Function::Create(Fn->getFunctionType(),
  1157. llvm::GlobalValue::InternalLinkage,
  1158. Fn->getAddressSpace(), FDInlineName, M);
  1159. Clone->addFnAttr(llvm::Attribute::AlwaysInline);
  1160. }
  1161. Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1162. Fn = Clone;
  1163. } else {
  1164. // Detect the unusual situation where an inline version is shadowed by a
  1165. // non-inline version. In that case we should pick the external one
  1166. // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way
  1167. // to detect that situation before we reach codegen, so do some late
  1168. // replacement.
  1169. for (const FunctionDecl *PD = FD->getPreviousDecl(); PD;
  1170. PD = PD->getPreviousDecl()) {
  1171. if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
  1172. std::string FDInlineName = (Fn->getName() + ".inline").str();
  1173. llvm::Module *M = Fn->getParent();
  1174. if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
  1175. Clone->replaceAllUsesWith(Fn);
  1176. Clone->eraseFromParent();
  1177. }
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. // Check if we should generate debug info for this function.
  1183. if (FD->hasAttr<NoDebugAttr>()) {
  1184. // Clear non-distinct debug info that was possibly attached to the function
  1185. // due to an earlier declaration without the nodebug attribute
  1186. Fn->setSubprogram(nullptr);
  1187. // Disable debug info indefinitely for this function
  1188. DebugInfo = nullptr;
  1189. }
  1190. // The function might not have a body if we're generating thunks for a
  1191. // function declaration.
  1192. SourceRange BodyRange;
  1193. if (Stmt *Body = FD->getBody())
  1194. BodyRange = Body->getSourceRange();
  1195. else
  1196. BodyRange = FD->getLocation();
  1197. CurEHLocation = BodyRange.getEnd();
  1198. // Use the location of the start of the function to determine where
  1199. // the function definition is located. By default use the location
  1200. // of the declaration as the location for the subprogram. A function
  1201. // may lack a declaration in the source code if it is created by code
  1202. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1203. SourceLocation Loc = FD->getLocation();
  1204. // If this is a function specialization then use the pattern body
  1205. // as the location for the function.
  1206. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1207. if (SpecDecl->hasBody(SpecDecl))
  1208. Loc = SpecDecl->getLocation();
  1209. Stmt *Body = FD->getBody();
  1210. if (Body) {
  1211. // Coroutines always emit lifetime markers.
  1212. if (isa<CoroutineBodyStmt>(Body))
  1213. ShouldEmitLifetimeMarkers = true;
  1214. // Initialize helper which will detect jumps which can cause invalid
  1215. // lifetime markers.
  1216. if (ShouldEmitLifetimeMarkers)
  1217. Bypasses.Init(Body);
  1218. }
  1219. // Emit the standard function prologue.
  1220. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1221. // Save parameters for coroutine function.
  1222. if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
  1223. for (const auto *ParamDecl : FD->parameters())
  1224. FnArgs.push_back(ParamDecl);
  1225. // Generate the body of the function.
  1226. PGO.assignRegionCounters(GD, CurFn);
  1227. if (isa<CXXDestructorDecl>(FD))
  1228. EmitDestructorBody(Args);
  1229. else if (isa<CXXConstructorDecl>(FD))
  1230. EmitConstructorBody(Args);
  1231. else if (getLangOpts().CUDA &&
  1232. !getLangOpts().CUDAIsDevice &&
  1233. FD->hasAttr<CUDAGlobalAttr>())
  1234. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1235. else if (isa<CXXMethodDecl>(FD) &&
  1236. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1237. // The lambda static invoker function is special, because it forwards or
  1238. // clones the body of the function call operator (but is actually static).
  1239. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1240. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1241. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1242. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1243. // Implicit copy-assignment gets the same special treatment as implicit
  1244. // copy-constructors.
  1245. emitImplicitAssignmentOperatorBody(Args);
  1246. } else if (Body) {
  1247. EmitFunctionBody(Body);
  1248. } else
  1249. llvm_unreachable("no definition for emitted function");
  1250. // C++11 [stmt.return]p2:
  1251. // Flowing off the end of a function [...] results in undefined behavior in
  1252. // a value-returning function.
  1253. // C11 6.9.1p12:
  1254. // If the '}' that terminates a function is reached, and the value of the
  1255. // function call is used by the caller, the behavior is undefined.
  1256. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1257. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1258. bool ShouldEmitUnreachable =
  1259. CGM.getCodeGenOpts().StrictReturn ||
  1260. !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType());
  1261. if (SanOpts.has(SanitizerKind::Return)) {
  1262. SanitizerScope SanScope(this);
  1263. llvm::Value *IsFalse = Builder.getFalse();
  1264. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1265. SanitizerHandler::MissingReturn,
  1266. EmitCheckSourceLocation(FD->getLocation()), None);
  1267. } else if (ShouldEmitUnreachable) {
  1268. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1269. EmitTrapCall(llvm::Intrinsic::trap);
  1270. }
  1271. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1272. Builder.CreateUnreachable();
  1273. Builder.ClearInsertionPoint();
  1274. }
  1275. }
  1276. // Emit the standard function epilogue.
  1277. FinishFunction(BodyRange.getEnd());
  1278. // If we haven't marked the function nothrow through other means, do
  1279. // a quick pass now to see if we can.
  1280. if (!CurFn->doesNotThrow())
  1281. TryMarkNoThrow(CurFn);
  1282. }
  1283. /// ContainsLabel - Return true if the statement contains a label in it. If
  1284. /// this statement is not executed normally, it not containing a label means
  1285. /// that we can just remove the code.
  1286. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1287. // Null statement, not a label!
  1288. if (!S) return false;
  1289. // If this is a label, we have to emit the code, consider something like:
  1290. // if (0) { ... foo: bar(); } goto foo;
  1291. //
  1292. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1293. // can't jump to one from outside their declared region.
  1294. if (isa<LabelStmt>(S))
  1295. return true;
  1296. // If this is a case/default statement, and we haven't seen a switch, we have
  1297. // to emit the code.
  1298. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1299. return true;
  1300. // If this is a switch statement, we want to ignore cases below it.
  1301. if (isa<SwitchStmt>(S))
  1302. IgnoreCaseStmts = true;
  1303. // Scan subexpressions for verboten labels.
  1304. for (const Stmt *SubStmt : S->children())
  1305. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1306. return true;
  1307. return false;
  1308. }
  1309. /// containsBreak - Return true if the statement contains a break out of it.
  1310. /// If the statement (recursively) contains a switch or loop with a break
  1311. /// inside of it, this is fine.
  1312. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1313. // Null statement, not a label!
  1314. if (!S) return false;
  1315. // If this is a switch or loop that defines its own break scope, then we can
  1316. // include it and anything inside of it.
  1317. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1318. isa<ForStmt>(S))
  1319. return false;
  1320. if (isa<BreakStmt>(S))
  1321. return true;
  1322. // Scan subexpressions for verboten breaks.
  1323. for (const Stmt *SubStmt : S->children())
  1324. if (containsBreak(SubStmt))
  1325. return true;
  1326. return false;
  1327. }
  1328. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1329. if (!S) return false;
  1330. // Some statement kinds add a scope and thus never add a decl to the current
  1331. // scope. Note, this list is longer than the list of statements that might
  1332. // have an unscoped decl nested within them, but this way is conservatively
  1333. // correct even if more statement kinds are added.
  1334. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1335. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1336. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1337. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1338. return false;
  1339. if (isa<DeclStmt>(S))
  1340. return true;
  1341. for (const Stmt *SubStmt : S->children())
  1342. if (mightAddDeclToScope(SubStmt))
  1343. return true;
  1344. return false;
  1345. }
  1346. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1347. /// to a constant, or if it does but contains a label, return false. If it
  1348. /// constant folds return true and set the boolean result in Result.
  1349. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1350. bool &ResultBool,
  1351. bool AllowLabels) {
  1352. llvm::APSInt ResultInt;
  1353. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1354. return false;
  1355. ResultBool = ResultInt.getBoolValue();
  1356. return true;
  1357. }
  1358. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1359. /// to a constant, or if it does but contains a label, return false. If it
  1360. /// constant folds return true and set the folded value.
  1361. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1362. llvm::APSInt &ResultInt,
  1363. bool AllowLabels) {
  1364. // FIXME: Rename and handle conversion of other evaluatable things
  1365. // to bool.
  1366. Expr::EvalResult Result;
  1367. if (!Cond->EvaluateAsInt(Result, getContext()))
  1368. return false; // Not foldable, not integer or not fully evaluatable.
  1369. llvm::APSInt Int = Result.Val.getInt();
  1370. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1371. return false; // Contains a label.
  1372. ResultInt = Int;
  1373. return true;
  1374. }
  1375. /// Determine whether the given condition is an instrumentable condition
  1376. /// (i.e. no "&&" or "||").
  1377. bool CodeGenFunction::isInstrumentedCondition(const Expr *C) {
  1378. // Bypass simplistic logical-NOT operator before determining whether the
  1379. // condition contains any other logical operator.
  1380. if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens()))
  1381. if (UnOp->getOpcode() == UO_LNot)
  1382. C = UnOp->getSubExpr();
  1383. const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens());
  1384. return (!BOp || !BOp->isLogicalOp());
  1385. }
  1386. /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that
  1387. /// increments a profile counter based on the semantics of the given logical
  1388. /// operator opcode. This is used to instrument branch condition coverage for
  1389. /// logical operators.
  1390. void CodeGenFunction::EmitBranchToCounterBlock(
  1391. const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock,
  1392. llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */,
  1393. Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) {
  1394. // If not instrumenting, just emit a branch.
  1395. bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
  1396. if (!InstrumentRegions || !isInstrumentedCondition(Cond))
  1397. return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH);
  1398. llvm::BasicBlock *ThenBlock = nullptr;
  1399. llvm::BasicBlock *ElseBlock = nullptr;
  1400. llvm::BasicBlock *NextBlock = nullptr;
  1401. // Create the block we'll use to increment the appropriate counter.
  1402. llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt");
  1403. // Set block pointers according to Logical-AND (BO_LAnd) semantics. This
  1404. // means we need to evaluate the condition and increment the counter on TRUE:
  1405. //
  1406. // if (Cond)
  1407. // goto CounterIncrBlock;
  1408. // else
  1409. // goto FalseBlock;
  1410. //
  1411. // CounterIncrBlock:
  1412. // Counter++;
  1413. // goto TrueBlock;
  1414. if (LOp == BO_LAnd) {
  1415. ThenBlock = CounterIncrBlock;
  1416. ElseBlock = FalseBlock;
  1417. NextBlock = TrueBlock;
  1418. }
  1419. // Set block pointers according to Logical-OR (BO_LOr) semantics. This means
  1420. // we need to evaluate the condition and increment the counter on FALSE:
  1421. //
  1422. // if (Cond)
  1423. // goto TrueBlock;
  1424. // else
  1425. // goto CounterIncrBlock;
  1426. //
  1427. // CounterIncrBlock:
  1428. // Counter++;
  1429. // goto FalseBlock;
  1430. else if (LOp == BO_LOr) {
  1431. ThenBlock = TrueBlock;
  1432. ElseBlock = CounterIncrBlock;
  1433. NextBlock = FalseBlock;
  1434. } else {
  1435. llvm_unreachable("Expected Opcode must be that of a Logical Operator");
  1436. }
  1437. // Emit Branch based on condition.
  1438. EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH);
  1439. // Emit the block containing the counter increment(s).
  1440. EmitBlock(CounterIncrBlock);
  1441. // Increment corresponding counter; if index not provided, use Cond as index.
  1442. incrementProfileCounter(CntrIdx ? CntrIdx : Cond);
  1443. // Go to the next block.
  1444. EmitBranch(NextBlock);
  1445. }
  1446. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1447. /// statement) to the specified blocks. Based on the condition, this might try
  1448. /// to simplify the codegen of the conditional based on the branch.
  1449. /// \param LH The value of the likelihood attribute on the True branch.
  1450. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1451. llvm::BasicBlock *TrueBlock,
  1452. llvm::BasicBlock *FalseBlock,
  1453. uint64_t TrueCount,
  1454. Stmt::Likelihood LH) {
  1455. Cond = Cond->IgnoreParens();
  1456. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1457. // Handle X && Y in a condition.
  1458. if (CondBOp->getOpcode() == BO_LAnd) {
  1459. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1460. // folded if the case was simple enough.
  1461. bool ConstantBool = false;
  1462. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1463. ConstantBool) {
  1464. // br(1 && X) -> br(X).
  1465. incrementProfileCounter(CondBOp);
  1466. return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
  1467. FalseBlock, TrueCount, LH);
  1468. }
  1469. // If we have "X && 1", simplify the code to use an uncond branch.
  1470. // "X && 0" would have been constant folded to 0.
  1471. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1472. ConstantBool) {
  1473. // br(X && 1) -> br(X).
  1474. return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock,
  1475. FalseBlock, TrueCount, LH, CondBOp);
  1476. }
  1477. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1478. // want to jump to the FalseBlock.
  1479. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1480. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1481. // can be propagated to that branch.
  1482. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1483. ConditionalEvaluation eval(*this);
  1484. {
  1485. ApplyDebugLocation DL(*this, Cond);
  1486. // Propagate the likelihood attribute like __builtin_expect
  1487. // __builtin_expect(X && Y, 1) -> X and Y are likely
  1488. // __builtin_expect(X && Y, 0) -> only Y is unlikely
  1489. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount,
  1490. LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH);
  1491. EmitBlock(LHSTrue);
  1492. }
  1493. incrementProfileCounter(CondBOp);
  1494. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1495. // Any temporaries created here are conditional.
  1496. eval.begin(*this);
  1497. EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock,
  1498. FalseBlock, TrueCount, LH);
  1499. eval.end(*this);
  1500. return;
  1501. }
  1502. if (CondBOp->getOpcode() == BO_LOr) {
  1503. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1504. // folded if the case was simple enough.
  1505. bool ConstantBool = false;
  1506. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1507. !ConstantBool) {
  1508. // br(0 || X) -> br(X).
  1509. incrementProfileCounter(CondBOp);
  1510. return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock,
  1511. FalseBlock, TrueCount, LH);
  1512. }
  1513. // If we have "X || 0", simplify the code to use an uncond branch.
  1514. // "X || 1" would have been constant folded to 1.
  1515. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1516. !ConstantBool) {
  1517. // br(X || 0) -> br(X).
  1518. return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock,
  1519. FalseBlock, TrueCount, LH, CondBOp);
  1520. }
  1521. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1522. // want to jump to the TrueBlock.
  1523. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1524. // We have the count for entry to the RHS and for the whole expression
  1525. // being true, so we can divy up True count between the short circuit and
  1526. // the RHS.
  1527. uint64_t LHSCount =
  1528. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1529. uint64_t RHSCount = TrueCount - LHSCount;
  1530. ConditionalEvaluation eval(*this);
  1531. {
  1532. // Propagate the likelihood attribute like __builtin_expect
  1533. // __builtin_expect(X || Y, 1) -> only Y is likely
  1534. // __builtin_expect(X || Y, 0) -> both X and Y are unlikely
  1535. ApplyDebugLocation DL(*this, Cond);
  1536. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount,
  1537. LH == Stmt::LH_Likely ? Stmt::LH_None : LH);
  1538. EmitBlock(LHSFalse);
  1539. }
  1540. incrementProfileCounter(CondBOp);
  1541. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1542. // Any temporaries created here are conditional.
  1543. eval.begin(*this);
  1544. EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock,
  1545. RHSCount, LH);
  1546. eval.end(*this);
  1547. return;
  1548. }
  1549. }
  1550. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1551. // br(!x, t, f) -> br(x, f, t)
  1552. if (CondUOp->getOpcode() == UO_LNot) {
  1553. // Negate the count.
  1554. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1555. // The values of the enum are chosen to make this negation possible.
  1556. LH = static_cast<Stmt::Likelihood>(-LH);
  1557. // Negate the condition and swap the destination blocks.
  1558. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1559. FalseCount, LH);
  1560. }
  1561. }
  1562. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1563. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1564. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1565. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1566. // The ConditionalOperator itself has no likelihood information for its
  1567. // true and false branches. This matches the behavior of __builtin_expect.
  1568. ConditionalEvaluation cond(*this);
  1569. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1570. getProfileCount(CondOp), Stmt::LH_None);
  1571. // When computing PGO branch weights, we only know the overall count for
  1572. // the true block. This code is essentially doing tail duplication of the
  1573. // naive code-gen, introducing new edges for which counts are not
  1574. // available. Divide the counts proportionally between the LHS and RHS of
  1575. // the conditional operator.
  1576. uint64_t LHSScaledTrueCount = 0;
  1577. if (TrueCount) {
  1578. double LHSRatio =
  1579. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1580. LHSScaledTrueCount = TrueCount * LHSRatio;
  1581. }
  1582. cond.begin(*this);
  1583. EmitBlock(LHSBlock);
  1584. incrementProfileCounter(CondOp);
  1585. {
  1586. ApplyDebugLocation DL(*this, Cond);
  1587. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1588. LHSScaledTrueCount, LH);
  1589. }
  1590. cond.end(*this);
  1591. cond.begin(*this);
  1592. EmitBlock(RHSBlock);
  1593. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1594. TrueCount - LHSScaledTrueCount, LH);
  1595. cond.end(*this);
  1596. return;
  1597. }
  1598. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1599. // Conditional operator handling can give us a throw expression as a
  1600. // condition for a case like:
  1601. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1602. // Fold this to:
  1603. // br(c, throw x, br(y, t, f))
  1604. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1605. return;
  1606. }
  1607. // Emit the code with the fully general case.
  1608. llvm::Value *CondV;
  1609. {
  1610. ApplyDebugLocation DL(*this, Cond);
  1611. CondV = EvaluateExprAsBool(Cond);
  1612. }
  1613. llvm::MDNode *Weights = nullptr;
  1614. llvm::MDNode *Unpredictable = nullptr;
  1615. // If the branch has a condition wrapped by __builtin_unpredictable,
  1616. // create metadata that specifies that the branch is unpredictable.
  1617. // Don't bother if not optimizing because that metadata would not be used.
  1618. auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
  1619. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1620. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1621. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1622. llvm::MDBuilder MDHelper(getLLVMContext());
  1623. Unpredictable = MDHelper.createUnpredictable();
  1624. }
  1625. }
  1626. // If there is a Likelihood knowledge for the cond, lower it.
  1627. // Note that if not optimizing this won't emit anything.
  1628. llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
  1629. if (CondV != NewCondV)
  1630. CondV = NewCondV;
  1631. else {
  1632. // Otherwise, lower profile counts. Note that we do this even at -O0.
  1633. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1634. Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1635. }
  1636. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1637. }
  1638. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1639. /// specified stmt yet.
  1640. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1641. CGM.ErrorUnsupported(S, Type);
  1642. }
  1643. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1644. /// variable-length array whose elements have a non-zero bit-pattern.
  1645. ///
  1646. /// \param baseType the inner-most element type of the array
  1647. /// \param src - a char* pointing to the bit-pattern for a single
  1648. /// base element of the array
  1649. /// \param sizeInChars - the total size of the VLA, in chars
  1650. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1651. Address dest, Address src,
  1652. llvm::Value *sizeInChars) {
  1653. CGBuilderTy &Builder = CGF.Builder;
  1654. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1655. llvm::Value *baseSizeInChars
  1656. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1657. Address begin =
  1658. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1659. llvm::Value *end = Builder.CreateInBoundsGEP(
  1660. begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end");
  1661. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1662. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1663. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1664. // Make a loop over the VLA. C99 guarantees that the VLA element
  1665. // count must be nonzero.
  1666. CGF.EmitBlock(loopBB);
  1667. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1668. cur->addIncoming(begin.getPointer(), originBB);
  1669. CharUnits curAlign =
  1670. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1671. // memcpy the individual element bit-pattern.
  1672. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1673. /*volatile*/ false);
  1674. // Go to the next element.
  1675. llvm::Value *next =
  1676. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1677. // Leave if that's the end of the VLA.
  1678. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1679. Builder.CreateCondBr(done, contBB, loopBB);
  1680. cur->addIncoming(next, loopBB);
  1681. CGF.EmitBlock(contBB);
  1682. }
  1683. void
  1684. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1685. // Ignore empty classes in C++.
  1686. if (getLangOpts().CPlusPlus) {
  1687. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1688. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1689. return;
  1690. }
  1691. }
  1692. // Cast the dest ptr to the appropriate i8 pointer type.
  1693. if (DestPtr.getElementType() != Int8Ty)
  1694. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1695. // Get size and alignment info for this aggregate.
  1696. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1697. llvm::Value *SizeVal;
  1698. const VariableArrayType *vla;
  1699. // Don't bother emitting a zero-byte memset.
  1700. if (size.isZero()) {
  1701. // But note that getTypeInfo returns 0 for a VLA.
  1702. if (const VariableArrayType *vlaType =
  1703. dyn_cast_or_null<VariableArrayType>(
  1704. getContext().getAsArrayType(Ty))) {
  1705. auto VlaSize = getVLASize(vlaType);
  1706. SizeVal = VlaSize.NumElts;
  1707. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1708. if (!eltSize.isOne())
  1709. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1710. vla = vlaType;
  1711. } else {
  1712. return;
  1713. }
  1714. } else {
  1715. SizeVal = CGM.getSize(size);
  1716. vla = nullptr;
  1717. }
  1718. // If the type contains a pointer to data member we can't memset it to zero.
  1719. // Instead, create a null constant and copy it to the destination.
  1720. // TODO: there are other patterns besides zero that we can usefully memset,
  1721. // like -1, which happens to be the pattern used by member-pointers.
  1722. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1723. // For a VLA, emit a single element, then splat that over the VLA.
  1724. if (vla) Ty = getContext().getBaseElementType(vla);
  1725. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1726. llvm::GlobalVariable *NullVariable =
  1727. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1728. /*isConstant=*/true,
  1729. llvm::GlobalVariable::PrivateLinkage,
  1730. NullConstant, Twine());
  1731. CharUnits NullAlign = DestPtr.getAlignment();
  1732. NullVariable->setAlignment(NullAlign.getAsAlign());
  1733. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1734. NullAlign);
  1735. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1736. // Get and call the appropriate llvm.memcpy overload.
  1737. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1738. return;
  1739. }
  1740. // Otherwise, just memset the whole thing to zero. This is legal
  1741. // because in LLVM, all default initializers (other than the ones we just
  1742. // handled above) are guaranteed to have a bit pattern of all zeros.
  1743. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1744. }
  1745. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1746. // Make sure that there is a block for the indirect goto.
  1747. if (!IndirectBranch)
  1748. GetIndirectGotoBlock();
  1749. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1750. // Make sure the indirect branch includes all of the address-taken blocks.
  1751. IndirectBranch->addDestination(BB);
  1752. return llvm::BlockAddress::get(CurFn, BB);
  1753. }
  1754. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1755. // If we already made the indirect branch for indirect goto, return its block.
  1756. if (IndirectBranch) return IndirectBranch->getParent();
  1757. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1758. // Create the PHI node that indirect gotos will add entries to.
  1759. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1760. "indirect.goto.dest");
  1761. // Create the indirect branch instruction.
  1762. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1763. return IndirectBranch->getParent();
  1764. }
  1765. /// Computes the length of an array in elements, as well as the base
  1766. /// element type and a properly-typed first element pointer.
  1767. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1768. QualType &baseType,
  1769. Address &addr) {
  1770. const ArrayType *arrayType = origArrayType;
  1771. // If it's a VLA, we have to load the stored size. Note that
  1772. // this is the size of the VLA in bytes, not its size in elements.
  1773. llvm::Value *numVLAElements = nullptr;
  1774. if (isa<VariableArrayType>(arrayType)) {
  1775. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1776. // Walk into all VLAs. This doesn't require changes to addr,
  1777. // which has type T* where T is the first non-VLA element type.
  1778. do {
  1779. QualType elementType = arrayType->getElementType();
  1780. arrayType = getContext().getAsArrayType(elementType);
  1781. // If we only have VLA components, 'addr' requires no adjustment.
  1782. if (!arrayType) {
  1783. baseType = elementType;
  1784. return numVLAElements;
  1785. }
  1786. } while (isa<VariableArrayType>(arrayType));
  1787. // We get out here only if we find a constant array type
  1788. // inside the VLA.
  1789. }
  1790. // We have some number of constant-length arrays, so addr should
  1791. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1792. // down to the first element of addr.
  1793. SmallVector<llvm::Value*, 8> gepIndices;
  1794. // GEP down to the array type.
  1795. llvm::ConstantInt *zero = Builder.getInt32(0);
  1796. gepIndices.push_back(zero);
  1797. uint64_t countFromCLAs = 1;
  1798. QualType eltType;
  1799. llvm::ArrayType *llvmArrayType =
  1800. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1801. while (llvmArrayType) {
  1802. assert(isa<ConstantArrayType>(arrayType));
  1803. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1804. == llvmArrayType->getNumElements());
  1805. gepIndices.push_back(zero);
  1806. countFromCLAs *= llvmArrayType->getNumElements();
  1807. eltType = arrayType->getElementType();
  1808. llvmArrayType =
  1809. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1810. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1811. assert((!llvmArrayType || arrayType) &&
  1812. "LLVM and Clang types are out-of-synch");
  1813. }
  1814. if (arrayType) {
  1815. // From this point onwards, the Clang array type has been emitted
  1816. // as some other type (probably a packed struct). Compute the array
  1817. // size, and just emit the 'begin' expression as a bitcast.
  1818. while (arrayType) {
  1819. countFromCLAs *=
  1820. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1821. eltType = arrayType->getElementType();
  1822. arrayType = getContext().getAsArrayType(eltType);
  1823. }
  1824. llvm::Type *baseType = ConvertType(eltType);
  1825. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1826. } else {
  1827. // Create the actual GEP.
  1828. addr = Address(Builder.CreateInBoundsGEP(
  1829. addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"),
  1830. ConvertTypeForMem(eltType),
  1831. addr.getAlignment());
  1832. }
  1833. baseType = eltType;
  1834. llvm::Value *numElements
  1835. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1836. // If we had any VLA dimensions, factor them in.
  1837. if (numVLAElements)
  1838. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1839. return numElements;
  1840. }
  1841. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1842. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1843. assert(vla && "type was not a variable array type!");
  1844. return getVLASize(vla);
  1845. }
  1846. CodeGenFunction::VlaSizePair
  1847. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1848. // The number of elements so far; always size_t.
  1849. llvm::Value *numElements = nullptr;
  1850. QualType elementType;
  1851. do {
  1852. elementType = type->getElementType();
  1853. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1854. assert(vlaSize && "no size for VLA!");
  1855. assert(vlaSize->getType() == SizeTy);
  1856. if (!numElements) {
  1857. numElements = vlaSize;
  1858. } else {
  1859. // It's undefined behavior if this wraps around, so mark it that way.
  1860. // FIXME: Teach -fsanitize=undefined to trap this.
  1861. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1862. }
  1863. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1864. return { numElements, elementType };
  1865. }
  1866. CodeGenFunction::VlaSizePair
  1867. CodeGenFunction::getVLAElements1D(QualType type) {
  1868. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1869. assert(vla && "type was not a variable array type!");
  1870. return getVLAElements1D(vla);
  1871. }
  1872. CodeGenFunction::VlaSizePair
  1873. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1874. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1875. assert(VlaSize && "no size for VLA!");
  1876. assert(VlaSize->getType() == SizeTy);
  1877. return { VlaSize, Vla->getElementType() };
  1878. }
  1879. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1880. assert(type->isVariablyModifiedType() &&
  1881. "Must pass variably modified type to EmitVLASizes!");
  1882. EnsureInsertPoint();
  1883. // We're going to walk down into the type and look for VLA
  1884. // expressions.
  1885. do {
  1886. assert(type->isVariablyModifiedType());
  1887. const Type *ty = type.getTypePtr();
  1888. switch (ty->getTypeClass()) {
  1889. #define TYPE(Class, Base)
  1890. #define ABSTRACT_TYPE(Class, Base)
  1891. #define NON_CANONICAL_TYPE(Class, Base)
  1892. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1893. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1894. #include "clang/AST/TypeNodes.inc"
  1895. llvm_unreachable("unexpected dependent type!");
  1896. // These types are never variably-modified.
  1897. case Type::Builtin:
  1898. case Type::Complex:
  1899. case Type::Vector:
  1900. case Type::ExtVector:
  1901. case Type::ConstantMatrix:
  1902. case Type::Record:
  1903. case Type::Enum:
  1904. case Type::Elaborated:
  1905. case Type::Using:
  1906. case Type::TemplateSpecialization:
  1907. case Type::ObjCTypeParam:
  1908. case Type::ObjCObject:
  1909. case Type::ObjCInterface:
  1910. case Type::ObjCObjectPointer:
  1911. case Type::BitInt:
  1912. llvm_unreachable("type class is never variably-modified!");
  1913. case Type::Adjusted:
  1914. type = cast<AdjustedType>(ty)->getAdjustedType();
  1915. break;
  1916. case Type::Decayed:
  1917. type = cast<DecayedType>(ty)->getPointeeType();
  1918. break;
  1919. case Type::Pointer:
  1920. type = cast<PointerType>(ty)->getPointeeType();
  1921. break;
  1922. case Type::BlockPointer:
  1923. type = cast<BlockPointerType>(ty)->getPointeeType();
  1924. break;
  1925. case Type::LValueReference:
  1926. case Type::RValueReference:
  1927. type = cast<ReferenceType>(ty)->getPointeeType();
  1928. break;
  1929. case Type::MemberPointer:
  1930. type = cast<MemberPointerType>(ty)->getPointeeType();
  1931. break;
  1932. case Type::ConstantArray:
  1933. case Type::IncompleteArray:
  1934. // Losing element qualification here is fine.
  1935. type = cast<ArrayType>(ty)->getElementType();
  1936. break;
  1937. case Type::VariableArray: {
  1938. // Losing element qualification here is fine.
  1939. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1940. // Unknown size indication requires no size computation.
  1941. // Otherwise, evaluate and record it.
  1942. if (const Expr *sizeExpr = vat->getSizeExpr()) {
  1943. // It's possible that we might have emitted this already,
  1944. // e.g. with a typedef and a pointer to it.
  1945. llvm::Value *&entry = VLASizeMap[sizeExpr];
  1946. if (!entry) {
  1947. llvm::Value *size = EmitScalarExpr(sizeExpr);
  1948. // C11 6.7.6.2p5:
  1949. // If the size is an expression that is not an integer constant
  1950. // expression [...] each time it is evaluated it shall have a value
  1951. // greater than zero.
  1952. if (SanOpts.has(SanitizerKind::VLABound)) {
  1953. SanitizerScope SanScope(this);
  1954. llvm::Value *Zero = llvm::Constant::getNullValue(size->getType());
  1955. clang::QualType SEType = sizeExpr->getType();
  1956. llvm::Value *CheckCondition =
  1957. SEType->isSignedIntegerType()
  1958. ? Builder.CreateICmpSGT(size, Zero)
  1959. : Builder.CreateICmpUGT(size, Zero);
  1960. llvm::Constant *StaticArgs[] = {
  1961. EmitCheckSourceLocation(sizeExpr->getBeginLoc()),
  1962. EmitCheckTypeDescriptor(SEType)};
  1963. EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
  1964. SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
  1965. }
  1966. // Always zexting here would be wrong if it weren't
  1967. // undefined behavior to have a negative bound.
  1968. // FIXME: What about when size's type is larger than size_t?
  1969. entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false);
  1970. }
  1971. }
  1972. type = vat->getElementType();
  1973. break;
  1974. }
  1975. case Type::FunctionProto:
  1976. case Type::FunctionNoProto:
  1977. type = cast<FunctionType>(ty)->getReturnType();
  1978. break;
  1979. case Type::Paren:
  1980. case Type::TypeOf:
  1981. case Type::UnaryTransform:
  1982. case Type::Attributed:
  1983. case Type::SubstTemplateTypeParm:
  1984. case Type::MacroQualified:
  1985. // Keep walking after single level desugaring.
  1986. type = type.getSingleStepDesugaredType(getContext());
  1987. break;
  1988. case Type::Typedef:
  1989. case Type::Decltype:
  1990. case Type::Auto:
  1991. case Type::DeducedTemplateSpecialization:
  1992. // Stop walking: nothing to do.
  1993. return;
  1994. case Type::TypeOfExpr:
  1995. // Stop walking: emit typeof expression.
  1996. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1997. return;
  1998. case Type::Atomic:
  1999. type = cast<AtomicType>(ty)->getValueType();
  2000. break;
  2001. case Type::Pipe:
  2002. type = cast<PipeType>(ty)->getElementType();
  2003. break;
  2004. }
  2005. } while (type->isVariablyModifiedType());
  2006. }
  2007. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  2008. if (getContext().getBuiltinVaListType()->isArrayType())
  2009. return EmitPointerWithAlignment(E);
  2010. return EmitLValue(E).getAddress(*this);
  2011. }
  2012. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  2013. return EmitLValue(E).getAddress(*this);
  2014. }
  2015. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  2016. const APValue &Init) {
  2017. assert(Init.hasValue() && "Invalid DeclRefExpr initializer!");
  2018. if (CGDebugInfo *Dbg = getDebugInfo())
  2019. if (CGM.getCodeGenOpts().hasReducedDebugInfo())
  2020. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  2021. }
  2022. CodeGenFunction::PeepholeProtection
  2023. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  2024. // At the moment, the only aggressive peephole we do in IR gen
  2025. // is trunc(zext) folding, but if we add more, we can easily
  2026. // extend this protection.
  2027. if (!rvalue.isScalar()) return PeepholeProtection();
  2028. llvm::Value *value = rvalue.getScalarVal();
  2029. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  2030. // Just make an extra bitcast.
  2031. assert(HaveInsertPoint());
  2032. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  2033. Builder.GetInsertBlock());
  2034. PeepholeProtection protection;
  2035. protection.Inst = inst;
  2036. return protection;
  2037. }
  2038. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  2039. if (!protection.Inst) return;
  2040. // In theory, we could try to duplicate the peepholes now, but whatever.
  2041. protection.Inst->eraseFromParent();
  2042. }
  2043. void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
  2044. QualType Ty, SourceLocation Loc,
  2045. SourceLocation AssumptionLoc,
  2046. llvm::Value *Alignment,
  2047. llvm::Value *OffsetValue) {
  2048. if (Alignment->getType() != IntPtrTy)
  2049. Alignment =
  2050. Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align");
  2051. if (OffsetValue && OffsetValue->getType() != IntPtrTy)
  2052. OffsetValue =
  2053. Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset");
  2054. llvm::Value *TheCheck = nullptr;
  2055. if (SanOpts.has(SanitizerKind::Alignment)) {
  2056. llvm::Value *PtrIntValue =
  2057. Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
  2058. if (OffsetValue) {
  2059. bool IsOffsetZero = false;
  2060. if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
  2061. IsOffsetZero = CI->isZero();
  2062. if (!IsOffsetZero)
  2063. PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr");
  2064. }
  2065. llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0);
  2066. llvm::Value *Mask =
  2067. Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1));
  2068. llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr");
  2069. TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond");
  2070. }
  2071. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  2072. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue);
  2073. if (!SanOpts.has(SanitizerKind::Alignment))
  2074. return;
  2075. emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  2076. OffsetValue, TheCheck, Assumption);
  2077. }
  2078. void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue,
  2079. const Expr *E,
  2080. SourceLocation AssumptionLoc,
  2081. llvm::Value *Alignment,
  2082. llvm::Value *OffsetValue) {
  2083. if (auto *CE = dyn_cast<CastExpr>(E))
  2084. E = CE->getSubExprAsWritten();
  2085. QualType Ty = E->getType();
  2086. SourceLocation Loc = E->getExprLoc();
  2087. emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  2088. OffsetValue);
  2089. }
  2090. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  2091. llvm::Value *AnnotatedVal,
  2092. StringRef AnnotationStr,
  2093. SourceLocation Location,
  2094. const AnnotateAttr *Attr) {
  2095. SmallVector<llvm::Value *, 5> Args = {
  2096. AnnotatedVal,
  2097. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  2098. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  2099. CGM.EmitAnnotationLineNo(Location),
  2100. };
  2101. if (Attr)
  2102. Args.push_back(CGM.EmitAnnotationArgs(Attr));
  2103. return Builder.CreateCall(AnnotationFn, Args);
  2104. }
  2105. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  2106. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  2107. // FIXME We create a new bitcast for every annotation because that's what
  2108. // llvm-gcc was doing.
  2109. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  2110. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  2111. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  2112. I->getAnnotation(), D->getLocation(), I);
  2113. }
  2114. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  2115. Address Addr) {
  2116. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  2117. llvm::Value *V = Addr.getPointer();
  2118. llvm::Type *VTy = V->getType();
  2119. auto *PTy = dyn_cast<llvm::PointerType>(VTy);
  2120. unsigned AS = PTy ? PTy->getAddressSpace() : 0;
  2121. llvm::PointerType *IntrinTy =
  2122. llvm::PointerType::getWithSamePointeeType(CGM.Int8PtrTy, AS);
  2123. llvm::Function *F =
  2124. CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, IntrinTy);
  2125. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  2126. // FIXME Always emit the cast inst so we can differentiate between
  2127. // annotation on the first field of a struct and annotation on the struct
  2128. // itself.
  2129. if (VTy != IntrinTy)
  2130. V = Builder.CreateBitCast(V, IntrinTy);
  2131. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I);
  2132. V = Builder.CreateBitCast(V, VTy);
  2133. }
  2134. return Address(V, Addr.getAlignment());
  2135. }
  2136. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  2137. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  2138. : CGF(CGF) {
  2139. assert(!CGF->IsSanitizerScope);
  2140. CGF->IsSanitizerScope = true;
  2141. }
  2142. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  2143. CGF->IsSanitizerScope = false;
  2144. }
  2145. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  2146. const llvm::Twine &Name,
  2147. llvm::BasicBlock *BB,
  2148. llvm::BasicBlock::iterator InsertPt) const {
  2149. LoopStack.InsertHelper(I);
  2150. if (IsSanitizerScope)
  2151. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  2152. }
  2153. void CGBuilderInserter::InsertHelper(
  2154. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  2155. llvm::BasicBlock::iterator InsertPt) const {
  2156. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  2157. if (CGF)
  2158. CGF->InsertHelper(I, Name, BB, InsertPt);
  2159. }
  2160. // Emits an error if we don't have a valid set of target features for the
  2161. // called function.
  2162. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  2163. const FunctionDecl *TargetDecl) {
  2164. return checkTargetFeatures(E->getBeginLoc(), TargetDecl);
  2165. }
  2166. // Emits an error if we don't have a valid set of target features for the
  2167. // called function.
  2168. void CodeGenFunction::checkTargetFeatures(SourceLocation Loc,
  2169. const FunctionDecl *TargetDecl) {
  2170. // Early exit if this is an indirect call.
  2171. if (!TargetDecl)
  2172. return;
  2173. // Get the current enclosing function if it exists. If it doesn't
  2174. // we can't check the target features anyhow.
  2175. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
  2176. if (!FD)
  2177. return;
  2178. // Grab the required features for the call. For a builtin this is listed in
  2179. // the td file with the default cpu, for an always_inline function this is any
  2180. // listed cpu and any listed features.
  2181. unsigned BuiltinID = TargetDecl->getBuiltinID();
  2182. std::string MissingFeature;
  2183. llvm::StringMap<bool> CallerFeatureMap;
  2184. CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
  2185. if (BuiltinID) {
  2186. StringRef FeatureList(
  2187. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
  2188. // Return if the builtin doesn't have any required features.
  2189. if (FeatureList.empty())
  2190. return;
  2191. assert(!FeatureList.contains(' ') && "Space in feature list");
  2192. TargetFeatures TF(CallerFeatureMap);
  2193. if (!TF.hasRequiredFeatures(FeatureList))
  2194. CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
  2195. << TargetDecl->getDeclName() << FeatureList;
  2196. } else if (!TargetDecl->isMultiVersion() &&
  2197. TargetDecl->hasAttr<TargetAttr>()) {
  2198. // Get the required features for the callee.
  2199. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  2200. ParsedTargetAttr ParsedAttr =
  2201. CGM.getContext().filterFunctionTargetAttrs(TD);
  2202. SmallVector<StringRef, 1> ReqFeatures;
  2203. llvm::StringMap<bool> CalleeFeatureMap;
  2204. CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  2205. for (const auto &F : ParsedAttr.Features) {
  2206. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  2207. ReqFeatures.push_back(StringRef(F).substr(1));
  2208. }
  2209. for (const auto &F : CalleeFeatureMap) {
  2210. // Only positive features are "required".
  2211. if (F.getValue())
  2212. ReqFeatures.push_back(F.getKey());
  2213. }
  2214. if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
  2215. if (!CallerFeatureMap.lookup(Feature)) {
  2216. MissingFeature = Feature.str();
  2217. return false;
  2218. }
  2219. return true;
  2220. }))
  2221. CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
  2222. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  2223. }
  2224. }
  2225. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  2226. if (!CGM.getCodeGenOpts().SanitizeStats)
  2227. return;
  2228. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  2229. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  2230. CGM.getSanStats().create(IRB, SSK);
  2231. }
  2232. llvm::Value *
  2233. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  2234. llvm::Value *Condition = nullptr;
  2235. if (!RO.Conditions.Architecture.empty())
  2236. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  2237. if (!RO.Conditions.Features.empty()) {
  2238. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  2239. Condition =
  2240. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  2241. }
  2242. return Condition;
  2243. }
  2244. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  2245. llvm::Function *Resolver,
  2246. CGBuilderTy &Builder,
  2247. llvm::Function *FuncToReturn,
  2248. bool SupportsIFunc) {
  2249. if (SupportsIFunc) {
  2250. Builder.CreateRet(FuncToReturn);
  2251. return;
  2252. }
  2253. llvm::SmallVector<llvm::Value *, 10> Args;
  2254. llvm::for_each(Resolver->args(),
  2255. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  2256. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  2257. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  2258. if (Resolver->getReturnType()->isVoidTy())
  2259. Builder.CreateRetVoid();
  2260. else
  2261. Builder.CreateRet(Result);
  2262. }
  2263. void CodeGenFunction::EmitMultiVersionResolver(
  2264. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  2265. assert(getContext().getTargetInfo().getTriple().isX86() &&
  2266. "Only implemented for x86 targets");
  2267. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  2268. // Main function's basic block.
  2269. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  2270. Builder.SetInsertPoint(CurBlock);
  2271. EmitX86CpuInit();
  2272. for (const MultiVersionResolverOption &RO : Options) {
  2273. Builder.SetInsertPoint(CurBlock);
  2274. llvm::Value *Condition = FormResolverCondition(RO);
  2275. // The 'default' or 'generic' case.
  2276. if (!Condition) {
  2277. assert(&RO == Options.end() - 1 &&
  2278. "Default or Generic case must be last");
  2279. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  2280. SupportsIFunc);
  2281. return;
  2282. }
  2283. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  2284. CGBuilderTy RetBuilder(*this, RetBlock);
  2285. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  2286. SupportsIFunc);
  2287. CurBlock = createBasicBlock("resolver_else", Resolver);
  2288. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  2289. }
  2290. // If no generic/default, emit an unreachable.
  2291. Builder.SetInsertPoint(CurBlock);
  2292. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2293. TrapCall->setDoesNotReturn();
  2294. TrapCall->setDoesNotThrow();
  2295. Builder.CreateUnreachable();
  2296. Builder.ClearInsertionPoint();
  2297. }
  2298. // Loc - where the diagnostic will point, where in the source code this
  2299. // alignment has failed.
  2300. // SecondaryLoc - if present (will be present if sufficiently different from
  2301. // Loc), the diagnostic will additionally point a "Note:" to this location.
  2302. // It should be the location where the __attribute__((assume_aligned))
  2303. // was written e.g.
  2304. void CodeGenFunction::emitAlignmentAssumptionCheck(
  2305. llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
  2306. SourceLocation SecondaryLoc, llvm::Value *Alignment,
  2307. llvm::Value *OffsetValue, llvm::Value *TheCheck,
  2308. llvm::Instruction *Assumption) {
  2309. assert(Assumption && isa<llvm::CallInst>(Assumption) &&
  2310. cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
  2311. llvm::Intrinsic::getDeclaration(
  2312. Builder.GetInsertBlock()->getParent()->getParent(),
  2313. llvm::Intrinsic::assume) &&
  2314. "Assumption should be a call to llvm.assume().");
  2315. assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
  2316. "Assumption should be the last instruction of the basic block, "
  2317. "since the basic block is still being generated.");
  2318. if (!SanOpts.has(SanitizerKind::Alignment))
  2319. return;
  2320. // Don't check pointers to volatile data. The behavior here is implementation-
  2321. // defined.
  2322. if (!Ty->getPointeeType().isNull() && Ty->getPointeeType().isVolatileQualified())
  2323. return;
  2324. // We need to temorairly remove the assumption so we can insert the
  2325. // sanitizer check before it, else the check will be dropped by optimizations.
  2326. Assumption->removeFromParent();
  2327. {
  2328. SanitizerScope SanScope(this);
  2329. if (!OffsetValue)
  2330. OffsetValue = Builder.getInt1(false); // no offset.
  2331. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
  2332. EmitCheckSourceLocation(SecondaryLoc),
  2333. EmitCheckTypeDescriptor(Ty)};
  2334. llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
  2335. EmitCheckValue(Alignment),
  2336. EmitCheckValue(OffsetValue)};
  2337. EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
  2338. SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
  2339. }
  2340. // We are now in the (new, empty) "cont" basic block.
  2341. // Reintroduce the assumption.
  2342. Builder.Insert(Assumption);
  2343. // FIXME: Assumption still has it's original basic block as it's Parent.
  2344. }
  2345. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2346. if (CGDebugInfo *DI = getDebugInfo())
  2347. return DI->SourceLocToDebugLoc(Location);
  2348. return llvm::DebugLoc();
  2349. }
  2350. llvm::Value *
  2351. CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
  2352. Stmt::Likelihood LH) {
  2353. switch (LH) {
  2354. case Stmt::LH_None:
  2355. return Cond;
  2356. case Stmt::LH_Likely:
  2357. case Stmt::LH_Unlikely:
  2358. // Don't generate llvm.expect on -O0 as the backend won't use it for
  2359. // anything.
  2360. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  2361. return Cond;
  2362. llvm::Type *CondTy = Cond->getType();
  2363. assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean");
  2364. llvm::Function *FnExpect =
  2365. CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy);
  2366. llvm::Value *ExpectedValueOfCond =
  2367. llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely);
  2368. return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
  2369. Cond->getName() + ".expval");
  2370. }
  2371. llvm_unreachable("Unknown Likelihood");
  2372. }