@@ -2028,9 +2028,18 @@ struct DSEState {
20282028 if (!InnerCallee)
20292029 return false ;
20302030 LibFunc Func;
2031+ std::optional<StringRef> ZeroedVariantName = std::nullopt ;
20312032 if (!TLI.getLibFunc (*InnerCallee, Func) || !TLI.has (Func) ||
2032- Func != LibFunc_malloc)
2033- return false ;
2033+ Func != LibFunc_malloc) {
2034+ Attribute Attr = Malloc->getFnAttr (" alloc-variant-zeroed" );
2035+ if (!Attr.isValid ()) {
2036+ return false ;
2037+ }
2038+ ZeroedVariantName = Attr.getValueAsString ();
2039+ if (ZeroedVariantName->empty ())
2040+ return false ;
2041+ }
2042+
20342043 // Gracefully handle malloc with unexpected memory attributes.
20352044 auto *MallocDef = dyn_cast_or_null<MemoryDef>(MSSA.getMemoryAccess (Malloc));
20362045 if (!MallocDef)
@@ -2057,15 +2066,32 @@ struct DSEState {
20572066
20582067 if (Malloc->getOperand (0 ) != MemSet->getLength ())
20592068 return false ;
2060- if (!shouldCreateCalloc (Malloc, MemSet) ||
2061- !DT.dominates (Malloc, MemSet) ||
2069+ if (!shouldCreateCalloc (Malloc, MemSet) || !DT.dominates (Malloc, MemSet) ||
20622070 !memoryIsNotModifiedBetween (Malloc, MemSet, BatchAA, DL, &DT))
20632071 return false ;
20642072 IRBuilder<> IRB (Malloc);
2065- Type *SizeTTy = Malloc->getArgOperand (0 )->getType ();
2066- auto *Calloc =
2067- emitCalloc (ConstantInt::get (SizeTTy, 1 ), Malloc->getArgOperand (0 ), IRB,
2068- TLI, Malloc->getType ()->getPointerAddressSpace ());
2073+ assert (Func == LibFunc_malloc || ZeroedVariantName.has_value ());
2074+ Value *Calloc = nullptr ;
2075+ if (ZeroedVariantName.has_value ()) {
2076+ LLVMContext &Ctx = Malloc->getContext ();
2077+ AttributeList Attr = InnerCallee->getAttributes ();
2078+ AllocFnKind AllocKind =
2079+ Attr.getFnAttr (Attribute::AllocKind).getAllocKind () |
2080+ AllocFnKind::Zeroed;
2081+ Attr =
2082+ Attr.addFnAttribute (Ctx, Attribute::getWithAllocKind (Ctx, AllocKind))
2083+ .removeFnAttribute (Ctx, " alloc-variant-zeroed" );
2084+ FunctionCallee ZeroedVariant = Malloc->getModule ()->getOrInsertFunction (
2085+ *ZeroedVariantName, InnerCallee->getFunctionType (), Attr);
2086+ SmallVector<Value *, 3 > Args;
2087+ Args.append (Malloc->arg_begin (), Malloc->arg_end ());
2088+ Calloc = IRB.CreateCall (ZeroedVariant, Args, *ZeroedVariantName);
2089+ } else {
2090+ Type *SizeTTy = Malloc->getArgOperand (0 )->getType ();
2091+ Calloc =
2092+ emitCalloc (ConstantInt::get (SizeTTy, 1 ), Malloc->getArgOperand (0 ),
2093+ IRB, TLI, Malloc->getType ()->getPointerAddressSpace ());
2094+ }
20692095 if (!Calloc)
20702096 return false ;
20712097
0 commit comments